test(ci): 新增 pytest 单元测试与最小 CI 门禁

tools/ci_check.py 统一本地与流水线检查:全量 Python 语法编译(py_compile 不落 __pycache__)+ tests/unit 纯逻辑单测,可选 --frontend 追加壳前端构建;.gitlab-ci.yml 在 Windows runner 上复用同一脚本;requirements-dev.txt / pytest.ini 固化测试依赖与用例路径。单测覆盖 XQ0033/0034/0035/0037/0045/0048 的纯逻辑部分。
This commit is contained in:
2026-11-11 12:48:37 +08:00
parent 88e51c3061
commit 6c1161fd54
12 changed files with 928 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
# 最小 CI:全量 Python 语法编译 + 插件纯逻辑单测。
# 执行环境:Windows runner(项目插件依赖 Windows/COM 场景,单测本身跨平台)。
# 本地等价命令:.venv\Scripts\python.exe tools/ci_check.py [--frontend]
# 前端构建未纳入默认流水线(需 runner 预装 Node/pnpm 与 node_modules),
# 可在本机用 --frontend 单独验证。
stages:
- check
python-check:
stage: check
interruptible: true
script:
- python -m venv .venv
- .venv/Scripts/python.exe -m pip install --quiet --upgrade pip
- .venv/Scripts/python.exe -m pip install --quiet pytest==9.2.0 openpyxl requests pandas
- .venv/Scripts/python.exe tools/ci_check.py
cache:
key: pip-$CI_COMMIT_REF_SLUG
paths:
- .venv/
+7
View File
@@ -0,0 +1,7 @@
[pytest]
# 只收集纯逻辑单测目录:tests/ 根下是历史探针脚本(依赖浏览器/真实环境),不能被自动收集
testpaths = tests/unit
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts = -q
+3
View File
@@ -0,0 +1,3 @@
# 开发/测试依赖(不参与执行机便携环境包构建,勿合并进 requirements.txt)
-r requirements.txt
pytest==9.2.0
View File
+83
View File
@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
"""插件纯逻辑单测的模块加载器。
插件目录名是中文且带空格,不是合法 Python 包名,无法直接 import。这里把插件目录
注册成英文别名包(如 ``xq0033``),保持插件内部的相对导入(``from .. import config``)
原样生效,不复制、不修改插件源码。
两种加载方式:
- ``plugins.module(alias, submodule)``:加载指定子模块,父包只注册路径、不执行顶层
``__init__.py``,避免把浏览器/登录等重依赖拖进单测;
- ``plugins.package(alias)``:真实执行插件 ``__init__.py``(仅测其内部纯函数时才需要)。
"""
import importlib
import importlib.machinery
import importlib.util
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
PLUGIN_DIR = ROOT / "plugins" / "XQ0001-0100"
# 插件顶层 __init__ 依赖执行机壳内置运行时(webhost.backend.plugins.base)
SHELL_PY = ROOT / "desktop" / "electron-shell" / "python"
if str(SHELL_PY) not in sys.path:
sys.path.insert(0, str(SHELL_PY))
# 别名 -> 插件源码目录
ALIASES = {
"xq0033": "XQ0033 门店管理及服务岗出勤积分更新",
"xq0034": "XQ0034 续签电子签",
"xq0035": "XQ0035 服务岗转正不通过电子签(离职+入职)",
"xq0037": "XQ0037 调动改签离职电子签",
"xq0045": "XQ0045_XQ0046 金色印象通联数据导出",
"xq0048": "XQ0048 CRM数据导出",
}
def _plugin_root(alias):
if alias not in ALIASES:
raise KeyError(f"未登记插件别名:{alias}")
return PLUGIN_DIR / ALIASES[alias]
def _register_namespace_package(alias):
"""注册只有 __path__ 的空壳包:子模块可相对导入,但不执行插件顶层 __init__。"""
existing = sys.modules.get(alias)
if existing is not None and not getattr(existing, "__file__", None):
return existing
if existing is not None:
return existing
root = _plugin_root(alias)
spec = importlib.machinery.ModuleSpec(alias, loader=None, is_package=True)
spec.submodule_search_locations = [str(root)]
mod = importlib.util.module_from_spec(spec)
sys.modules[alias] = mod
return mod
class PluginLoader:
def module(self, alias, submodule):
"""加载 ``<alias>.<submodule>``,如 module("xq0033", "logic.rejoin_gap")。"""
_register_namespace_package(alias)
return importlib.import_module(f"{alias}.{submodule}")
def package(self, alias):
"""真实执行插件顶层 ``__init__.py`` 并返回包对象(模块级缓存)。"""
existing = sys.modules.get(alias)
if existing is not None and getattr(existing, "__file__", None):
return existing
root = _plugin_root(alias)
spec = importlib.util.spec_from_file_location(
alias, str(root / "__init__.py"), submodule_search_locations=[str(root)])
mod = importlib.util.module_from_spec(spec)
sys.modules[alias] = mod
spec.loader.exec_module(mod)
return mod
@pytest.fixture(scope="session")
def plugins():
return PluginLoader()
+169
View File
@@ -0,0 +1,169 @@
# -*- coding: utf-8 -*-
"""XQ0033 离职当月再入职「不操作段」与日期滚动口径单测。
口径来源(插件 docstring / 项目记忆):
- 台账工号(同工号再入职):[本月1日, 再入职日) 不导入、不删除;
- 历史工号(换工号再入职):整月不操作,且必须「工号+姓名」同时匹配;
- 所有月份窗口锚定积分日期 T-2 所在月;
- 跳天补漏只补 T-2 所在月、且早于 T-2 的日期。
"""
from datetime import date, timedelta
import pytest
@pytest.fixture(scope="module")
def mod(plugins):
return plugins.module("xq0033", "logic.rejoin_gap")
@pytest.fixture(scope="module")
def pkg(plugins):
return plugins.package("xq0033")
@pytest.fixture
def keys(mod):
cfg = mod.config
return {
"code": "hr_staff_base.base_code",
"name": "hr_staff_base.staff_name",
"leave": f"{cfg.REJOIN_FIELD_PREFIX}.leave_date",
"join": f"{cfg.REJOIN_FIELD_PREFIX}.join_date",
}
def _row(keys, code, name, leave, join):
return {keys["code"]: code, keys["name"]: name,
keys["leave"]: leave, keys["join"]: join}
def _emp(code, name):
"""「员工信息9列」元组(索引 0=工号、8=姓名),与报表行结构一致。"""
return (code, "", "", "", "", "", "", "", name)
# ---------------- RejoinGuard:本月再入职 ----------------
def test_this_month_backfills_noop_before_join(mod, keys):
g = mod.RejoinGuard([_row(keys, "37037921", "何蕾", "2026-10-01", "2026-10-18")],
anchor=date(2026, 10, 20))
assert g.invalid_until("37037921", "何蕾") == 18
assert g.is_invalid("37037921", "何蕾", 1) is True
assert g.is_invalid("37037921", "何蕾", 17) is True
# 再入职日当天起恢复正常(属于新周期)
assert g.is_invalid("37037921", "何蕾", 18) is False
def test_join_next_month_marks_whole_month(mod, keys):
g = mod.RejoinGuard([_row(keys, "37037921", "何蕾", "2026-10-30", "2026-11-18")],
anchor=date(2026, 10, 20))
assert g.invalid_until("37037921", "何蕾") == mod._WHOLE_MONTH
assert g.is_invalid("37037921", "何蕾", 17) is True
assert g.is_invalid("37037921", "何蕾", 31) is True
def test_join_before_this_month_has_no_gap(mod, keys):
g = mod.RejoinGuard([_row(keys, "37037921", "何蕾", "2026-08-01", "2026-09-10")],
anchor=date(2026, 10, 20))
assert g.invalid_until("37037921", "何蕾") == 1
assert g.is_invalid("37037921", "何蕾", 1) is False
def test_anchor_month_follows_t_minus_2_not_run_day(mod, keys):
"""月初运行(T-2 落在上月)时,不操作段按 T-2 所在月计算。"""
g = mod.RejoinGuard([_row(keys, "37037921", "何蕾", "2026-09-30", "2026-10-18")],
anchor=date(2026, 10, 31))
assert g.invalid_until("37037921", "何蕾") == 18
# ---------------- RejoinGuard:历史工号(换工号再入职) ----------------
def test_old_code_requires_same_name(mod, keys):
g = mod.RejoinGuard([_row(keys, "37037921", "何蕾", "2026-09-30", "2026-10-18")],
old_codes_map={"37037921": ["37031111"]},
anchor=date(2026, 10, 20))
assert g.invalid_until("37031111", "何蕾") == mod._WHOLE_MONTH
# 工号可能被复用:姓名不一致时不跳过,避免误伤他人积分
assert g.invalid_until("37031111", "张三") is None
assert g.is_invalid("37031111", "张三", 1) is False
def test_missing_fields_are_ignored(mod, keys):
g = mod.RejoinGuard([
_row(keys, "", "何蕾", "2026-10-01", "2026-10-18"), # 无工号
_row(keys, "37037921", "何蕾", "", "2026-10-18"), # 无离职日
_row(keys, "37037922", "王五", "2026-10-01", "bad-date"), # 再入职日异常
], anchor=date(2026, 10, 20))
assert bool(g) is False
assert g.describe() == []
# ---------------- RejoinGuard:allow / describe ----------------
def test_allow_filters_import_and_delete_rows(mod, keys):
g = mod.RejoinGuard([_row(keys, "37037921", "何蕾", "2026-10-01", "2026-10-18")],
anchor=date(2026, 10, 20))
rows = [
(_emp("37037921", "何蕾"), date(2026, 10, 3)), # 不操作段:剔除
(_emp("37037921", "何蕾"), date(2026, 10, 18)), # 新周期:保留
(_emp("37037922", "王五"), date(2026, 10, 3)), # 不在名单:保留
]
kept = g.allow(rows)
assert [r[1] for r in kept] == [date(2026, 10, 18), date(2026, 10, 3)]
def test_allow_returns_input_when_no_rejoin(mod, keys):
g = mod.RejoinGuard([], anchor=date(2026, 10, 20))
rows = [(_emp("37037921", "何蕾"), date(2026, 10, 3))]
assert g.allow(rows) is rows
def test_describe_text(mod, keys):
g = mod.RejoinGuard([_row(keys, "37037921", "何蕾", "2026-10-01", "2026-10-18")],
old_codes_map={"37037921": ["37031111"]},
anchor=date(2026, 10, 20))
text = "\n".join(g.describe())
assert "何蕾(37037921) 再入职 10-18 → 1~17 日不导入/不删除" in text
assert "37031111" in text and "整月" in text
# ---------------- 日期滚动:跳天补漏 ----------------
def test_gap_days_none_or_covered(pkg):
t2 = date(2026, 10, 20)
assert pkg._gap_days(t2, None) == []
assert pkg._gap_days(t2, t2) == []
assert pkg._gap_days(t2, date(2026, 10, 19)) == []
def test_gap_days_fills_skipped_days(pkg):
assert pkg._gap_days(date(2026, 10, 20), date(2026, 10, 10)) == [
date(2026, 10, 11) + timedelta(days=i) for i in range(9)
]
def test_gap_days_clamped_to_t2_month(pkg):
"""跨月时不补上月日期:月初 T-2 属上月,窗口取 T-2 所在月。"""
assert pkg._gap_days(date(2026, 10, 5), date(2026, 9, 28)) == [
date(2026, 10, 1), date(2026, 10, 2), date(2026, 10, 3), date(2026, 10, 4)
]
# T-2 已进入新月份、上轮在上月末 → 无同月可补日期
assert pkg._gap_days(date(2026, 11, 1), date(2026, 10, 30)) == []
# ---------------- 日期滚动:跨月首轮识别 ----------------
def test_is_new_month_prefers_file_month(pkg):
assert pkg._is_new_month((2026, 10), None, date(2026, 11, 5)) is True
assert pkg._is_new_month((2026, 11), date(2026, 10, 30), date(2026, 11, 5)) is False
def test_is_new_month_falls_back_to_covered_until(pkg):
assert pkg._is_new_month(None, date(2026, 10, 30), date(2026, 11, 5)) is True
assert pkg._is_new_month(None, date(2026, 11, 1), date(2026, 11, 5)) is False
def test_is_new_month_unknown_keeps_rolling(pkg):
"""两处都拿不到时按「未跨月」处理,不做无依据的清空。"""
assert pkg._is_new_month(None, None, date(2026, 11, 5)) is False
+100
View File
@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""XQ0034 续签期限复算与文本归一单测。
核心口径(2026-11-10 用户给出 AI 表公式):
新合同期限 = ROUND(DATEDIF(旧合同到期日, 续签截止日+1, "M"), 0),
DATEDIF 与 Excel 一致:day(end) < day(start) 少算一个月。
此前「取最近整月」口径会多算 1 个月,这些用例用于锁死回归。
"""
from datetime import date
import pytest
@pytest.fixture(scope="module")
def mod(plugins):
return plugins.module("xq0034", "data.renewal_esign")
# ---------------- DATEDIF 语义 ----------------
def test_datedif_full_months(mod):
assert mod._datedif_months(date(2026, 1, 1), date(2026, 2, 1)) == 1
assert mod._datedif_months(date(2026, 1, 1), date(2027, 1, 1)) == 12
def test_datedif_month_end_short_month(mod):
"""2026-01-31 → 2026-02-28:日不足,不足一个完整月(Excel 语义为 0)。"""
assert mod._datedif_months(date(2026, 1, 31), date(2026, 2, 28)) == 0
def test_datedif_missing_input(mod):
assert mod._datedif_months(None, date(2026, 1, 1)) is None
assert mod._datedif_months(date(2026, 1, 1), None) is None
# ---------------- 新合同期限复算 ----------------
def test_renew_months_uses_old_expire_as_base(mod):
"""刘瑶案例:旧合同到期 2026-10-31、续签截止 2027-10-31 → 12 个月。"""
n, why = mod._renew_months(date(2026, 11, 1), date(2027, 10, 31), date(2026, 10, 31))
assert n == 12
assert "DATEDIF(2026-10-31, 2027-11-01)=12" in why
def test_renew_months_falls_back_to_start_minus_one(mod):
n, _ = mod._renew_months(date(2026, 11, 1), date(2027, 10, 31), None)
assert n == 12
def test_renew_months_rejects_end_not_after_base(mod):
n, why = mod._renew_months(date(2026, 11, 1), date(2026, 10, 1), date(2026, 10, 31))
assert n is None
assert "不晚于旧合同到期日" in why
def test_renew_months_requires_dates(mod):
n, why = mod._renew_months(None, date(2027, 10, 31), None)
assert n is None
assert why == "续签开始/截止日期为空"
# ---------------- 字段归一 ----------------
@pytest.mark.parametrize("raw, expect", [
("12.00", "12"), ("12", "12"), (12.0, "12"), ("12.5", "12.5"),
("", ""), (None, ""), ("abc", ""),
])
def test_deadline_code(mod, raw, expect):
assert mod._deadline_code(raw) == expect
@pytest.mark.parametrize("raw, expect", [
(123, "123"), ("123.0", "123"), ("00123", "123"), (" 37037921 ", "37037921"),
("A001", "A001"), (None, ""),
])
def test_norm_code(mod, raw, expect):
assert mod._norm_code(raw) == expect
@pytest.mark.parametrize("raw, expect", [
("+86 138-0000-0000", "13800000000"),
("13800000000", "13800000000"), # 全角数字
("138 0000 0000", "13800000000"),
("", ""), (None, ""),
])
def test_norm_phone(mod, raw, expect):
assert mod._norm_phone(raw) == expect
@pytest.mark.parametrize("raw, ok", [
("13800000000", True), ("138-0000-0000", False), # 未归一 -> 交给 _norm_phone 后再校验
("12800000000", False), ("1380000000", False), ("", False),
])
def test_valid_phone(mod, raw, ok):
assert mod._valid_phone(raw) is ok
def test_norm_name_folds_width_and_spaces(mod):
assert mod._norm_name("重庆 金色印象(有限公司)") == "重庆金色印象(有限公司)"
assert mod._norm_name(None) == ""
+100
View File
@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""XQ0035 后浪新天地LIFE+主题会馆签署单位岗位细分单测。
规则(2026-10-16 业务拍板):岗位含 小吃厨师/吧员/员工餐厨师/餐饮组长 任一(子串)
→ 「(餐饮)」主体;其余(含岗位为空)→「(非餐饮)」主体。岗位列是权威,
即使传入单位名已带后缀也按岗位重新判定。单位名不含「后浪新天地」时原样返回、不查字典。
"""
import pytest
@pytest.fixture(scope="module")
def mod(plugins):
return plugins.module("xq0035", "data.step2_sign_new_contract")
@pytest.fixture
def resolver(monkeypatch, mod):
"""替换单位字典查询:known 里的单位名视为存在,返回假 code。"""
known = set()
calls = []
def fake(session, name):
calls.append(name)
return "SID" if name in known else ""
monkeypatch.setattr(mod, "_unit_set_id_by_name", fake)
return known, calls
def test_non_houlang_unit_returned_as_is(mod, resolver):
known, calls = resolver
assert mod.houlang_unit_name(object(), "其他门店", "吧员") == "其他门店"
assert calls == [] # 非后浪单位不查字典
@pytest.mark.parametrize("position", ["小吃厨师", "吧员", "员工餐厨师", "餐饮组长",
"吧员(兼职)", "夜班 餐饮组长"])
def test_catering_positions_map_to_catering(mod, resolver, position):
known, _ = resolver
known.add(f"{mod.HOULANG_BASE_NAME}(餐饮)")
assert mod.houlang_unit_name(object(), mod.HOULANG_BASE_NAME, position) == \
f"{mod.HOULANG_BASE_NAME}(餐饮)"
@pytest.mark.parametrize("position", ["服务员", "前台", "", None, "厨师长"])
def test_other_positions_map_to_non_catering(mod, resolver, position):
known, _ = resolver
known.add(f"{mod.HOULANG_BASE_NAME}(非餐饮)")
assert mod.houlang_unit_name(object(), mod.HOULANG_BASE_NAME, position) == \
f"{mod.HOULANG_BASE_NAME}(非餐饮)"
def test_halfwidth_bracket_variant_is_tried(mod, resolver):
"""单位字典只有半角括号条目时,回退半角变体。"""
known, calls = resolver
known.add(f"{mod.HOULANG_BASE_NAME}(餐饮)")
assert mod.houlang_unit_name(object(), mod.HOULANG_BASE_NAME, "吧员") == \
f"{mod.HOULANG_BASE_NAME}(餐饮)"
assert calls == [f"{mod.HOULANG_BASE_NAME}(餐饮)",
f"{mod.HOULANG_BASE_NAME}(餐饮)"]
def test_both_variants_missing_returns_none(mod, resolver):
"""字典两条变体都未命中 → None,由调用方兜底并告警。"""
known, _ = resolver
assert mod.houlang_unit_name(object(), mod.HOULANG_BASE_NAME, "吧员") is None
def test_position_overrides_suffix_already_in_unit_name(mod, resolver):
"""单位名已带(餐饮)后缀但岗位非餐饮 → 以岗位为准重新判定。"""
known, _ = resolver
known.add(f"{mod.HOULANG_BASE_NAME}(非餐饮)")
unit = f"{mod.HOULANG_BASE_NAME}(餐饮)"
assert mod.houlang_unit_name(object(), unit, "服务员") == \
f"{mod.HOULANG_BASE_NAME}(非餐饮)"
def test_unit_name_is_stripped(mod, resolver):
known, _ = resolver
known.add(f"{mod.HOULANG_BASE_NAME}(餐饮)")
assert mod.houlang_unit_name(object(), f" {mod.HOULANG_BASE_NAME} ", "吧员") == \
f"{mod.HOULANG_BASE_NAME}(餐饮)"
# ---------------- 上一份合同文本解析 ----------------
@pytest.mark.parametrize("info, treaty, start, end, stop", [
("劳动合同解除 (固定期2026-07-27~2027-07-26,终止/解除时间: 2026-09-30)",
"1", "2026-07-27", "2027-07-26", "2026-09-30"),
# 真实数据冒号后可能带空格、也可能是全角冒号
("超龄人员用工协议解除 (2026-07-27~2027-07-26, 解除时间: 2026-09-30)",
"ext_8", "2026-07-27", "2027-07-26", "2026-09-30"),
(None, "", "", "", ""),
("", "", "", "", ""),
])
def test_parse_last_contract(mod, info, treaty, start, end, stop):
got = mod._parse_last_contract(info)
expect_treaty = {"1": mod.TREATY_TYPE_LABOR, "ext_8": mod.TREATY_TYPE_OVERAGE, "": ""}[treaty]
assert got == {"treaty_type": expect_treaty, "start_date": start,
"end_date": end, "stop_date": stop}
+188
View File
@@ -0,0 +1,188 @@
# -*- coding: utf-8 -*-
"""XQ0037 合同信息计算规则单测(不动浏览器/HR 的真实纯逻辑)。
覆盖 _parse_idcard / _retire_date / _defer_months / _month_span / _labor_template_id
以及 calc_plan 的期限、退休封顶、签署单位、异常分支。
"""
from datetime import date
import pytest
@pytest.fixture(scope="module")
def mod(plugins):
return plugins.module("xq0037", "data.step3_transfer_todo")
# ---------------- 身份证解析 ----------------
@pytest.mark.parametrize("idcard, birth, sex", [
("110101199001011234", date(1990, 1, 1), "1"), # 第17位 3=奇 -> 男
("110101199001011244", date(1990, 1, 1), "2"), # 第17位 4=偶 -> 女
("11010119900101123X", date(1990, 1, 1), "1"), # 末位 X 合法
("110101900101123", date(1990, 1, 1), "1"), # 15 位,第15位 3=奇 -> 男
])
def test_parse_idcard_valid(mod, idcard, birth, sex):
assert mod._parse_idcard(idcard) == (birth, sex)
@pytest.mark.parametrize("idcard", ["", None, "abc", "11010119900101123",
"110101199002311234"]) # 末一种:2-31 非法日期
def test_parse_idcard_invalid(mod, idcard):
assert mod._parse_idcard(idcard) == (None, None)
# ---------------- 退休日 / 月份工具 ----------------
def test_retire_date_male_female(mod):
assert mod._retire_date("1", date(2000, 1, 1)) == date(2060, 1, 1)
assert mod._retire_date("2", date(2000, 1, 1)) == date(2050, 1, 1)
def test_retire_date_leap_day_falls_back_to_feb28(mod):
"""2-29 生日遇平年:退到 2-28,不能抛 ValueError。"""
assert mod._retire_date("2", date(2000, 2, 29)) == date(2050, 2, 28)
def test_defer_months_clamps_to_month_end(mod):
assert mod._defer_months(date(2026, 1, 31), 1) == date(2026, 2, 28)
assert mod._defer_months(date(2026, 11, 1), 12) == date(2027, 11, 1)
def test_month_span_ignores_day_remainder_and_minimum_one(mod):
assert mod._month_span(date(2026, 11, 1), date(2027, 6, 1)) == 7
assert mod._month_span(date(2026, 1, 31), date(2026, 2, 28)) == 1 # 零头不计,最小 1
def test_labor_template_by_sequence(mod):
assert mod._labor_template_id("中国技师") == mod.TPL_LABOR_TECH
assert mod._labor_template_id("服务序列") == mod.TPL_LABOR_SERV
assert mod._labor_template_id("职能专业序列") == mod.TPL_LABOR_FUNC
assert mod._labor_template_id("") == mod.TPL_LABOR_FUNC
# ---------------- calc_plan ----------------
@pytest.fixture
def env(monkeypatch, mod):
"""隔离所有网络查询:模板、单位 code、单位详情固定返回。"""
monkeypatch.setattr(mod, "_new_contract_template_ids", lambda session, base_id: "")
monkeypatch.setattr(mod, "_unit_set_detail", lambda session, si_area: ("执照名称", "印章编号"))
monkeypatch.setattr(mod, "_unit_set_id_by_name",
lambda session, name: "SID" if name else "")
return mod
def _roster(**kw):
base = {"现职位序列": "服务序列", "现单位": "石桥铺会馆",
"现四级部门": "石桥铺会馆", "现岗位": "服务员"}
base.update(kw)
return base
def _biz(**kw):
base = {"idcard": "110101199501011234", "staff_id": "S1",
"leaveoffice_time": "2026-10-31"}
base.update(kw)
return base
def test_service_sequence_signs_12_months(mod, env):
plan, err = mod.calc_plan(object(), _biz(), _roster(现职位序列="服务序列"))
assert err is None
assert plan["months"] == 12
assert plan["treaty_type"] == "1"
assert plan["start"] == "2026-11-01"
assert plan["end_time"] == "2027-11-01"
assert plan["end"] == "2027-10-31"
assert plan["si_area"] == "SID"
assert mod.TPL_LABOR_SERV in plan["templates"]
assert mod.TPL_INTEGRITY in plan["templates"]
assert mod.TPL_SOCIAL in plan["templates"]
def test_other_sequence_signs_36_months(mod, env):
plan, err = mod.calc_plan(object(), _biz(), _roster(现职位序列="职能专业序列"))
assert err is None
assert plan["months"] == 36
assert plan["end"] == "2029-10-31"
assert mod.TPL_LABOR_FUNC in plan["templates"]
def test_overage_signs_12_months_overage_agreement(mod, env):
"""已达法定退休年龄:不分序列统一 12 个月 + 超龄人员用工协议,且不算异常。"""
plan, err = mod.calc_plan(object(), _biz(idcard="110101193501011234"),
_roster(现职位序列="职能专业序列"))
assert err is None
assert plan["months"] == 12
assert plan["treaty_type"] == mod.TREATY_TYPE_OVERAGE
assert mod.TPL_OVERAGE_AGREEMENT in plan["templates"]
def test_retirement_cap_before_reaching_age(mod, env):
"""未达龄但按期限签会越过退休日 -> 终止日封顶到退休日、期限按实际月数登记。"""
# 1969-06-01 男:退休日 2029-06-01;36 个月会签到期 2029-10-31 -> 应封顶
plan, err = mod.calc_plan(object(), _biz(idcard="110101196906011234"),
_roster(现职位序列="职能专业序列"))
assert err is None
assert plan["end"] == "2029-06-01"
assert plan["end_time"] == "2029-06-02"
assert plan["months"] == 31
assert plan["treaty_type"] == "1" # 未达龄仍走劳动合同
def test_lakeside_business_unit_split_by_sequence(mod, env):
plan, err = mod.calc_plan(
object(), _biz(), _roster(现单位=mod.UNIT_GOLDEN_LAKESIDE, 现职位序列="职能专业序列"))
assert err is None
assert plan["unit_name"] == mod.UNIT_LAKESIDE_COMPANY
plan2, err2 = mod.calc_plan(
object(), _biz(), _roster(现单位=mod.UNIT_GOLDEN_LAKESIDE, 现职位序列="服务序列"))
assert err2 is None
assert plan2["unit_name"] == mod.UNIT_SHIQIAOPU
def test_houlang_unit_split_uses_position(mod, env, monkeypatch):
"""后浪按岗位细分:calc_plan 必须把「现岗位」透传给细分函数。"""
captured = {}
def fake_split(session, unit_name, position):
captured["unit_name"] = unit_name
captured["position"] = position
return f"{mod.UNIT_TRAINING_VENUE}(餐饮)"
monkeypatch.setattr(mod, "houlang_unit_name", fake_split)
plan, err = mod.calc_plan(
object(), _biz(),
_roster(现四级部门="后浪新天地LIFE+主题会馆", 现岗位="吧员"))
assert err is None
assert captured == {"unit_name": "后浪新天地LIFE+主题会馆", "position": "吧员"}
assert plan["unit_name"] == f"{mod.UNIT_TRAINING_VENUE}(餐饮)"
def test_houlang_unit_missing_abnormal(mod, env, monkeypatch):
monkeypatch.setattr(mod, "houlang_unit_name", lambda s, u, p: None)
plan, err = mod.calc_plan(
object(), _biz(), _roster(现四级部门="后浪新天地LIFE+主题会馆", 现岗位="吧员"))
assert plan is None
assert "单位字典未找到键值" in err
def test_missing_idcard_abnormal(mod, env):
plan, err = mod.calc_plan(object(), _biz(idcard=""), _roster())
assert plan is None
assert "身份证" in err
def test_bad_leave_date_abnormal(mod, env):
plan, err = mod.calc_plan(object(), _biz(leaveoffice_time="bad"), _roster())
assert plan is None
assert "实际离职日期异常" in err
def test_unit_code_missing_abnormal(mod, env, monkeypatch):
monkeypatch.setattr(mod, "_unit_set_id_by_name", lambda session, name: "")
plan, err = mod.calc_plan(object(), _biz(), _roster())
assert plan is None
assert "单位字典未找到键值" in err
+93
View File
@@ -0,0 +1,93 @@
# -*- coding: utf-8 -*-
"""XQ0045_XQ0046 交易查询 xlsx 按商户分组拆分单测。
规则:商户名称精确匹配(仅统一全角括号与首尾空白),未命中归「其他账号」;
每个拆分工作簿保留原 sheet 的标题行/表头行,只按本组数据行过滤。
"""
import openpyxl
import pytest
from pathlib import Path
@pytest.fixture(scope="module")
def mod(plugins):
return plugins.module("xq0045", "data.xlsx_split")
def test_norm_normalizes_brackets_and_spaces(mod):
assert mod._norm(None) == ""
assert mod._norm(" 金色印象 ") == "金色印象"
assert mod._norm("公司(重庆)") == "公司(重庆)"
assert mod._norm("公司(重庆)") == "公司(重庆)"
def test_group_names_are_disjoint(mod):
"""同一商户归一后不得出现在两个分组里,否则归属依赖遍历顺序。"""
groups = {}
for label, names in mod.config.SPLIT_GROUPS:
for name in names:
norm = mod._norm(name)
assert norm not in groups, f"{norm} 同时属于 {groups.get(norm)} 与 {label}"
groups[norm] = label
def test_locate_header(mod):
ws = openpyxl.Workbook().active
ws.append(["交易查询结果"])
ws.append(["商户名称", "金额"])
ws.append(["金色印象", 100])
assert mod._locate_header(ws) == (2, 1)
def test_locate_header_missing(mod):
ws = openpyxl.Workbook().active
ws.append(["没有关键列", "金额"])
assert mod._locate_header(ws) == (None, None)
def _build_source(path):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "sheet1"
ws.append(["交易查询结果"])
ws.append(["商户名称", "金额"])
ws.append(["金色印象", 100])
ws.append(["重庆金色印象品牌管理有限公司518344", 200])
ws.append(["某未分组商户", 300])
ws2 = wb.create_sheet("汇总")
ws2.append(["商户名称", "笔数"])
ws2.append(["金色印象", 1])
ws2.append(["某未分组商户", 1])
wb.save(path)
def _rows(path, sheet):
wb = openpyxl.load_workbook(path)
return [[c.value for c in row] for row in wb[sheet].iter_rows()]
def test_split_creates_three_workbooks_with_filtered_rows(mod, tmp_path):
src = tmp_path / "交易查询.xlsx"
_build_source(src)
out = mod.split_trx_file(src)
assert [Path(p).name for p in out] == [
"交易查询_综合门店.xlsx", "交易查询_品牌管理公司.xlsx", "交易查询_其他账号.xlsx"]
group1 = _rows(tmp_path / "交易查询_综合门店.xlsx", "sheet1")
assert group1[0][0] == "交易查询结果" # 标题行保留
assert group1[1] == ["商户名称", "金额"] # 表头行保留
assert group1[2] == ["金色印象", 100] # 只保留本组数据行
group2 = _rows(tmp_path / "交易查询_品牌管理公司.xlsx", "sheet1")
assert group2[2] == ["重庆金色印象品牌管理有限公司518344", 200]
other = _rows(tmp_path / "交易查询_其他账号.xlsx", "sheet1")
assert other[2] == ["某未分组商户", 300]
# 汇总 sheet 同样按各自商户列过滤
assert _rows(tmp_path / "交易查询_其他账号.xlsx", "汇总") == [
["商户名称", "笔数"], ["某未分组商户", 1]]
# 原全量文件保持不动
assert _rows(src, "sheet1")[3] == ["重庆金色印象品牌管理有限公司518344", 200]
+66
View File
@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
"""XQ0048 导出内容勾选过滤单测。
契约(插件 UI 与 config 约定):
- keys=None(旧配置/定时任务未传)→ 全部导出 + 含截图(向后兼容);
- 显式空列表 → 什么都不导出(UI 已拦截,这里守住语义);
- 勾选键 = 导出接口#日期规则,跨版本稳定且唯一。
"""
import pytest
@pytest.fixture(scope="module")
def cfg(plugins):
return plugins.module("xq0048", "config")
def test_none_keys_means_export_all(cfg):
reports, include_shot = cfg.filter_reports(None)
assert reports == list(cfg.REPORTS)
assert include_shot is True
def test_empty_keys_exports_nothing(cfg):
reports, include_shot = cfg.filter_reports([])
assert reports == []
assert include_shot is False
def test_screenshot_key_only(cfg):
reports, include_shot = cfg.filter_reports([cfg.SCREENSHOT_KEY])
assert reports == []
assert include_shot is True
def test_single_report_key(cfg):
key = cfg.report_key(cfg.REPORTS[0])
reports, include_shot = cfg.filter_reports([key])
assert reports == [cfg.REPORTS[0]]
assert include_shot is False
def test_unknown_keys_ignored(cfg):
reports, include_shot = cfg.filter_reports(["report/not-exist#prev"])
assert reports == []
assert include_shot is False
def test_report_keys_are_unique(cfg):
"""勾选键必须唯一,否则 UI 勾选会串项(同名报表靠日期规则区分)。"""
keys = [cfg.report_key(e) for e in cfg.REPORTS]
assert len(keys) == len(set(keys))
def test_ui_checklist_matches_config(cfg):
"""前端 ITEMS 与 config.REPORTS 必须一一对应(改清单时两边同步,否则勾选键落空)。"""
import re
from pathlib import Path
root = Path(__file__).resolve().parents[2]
app_vue = (root / "plugins" / "XQ0001-0100" / "XQ0048 CRM数据导出"
/ "ui-src" / "src" / "App.vue")
if not app_vue.exists():
pytest.skip("ui-src 源码未随仓库提供")
ui_keys = set(re.findall(r"key:\s*'([^']+)'", app_vue.read_text(encoding="utf-8")))
ui_keys.discard(cfg.SCREENSHOT_KEY)
assert ui_keys == {cfg.report_key(e) for e in cfg.REPORTS}
+98
View File
@@ -0,0 +1,98 @@
# -*- coding: utf-8 -*-
"""仓库最小 CI 检查(本地与 GitLab Runner 共用)。
用法:
.venv\\Scripts\\python.exe tools/ci_check.py # 语法编译 + 单测
.venv\\Scripts\\python.exe tools/ci_check.py --frontend # 追加执行机壳前端构建
检查项:
1. 全量 Python 语法编译(py_compile:只编译不落 __pycache__,避免污染工作区);
2. tests/unit 纯逻辑单测(pytest);
3. --frontend:electron-shell/frontend 的 vite build(需本机有 pnpm/npm 与 node_modules)。
不检查 controlplane-next 前端:其 build 前置 vue-tsc 全量类型检查,历史类型告警
不在本 CI 的阻塞范围,单独治理。
"""
import argparse
import os
import py_compile
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
# 依赖目录 / 产物 / 本地临时目录不参与语法检查
EXCLUDE_DIRS = {
".venv", "venv", "node_modules", ".git", "__pycache__",
"dist", "build", "dist-plugin", "dist-sdk", "dist-app", "dist-env",
"python-env", "logs", "out",
".tmp-deploy", ".tmp2", ".tmp_xq0052", "tmp_probe_js",
}
def iter_py_files():
for path in ROOT.rglob("*.py"):
rel_parts = path.relative_to(ROOT).parts
if any(part in EXCLUDE_DIRS for part in rel_parts[:-1]):
continue
yield path
def check_syntax():
files = list(iter_py_files())
errors = []
with tempfile.TemporaryDirectory() as tmp:
cfile = str(Path(tmp) / "x.pyc")
for path in files:
try:
py_compile.compile(str(path), cfile=cfile, doraise=True)
except py_compile.PyCompileError as exc:
errors.append(f"{path.relative_to(ROOT)}: {exc.msg}")
print(f"[syntax] 检查 {len(files)} 个 Python 文件,失败 {len(errors)} 个")
for line in errors:
print(" " + line)
return len(errors)
def run_pytest():
cmd = [sys.executable, "-m", "pytest", "-p", "no:cacheprovider"]
print("[pytest] " + " ".join(cmd))
return subprocess.run(cmd, cwd=ROOT).returncode
def run_frontend_build():
front = ROOT / "desktop" / "electron-shell" / "frontend"
if not (front / "node_modules").exists():
print("[frontend] 跳过:node_modules 未安装")
return 0
# Windows 上 which("pnpm") 可能命中 pnpm.ps1(cmd.exe 无法直接执行),优先取 .cmd
pm = (shutil.which("pnpm.cmd") or shutil.which("pnpm")
or shutil.which("npm.cmd") or shutil.which("npm"))
if not pm:
print("[frontend] 跳过:未找到 pnpm/npm")
return 0
print(f"[frontend] {Path(pm).name} run build")
return subprocess.run(f'"{pm}" run build', cwd=front, shell=True).returncode
def main():
parser = argparse.ArgumentParser(description="仓库最小 CI 检查")
parser.add_argument("--frontend", action="store_true", help="追加执行机壳前端构建")
args = parser.parse_args()
os.chdir(ROOT)
failed = check_syntax() != 0
if run_pytest() != 0:
failed = True
if args.frontend and run_frontend_build() != 0:
failed = True
print("CI 结果:" + ("FAILED" if failed else "PASSED"))
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())