"""测试夹具:统一提供样本数据、规则路径和一次完整的处理结果。 注意:``CDA_DATA_DIR`` 必须在 import toolsvc 之前设置,否则设置单例会绑定到 开发时的 ``data/`` 目录,测试会污染真实数据。 """ from __future__ import annotations import json import os import sys from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[2] SERVICE = ROOT / "tools-service" SAMPLES = ROOT / "samples" TEST_DATA = SERVICE / ".pytest-data" if str(SERVICE) not in sys.path: sys.path.insert(0, str(SERVICE)) # 每次会话都从干净的对象库开始(不能放在 pytest basetemp 里: # 那个目录会在会话开始时被清理,而 SQLite 连接还开着,Windows 会报占用) import shutil # noqa: E402 shutil.rmtree(TEST_DATA, ignore_errors=True) os.environ["CDA_DATA_DIR"] = str(TEST_DATA) os.environ["CDA_LEDGER_JSONL"] = "1" from toolsvc.customs import CustomsProcessRequest, load_processor # noqa: E402 @pytest.fixture(scope="session") def root() -> Path: return ROOT @pytest.fixture(scope="session") def sample_csv() -> Path: path = SAMPLES / "small.csv" if not path.exists(): pytest.skip("缺少样本数据,请先运行 python scripts/gen_sample_data.py") return path @pytest.fixture(scope="session") def sample_expected() -> dict: path = SAMPLES / "small.expected.json" if not path.exists(): pytest.skip("缺少样本预言机文件,请先运行 python scripts/gen_sample_data.py") return json.loads(path.read_text(encoding="utf-8")) @pytest.fixture(scope="session") def processed(tmp_path_factory) -> dict: """跑一次完整流程,供多个测试用例复用(避免重复十几秒)。""" output = tmp_path_factory.mktemp("pipeline") result = load_processor().process( CustomsProcessRequest( input_path=str(SAMPLES / "small.csv"), output_dir=str(output), ) ) return {"result": result, "output": output} @pytest.fixture() def workdir(tmp_path) -> Path: return tmp_path