Files
37duAutomation/libs/hr_sdk/hr_sdk/_selftest.py
T
puddy 9873eb1963 restore: 恢复 11-06~11-09 本地未提交改动
- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto
- controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图
- electron-shell: 插件同步、注册表、runner 调整
- plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新
- tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
2026-11-09 17:27:10 +08:00

460 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""离线自测:不联网、不读生产 cookie、不启动浏览器/WS。
安装时由 ``sdk.json.selftest`` 声明,客户端冒烟会执行 ``main()``;
开发态也可直接跑:``python -m hr_sdk._selftest``。
"""
from __future__ import annotations
import hashlib
import json
import os
import tempfile
from datetime import date
from . import attach, attendance, auth, contract, imports, seal, shift, workflow
from . import client as client_mod
from . import config, errors, export, ledger, org, query, roster, session
_CHECKS = 0
def _ok(cond, message: str) -> None:
global _CHECKS
_CHECKS += 1
if not cond:
raise AssertionError(message)
def _eq(actual, expected, message: str) -> None:
_ok(actual == expected, f"{message}:期望 {expected!r},实际 {actual!r}")
def _raises(exc_type, fn, message: str) -> None:
try:
fn()
except exc_type:
_ok(True, message)
return
except Exception as other: # noqa: BLE001
raise AssertionError(f"{message}:期望 {exc_type.__name__},实际 {type(other).__name__}")
raise AssertionError(f"{message}:未抛出 {exc_type.__name__}")
# ==================== 查询条件加密 ====================
#: 与既有实现(workflows/share/roster_export_api.py)逐字节一致的回归锚点
_EXPECT_LEN = 758
_EXPECT_SHA = "eb63099b0c8e0c52a040553c20f1c6d069cd72b2e90816035fbfcf69a60f6842"
def test_query() -> None:
_eq(len(query.CUSTOM_CHARS), 65, "自定义字符表长度(64 字符 + 填充位)")
encoded = query.encode(roster.in_service_conditions())
_eq(len(encoded), _EXPECT_LEN, "在职条件加密串长度")
_eq(hashlib.sha256(encoded.encode()).hexdigest(), _EXPECT_SHA,
"在职条件加密串与既有实现一致")
conds = query.date_range("`x.y`", "2026-01-01", "2026-01-31")
_eq(len(conds), 2, "日期区间条件条数")
_eq(conds[0]["leftBracket"], "(", "日期区间左括号")
_eq(conds[1]["rightBracket"], ")", "日期区间右括号")
_eq(conds[0]["inputType"], "date", "日期区间 inputType")
single = query.condition("`a.b`", "in", "1", query_text="1", input_type="select")
_eq(set(single), {"queryField", "leftBracket", "queryType", "queryValue",
"queryText", "rightBracket", "logic", "inputType"}, "条件字段齐全")
_eq(single["logic"], "AND", "默认逻辑 AND")
# ==================== 公共入参 ====================
def test_config() -> None:
params = config.base_params("员工花名册", "assemble-hr_staff_base", roster.ROSTER_ID)
_ok(len(params) >= 35, "公共入参字段数")
_eq(params["rosterId"], roster.ROSTER_ID, "rosterId 注入")
_eq(params["tableId"], "assemble-hr_staff_base", "tableId 注入")
_eq(params["menuName"], "员工花名册", "menuName 注入")
_ok(all(isinstance(v, str) for v in params.values()), "入参值全部为字符串")
with_user = config.base_params("m", "t", "r", user={"userId": "u1", "staffId": "s1",
"roleIds": "r1"})
_eq((with_user["currentUserId"], with_user["currentStaffId"], with_user["currentRoleIds"]),
("u1", "s1", "r1"), "身份覆盖生效")
_eq(config.base_params("m", "t", "r", baseHrefPath="x")["baseHrefPath"], "x", "任意覆盖项")
_ok(config.cookies_file().endswith(".json"), "cookies 路径是文件")
# ==================== 会话 ====================
def test_session() -> None:
_ok(session.looks_like_login_page("<!DOCTYPE html><html>"), "HTML 判定为登录页")
_ok(not session.looks_like_login_page('{"state":"1"}'), "JSON 判定为正常")
_raises(errors.ConfigError,
lambda: session.session_from_cookies(r"Z:\not-exist\hr_cookies.json"),
"cookie 文件缺失抛 ConfigError")
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "c.json")
with open(path, "w", encoding="utf-8") as fp:
json.dump([{"name": "a", "value": "1", "domain": ".37du.co", "path": "/"},
{"name": "b", "value": "2", "domain": ".other.com", "path": "/"}], fp)
sess = session.session_from_cookies(path)
_eq(len(sess.cookies), 1, "仅保留目标域 cookies")
# ==================== 客户端 ====================
class _Resp:
def __init__(self, text: str, status: int = 200):
self.text = text
self.status_code = status
self.content = text.encode("utf-8")
def json(self):
return json.loads(self.text)
class _FakeSession:
cookies: list = []
def get(self, url, **kwargs): # noqa: D401
return _Resp('{"state":"1"}')
def post(self, url, **kwargs):
return _Resp('{"state":"1"}')
def test_client() -> None:
hr = client_mod.HrClient(_FakeSession(), log=lambda m: None)
_eq(hr.as_json(_Resp('{"state": "1"}')), {"state": "1"}, "JSON 解析")
_raises(errors.SessionExpiredError, lambda: hr.as_json(_Resp("<html>login</html>")),
"HTML 响应抛登录态失效")
_raises(errors.ApiError, lambda: hr.as_json(_Resp("{oops")), "坏 JSON 抛 ApiError")
pages = {1: ([{"a": 1}, {"a": 2}], True), 2: ([{"a": 3}], False)}
rows = hr.paginate(lambda no, size: pages[no], page_size=2, sleep=0)
_eq(len(rows), 3, "分页合并 3 行")
_eq(rows[-1]["a"], 3, "分页顺序保持")
_eq(hr.check_state({"state": "1", "datas": []})["state"], "1", "state=1 通过")
_raises(errors.SessionExpiredError,
lambda: hr.check_state({"state": "0", "meg": "会话过期,请重新登录!"}),
"服务端会话过期 → 登录态失效")
_raises(errors.ApiError,
lambda: hr.check_state({"state": "0", "meg": "参数错误"}),
"业务错误 → ApiError")
_raises(errors.ConfigError, lambda: client_mod.HrClient(None), "空会话抛 ConfigError")
# ==================== 导出机制 ====================
def test_export() -> None:
base = config.base_params("m", "t", "r")
with_cond = export.build_params(base, conditions=roster.in_service_conditions(),
template="员工基础信息", filters="a.b,c.d")
_eq(with_cond["exportConfig"],
'{"exportName":"员工基础信息","exportFilters":"a.b,c.d"}', "导出配置 JSON")
_ok(with_cond["commonQuery"].startswith("BH"), "条件加密注入 commonQuery")
_ok(int(with_cond["_t"]) > 1_000_000_000_000, "时间戳为毫秒")
_raises(errors.ConfigError,
lambda: export.build_params(base, template="t", filters=""),
"有模板无字段串抛 ConfigError")
_eq(export.build_params(base, conditions=None).get("commonQuery"), "",
"无条件时 commonQuery 保持空串")
# ==================== 业务接口(纯构造部分) ====================
class _DummyClient:
def __init__(self):
self.log = lambda msg: None
def test_roster() -> None:
_eq(len(roster.in_service_conditions()), 2, "在职条件 2 条")
_eq(len(roster.leave_conditions("2026-09-01", "2026-10-31")), 4, "离职条件 4 条")
_eq(roster.leave_range(date(2026, 11, 9)), ("2026-10-01", "2026-11-09"), "离职默认范围")
# TTL 缓存命中:不触碰网络(DummyClient 无 session)
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "花名册.xlsx")
with open(path, "wb") as fp:
fp.write(b"x")
_eq(roster.export(_DummyClient(), output=path, ttl=900), os.path.abspath(path),
"TTL 缓存命中直接复用")
def test_ledger() -> None:
_eq(ledger.recent_range(date(2026, 11, 9), 30), ("2026-10-11", "2026-11-09"),
"近 30 天范围")
_eq(ledger.recent_range(date(2026, 3, 1), 1), ("2026-03-01", "2026-03-01"), "单日范围")
_ok(ledger.TRANSFER_ROSTER_ID != ledger.PRE_ENTRY_ROSTER_ID, "两个台账 rosterId 不同")
_ok(ledger.TRANSFER_EXPORT_URL.endswith("exportCommonListData.mc"), "调动导出地址")
_ok(ledger.PRE_ENTRY_EXPORT_URL.endswith("exportCommonListData.mc"), "预入职导出地址")
def test_org() -> None:
conds = org.conditions()
_eq(len(conds), 1, "组织条件 1 条")
_eq(conds[0]["queryType"], "in", "组织条件类型")
_ok(org.ORG_QUERY_URL.endswith("queryRealTimeData.mc"), "组织查询地址")
def test_workflow() -> None:
data = {"jsonList": [
{"title": "请假-张三", "taskId": "t1", "businessKey": "b1",
"processId": "p1", "formId": "f1", "createTime": "2026-11-01"},
{"title": "缺字段行"},
]}
docs = workflow.parse_docs(data)
_eq(len(docs), 1, "缺 taskId/businessKey 的行被跳过")
_eq(docs[0]["taskId"], "t1", "taskId 解析")
_ok("reqType=WAIT" in docs[0]["detail_url"], "详情地址带待办视图参数")
_ok(workflow.detail_url(task_id="t1").endswith("systemId="), "detail_url 拼接")
_ok(workflow.WE_PROCESS_QUERY_URL.endswith("getProcessAndData"), "待办查询地址")
def test_attendance() -> None:
_eq(len(attendance.DAILY_STATUSES), 4, "逐日考勤四种状态")
ok = attendance._check_success({"success": True, "code": 200, "data": {}}, "x")
_eq(str(ok.get("code")), "200", "success/code 信封通过")
_raises(errors.SessionExpiredError,
lambda: attendance._check_success(
{"success": False, "code": 500, "message": "会话过期"}, "x"),
"会话过期 → 登录态失效")
_raises(errors.ApiError,
lambda: attendance._check_success(
{"success": False, "code": 500, "message": "参数错误"}, "x"),
"业务失败 → ApiError")
def test_shift() -> None:
_eq(shift.day_shift([{"2026-11-09_team_name": "早班"}], "2026-11-09"), "早班",
"当日排班取值")
_eq(shift.day_shift([{"2026-11-09_team_name": ""}], "2026-11-09"), "",
"空排班返回空串")
_eq(shift.day_shift([], "2026-11-09"), "", "无记录返回空串")
_ok(shift.WORK_DATE_QUERY_URL.endswith("rf_s_kq_work_date_query/redApiExec.mc"),
"部门排班地址")
def test_seal() -> None:
_eq(seal.normalize_month("202610"), "2026-10", "YYYYMM 归一")
_eq(seal.normalize_month("2026-10"), "2026-10", "YYYY-MM 保持")
_eq(len(seal.normalize_month()), 7, "缺省取上月(YYYY-MM)")
_ok(seal.SEAL_URL.endswith("getPageAjaxList.mc"), "封存查询地址")
def test_attach() -> None:
headers = {"Content-Disposition": 'attachment; filename="合同.pdf"'}
_eq(attach._filename_from_headers(headers, "x.bin"), "合同.pdf", "文件名解析")
_eq(attach._filename_from_headers({}, "f.bin"), "f.bin", "无头信息用兜底名")
_raises(errors.ConfigError, lambda: attach.download(_DummyClient(), "", "d"),
"空 file_id 抛 ConfigError")
def test_contract() -> None:
_eq(len(contract.ROSTERS), 2, "两个合同台账")
_raises(errors.ConfigError,
lambda: contract.export(_DummyClient(), tag="不存在"),
"未知合同台账抛 ConfigError")
_raises(errors.ConfigError,
lambda: contract.export(_DummyClient(), tag="生效中"),
"模板与字段串都没给抛 ConfigError")
def test_export_pipeline() -> None:
"""桩掉 export_table,验证「参数构造 → 调用」链路(防模块名被同名函数遮蔽)。"""
calls = {}
original = export.export_table
def _stub(client, **kwargs):
calls.clear()
calls.update(kwargs)
return kwargs["output_path"]
export.export_table = _stub
try:
with tempfile.TemporaryDirectory() as tmp:
path = roster.export_one(_DummyClient(), "在职", filters="a.b,c.d",
output=os.path.join(tmp, "在职.xlsx"))
_ok(path.endswith("在职.xlsx"), "花名册单状态导出链路")
_ok("员工基础信息" in calls["params"]["exportConfig"], "导出参数带模板名")
_ok(bool(calls["params"]["commonQuery"]), "导出参数带加密条件")
path = contract.export(_DummyClient(), "生效中", filters="a.b",
output=os.path.join(tmp, "合同.xlsx"))
_ok(path.endswith("合同.xlsx"), "合同台账导出链路")
_eq(calls["params"]["rosterId"], contract.ROSTERS["生效中"], "合同 rosterId")
finally:
export.export_table = original
class _ImportResp:
def __init__(self, text: str):
self.text = text
self.status_code = 200
self.content = text.encode("utf-8")
def json(self):
return json.loads(self.text)
class _ImportStubClient:
"""导入链路用的假客户端:只回放固定配置与表头校验响应,不联网。"""
def __init__(self) -> None:
self.log = lambda msg: None
def get(self, url, headers=None, timeout=None):
conf = {
"id": "12eecb13-78b0-4fac-a865-10c3043a33e1",
"title": "商业保险增员导入",
"maxNum": 500,
"fieldJson": json.dumps([{"columnName": "a", "columnDisplay": "姓名"},
{"columnName": "b", "columnDisplay": "工号"}],
ensure_ascii=False),
}
return _ImportResp("var hrModuleBaseImport = " + json.dumps(conf, ensure_ascii=False)
+ ";")
def post_files(self, url, files=None, data=None, timeout=None):
return _ImportResp(json.dumps({
"state": "1",
"result": [{"excelColName": "姓名", "excelColNum": 1},
{"excelColName": "工号", "excelColNum": 2}],
}, ensure_ascii=False))
def as_json(self, resp, label=""):
return json.loads(resp.text)
def check_state(self, data, label=""):
return data
def test_imports() -> None:
_eq(imports.menu_info("add")["label"], "增员导入", "增员菜单")
_ok(imports.menu_info("SUB")["import_id"].startswith("22e"), "减员菜单(大小写不敏感)")
_raises(errors.ConfigError, lambda: imports.menu_info("x"), "未知导入类型抛 ConfigError")
fields = [{"columnName": "a", "columnDisplay": "姓名"},
{"columnName": "b", "columnDisplay": "工号"}]
titles = [{"excelColName": "姓名", "excelColNum": 1},
{"excelColName": "工号", "excelColNum": 2}]
title_list, matched = imports.match_titles(fields, titles)
_eq(matched, 2, "表头匹配列数")
_eq(title_list[0]["excelColNum"], 1, "回填 excelColNum")
_eq(len(imports.field_list({"fieldJson": '[{"columnName":"a"}]'})), 1, "fieldJson 解析")
text = '{"姓名":"张三","备注":"a&b=c"}'
_eq(query.decode_raw(query.encode_raw(text)), text, "titleList 编码/解码互逆")
from openpyxl import Workbook
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "import.xlsx")
book = Workbook()
sheet = book.active
sheet.append(["商业保险增员导入"])
sheet.append(["姓名", "工号"])
sheet.append([])
sheet.append([1, "37000001"])
sheet.append([2, "37000002"])
sheet.append(["", "37000003"]) # A 列空 → 不计入
book.save(path)
_eq(imports.read_codes(path), ["37000001", "37000002"], "读导入文件工号")
stub = _ImportStubClient()
res = imports.upload(stub, path, "add")
_eq(res["dry_run"], True, "默认 dry_run")
_eq(res["applied"], False, "dry_run 不提交写库")
_eq(res["ok"], True, "dry_run 校验通过")
_eq(res["matched"], 2, "dry_run 匹配列数")
_eq(res["fields"], 2, "模板字段数")
_raises(errors.ConfigError,
lambda: imports.upload(stub, os.path.join(tmp, "none.xlsx")),
"文件缺失抛 ConfigError")
def test_auth() -> None:
import base64 as _b64
raw = _b64.b64decode(auth.aes_encrypt_password("123456"))
_eq(len(raw) % 16, 0, "AES 密文按 16 字节对齐")
from Crypto.Cipher import AES
plain = AES.new(auth.AES_KEY, AES.MODE_ECB).decrypt(raw)
_ok(plain.startswith(b"123456"), "AES 回解得到原文")
_ok(auth.CAPTCHA_GET_URL.endswith("image.mob"), "滑块图地址")
_ok(auth.LOGIN_POST_URL.endswith("/PW"), "登录提交地址")
_eq(auth.solve_distance({"shade": None, "origin": None, "cutout": None}),
(None, "无法定位"), "缺图时无法定位缺口")
old_user = os.environ.pop("hr_login_username", None)
old_pwd = os.environ.pop("hr_login_password", None)
try:
with tempfile.TemporaryDirectory() as tmp:
res = auth.ensure_login(cookie_path=os.path.join(tmp, "none.json"))
_eq(res["success"], False, "无凭证时 ensure_login 失败")
_eq(res["relogin"], False, "无凭证时不标记 relogin")
_raises(errors.ConfigError, lambda: auth.login("", ""), "空账号抛 ConfigError")
finally:
if old_user is not None:
os.environ["hr_login_username"] = old_user
if old_pwd is not None:
os.environ["hr_login_password"] = old_pwd
_eq(config.cookies_file(account="alice").split(os.sep)[-2], "alice",
"cookie 按账号隔离目录")
# ==================== 入口 ====================
def main() -> int:
from . import __version__
tests = [
("query", test_query),
("config", test_config),
("session", test_session),
("client", test_client),
("export", test_export),
("roster", test_roster),
("ledger", test_ledger),
("org", test_org),
("workflow", test_workflow),
("attendance", test_attendance),
("shift", test_shift),
("seal", test_seal),
("attach", test_attach),
("contract", test_contract),
("export_pipeline", test_export_pipeline),
("imports", test_imports),
("auth", test_auth),
]
failed = 0
try:
_eq(__version__, "0.1.3", "包版本与 sdk.json 一致")
for name, fn in tests:
try:
fn()
print(f"[ok] {name}")
except AssertionError as exc:
failed += 1
print(f"[FAIL] {name}: {exc}")
except Exception as exc: # noqa: BLE001
failed += 1
print(f"[ERROR] {name}: {type(exc).__name__}: {exc}")
finally:
print(f"自测完成:{_CHECKS} 项断言,失败 {failed} 组")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())