conftest.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """测试夹具:统一提供样本数据、规则路径和一次完整的处理结果。
  2. 注意:``CDA_DATA_DIR`` 必须在 import toolsvc 之前设置,否则设置单例会绑定到
  3. 开发时的 ``data/`` 目录,测试会污染真实数据。
  4. """
  5. from __future__ import annotations
  6. import json
  7. import os
  8. import sys
  9. from pathlib import Path
  10. import pytest
  11. ROOT = Path(__file__).resolve().parents[2]
  12. SERVICE = ROOT / "tools-service"
  13. SAMPLES = ROOT / "samples"
  14. TEST_DATA = SERVICE / ".pytest-data"
  15. if str(SERVICE) not in sys.path:
  16. sys.path.insert(0, str(SERVICE))
  17. # 每次会话都从干净的对象库开始(不能放在 pytest basetemp 里:
  18. # 那个目录会在会话开始时被清理,而 SQLite 连接还开着,Windows 会报占用)
  19. import shutil # noqa: E402
  20. shutil.rmtree(TEST_DATA, ignore_errors=True)
  21. os.environ["CDA_DATA_DIR"] = str(TEST_DATA)
  22. os.environ["CDA_LEDGER_JSONL"] = "1"
  23. from toolsvc.customs import CustomsProcessRequest, load_processor # noqa: E402
  24. @pytest.fixture(scope="session")
  25. def root() -> Path:
  26. return ROOT
  27. @pytest.fixture(scope="session")
  28. def sample_csv() -> Path:
  29. path = SAMPLES / "small.csv"
  30. if not path.exists():
  31. pytest.skip("缺少样本数据,请先运行 python scripts/gen_sample_data.py")
  32. return path
  33. @pytest.fixture(scope="session")
  34. def sample_expected() -> dict:
  35. path = SAMPLES / "small.expected.json"
  36. if not path.exists():
  37. pytest.skip("缺少样本预言机文件,请先运行 python scripts/gen_sample_data.py")
  38. return json.loads(path.read_text(encoding="utf-8"))
  39. @pytest.fixture(scope="session")
  40. def processed(tmp_path_factory) -> dict:
  41. """跑一次完整流程,供多个测试用例复用(避免重复十几秒)。"""
  42. output = tmp_path_factory.mktemp("pipeline")
  43. result = load_processor().process(
  44. CustomsProcessRequest(
  45. input_path=str(SAMPLES / "small.csv"),
  46. output_dir=str(output),
  47. )
  48. )
  49. return {"result": result, "output": output}
  50. @pytest.fixture()
  51. def workdir(tmp_path) -> Path:
  52. return tmp_path