"""trigger_consumer 公共模块测试。 用途:锁定 trigger 文件四态目录契约(根目录待领取 → processing 处理中 → processed/failed 终态)的领取与归档行为。 依赖:标准库 tempfile/pathlib、scripts.rpa.common.trigger_consumer。 逻辑:claim 原子性(二次领取返回 None)、归档落位、非法入参拒绝。 """ from __future__ import annotations import sys from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common")) from trigger_consumer import archive_trigger, claim_trigger # noqa: E402 def _write_trigger(root: Path, name: str = "batch_1.json") -> Path: path = root / name path.write_text('{"schema_version": "x"}', encoding="utf-8") return path def test_claim_moves_file_into_processing(tmp_path): """首次领取应把 trigger 原子移入 processing/ 并返回新路径。""" path = _write_trigger(tmp_path) claimed = claim_trigger(path) assert claimed == tmp_path / "processing" / path.name assert claimed.read_text(encoding="utf-8") == '{"schema_version": "x"}' assert not path.exists() def test_claim_twice_returns_none(tmp_path): """同一 trigger 二次领取必须返回 None(防双消费/重复导出)。""" path = _write_trigger(tmp_path) assert claim_trigger(path) is not None assert claim_trigger(path) is None def test_archive_processed_and_failed(tmp_path): """processing/ 中的文件按 outcome 归档到同名终态目录。""" path = _write_trigger(tmp_path) claimed = claim_trigger(path) done = archive_trigger(claimed, "processed") assert done == tmp_path / "processed" / path.name and done.exists() path2 = _write_trigger(tmp_path, "batch_2.json") claimed2 = claim_trigger(path2) failed = archive_trigger(claimed2, "failed") assert failed == tmp_path / "failed" / path2.name and failed.exists() def test_archive_rejects_bad_outcome_and_unclaimed_path(tmp_path): """非法 outcome 与未经领取的路径都必须拒绝,防止归档错位。""" path = _write_trigger(tmp_path) with pytest.raises(ValueError): archive_trigger(path, "processed") # 未领取,不在 processing/ 下 claimed = claim_trigger(_write_trigger(tmp_path, "batch_3.json")) with pytest.raises(ValueError): archive_trigger(claimed, "done") # outcome 白名单外 def test_inventory_worker_scans_with_claim(tmp_path): """库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。""" root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8") assert "claim_trigger" in text # 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent assert text.count('trigger_path.parent / "failed"') == 0 def test_receipt_worker_runs_periodic_disk_cleanup(): """收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。""" receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8") assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8") assert '"receipt_"' in cleanup or "'receipt_'" in cleanup