unis_hrms/tests/test_org_io.py

138 lines
6.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""组织架构导入 / 导出 / 模板,以及人事档案模板下载的鉴权回归。"""
from __future__ import annotations
import io
from openpyxl import Workbook, load_workbook
API = "/api/v1"
XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
def _xlsx(headers: list[str], rows: list[list]) -> bytes:
wb = Workbook()
ws = wb.active
ws.append(headers)
for row in rows:
ws.append(row)
buffer = io.BytesIO()
wb.save(buffer)
return buffer.getvalue()
def _upload(client, path: str, headers: dict, file_headers: list[str], rows: list[list]):
return client.post(
f"{API}{path}", headers=headers,
files={"file": ("import.xlsx", _xlsx(file_headers, rows), XLSX)},
)
def test_employee_import_template_downloads_with_auth(client, admin):
"""回归:模板以前用 window.open,带不上 token,登录态下反而 401。"""
resp = client.get(f"{API}/employees/import-template", headers=admin)
assert resp.status_code == 200, resp.text
assert resp.headers["content-type"].startswith(XLSX)
sheet = load_workbook(io.BytesIO(resp.content)).active
assert "姓名" in [cell.value for cell in sheet[1]]
def test_org_io_endpoints_are_permission_gated(client, admin, hr):
paths = [
"/org/departments/export", "/org/departments/import-template",
"/org/positions/export", "/org/positions/import-template",
"/org/job-levels/export", "/org/job-levels/import-template",
]
for path in paths:
assert client.get(f"{API}{path}", headers=hr).status_code == 403, path
assert client.get(f"{API}{path}", headers=admin).status_code == 200, path
def _dept_nodes(nodes: list[dict]) -> list[dict]:
out: list[dict] = []
for node in nodes:
out.append(node)
out.extend(_dept_nodes(node.get("children") or []))
return out
def test_department_import_export_roundtrip(client, admin):
headers = ["部门编码", "部门名称", "上级部门编码", "部门负责人工号", "成本中心", "排序", "是否启用", "备注"]
# 子部门写在上级前面,验证导入后仍能正确挂接并重算层级
rows = [
["T-IO-002", "测试子部门", "T-IO-001", "EMP00001", "CC-T2", 20, "是", "子部门"],
["T-IO-001", "测试一级部门", "", "", "CC-T1", 10, "是", "一级部门"],
]
try:
resp = _upload(client, "/org/departments/import", admin, headers, rows)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["created"] == 2 and body["failed"] == 0, body
nodes = _dept_nodes(client.get(f"{API}/org/departments/tree", headers=admin).json())
parent = next(n for n in nodes if n["code"] == "T-IO-001")
child = next(n for n in nodes if n["code"] == "T-IO-002")
assert child["parent_id"] == parent["id"]
assert child["level"] == parent["level"] + 1
assert parent["is_parent"] is True
exported = client.get(f"{API}/org/departments/export", headers=admin)
assert exported.status_code == 200
sheet = load_workbook(io.BytesIO(exported.content)).active
codes = {row[0] for row in sheet.iter_rows(min_row=2, values_only=True)}
assert {"T-IO-001", "T-IO-002"} <= codes
# 再次导入:同一批数据应全部走更新,不重复建部门
again = _upload(client, "/org/departments/import", admin, headers, rows)
assert again.status_code == 200
assert again.json()["updated"] == 2 and again.json()["created"] == 0
finally:
remaining = _dept_nodes(client.get(f"{API}/org/departments/tree", headers=admin).json())
for code in ("T-IO-002", "T-IO-001"):
node = next((n for n in remaining if n["code"] == code), None)
if node:
client.delete(f"{API}/org/departments/{node['id']}", headers=admin)
def test_position_and_job_level_import(client, admin):
position_headers = ["职位编码", "职位名称", "职务序列", "排序", "是否启用", "备注"]
level_headers = ["职级编码", "职级名称", "职等", "排序", "是否启用", "备注"]
try:
created = _upload(client, "/org/positions/import", admin, position_headers,
[["T-POS-01", "测试职位", "技术序列", 10, "是", ""]])
assert created.status_code == 200 and created.json()["created"] == 1, created.text
updated = _upload(client, "/org/positions/import", admin, position_headers,
[["T-POS-01", "测试职位改名", "技术序列", 20, "否", ""]])
assert updated.json()["updated"] == 1, updated.text
rows = client.get(f"{API}/org/positions", headers=admin,
params={"keyword": "T-POS-01"}).json()["items"]
assert rows and rows[0]["name"] == "测试职位改名" and rows[0]["is_active"] is False
created = _upload(client, "/org/job-levels/import", admin, level_headers,
[["T-JL-01", "T5", 5, 10, "是", ""]])
assert created.status_code == 200 and created.json()["created"] == 1, created.text
levels = client.get(f"{API}/org/job-levels", headers=admin,
params={"keyword": "T-JL-01"}).json()["items"]
assert levels and levels[0]["grade"] == 5
finally:
for path, code in (("/org/positions", "T-POS-01"), ("/org/job-levels", "T-JL-01")):
items = client.get(f"{API}{path}", headers=admin, params={"keyword": code}).json()["items"]
for item in items:
client.delete(f"{API}{path}/{item['id']}", headers=admin)
def test_csv_import_is_supported(client, admin):
content = "职位编码,职位名称,职务序列,排序,是否启用,备注\nT-CSV-01,CSV职位,技术序列,10,是,\n".encode("utf-8-sig")
try:
resp = client.post(
f"{API}/org/positions/import", headers=admin,
files={"file": ("positions.csv", content, "text/csv")},
)
assert resp.status_code == 200, resp.text
assert resp.json()["created"] == 1, resp.text
finally:
items = client.get(f"{API}/org/positions", headers=admin,
params={"keyword": "T-CSV-01"}).json()["items"]
for item in items:
client.delete(f"{API}/org/positions/{item['id']}", headers=admin)