Files
37duAutomation/tests/unit/conftest.py
T
puddy 6c1161fd54 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 的纯逻辑部分。
2026-11-11 12:48:37 +08:00

84 lines
3.1 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 -*-
"""插件纯逻辑单测的模块加载器。
插件目录名是中文且带空格,不是合法 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()