"""在途调拨测试的可控外部系统替身:FakeCapabilityClient / FakeRPA / FakeWeCom / FakeClock。 用途:让 L0/L1 测试在不接触真实 RPA、外部系统、企业微信的前提下覆盖全部业务分支, 并把每一次外部调用完整记录到 call log,供断言副作用与调用次数。 依赖:标准库(dataclasses / decimal / zoneinfo)、capability_client(域类型)。 逻辑:FakeCapabilityClient 以 (料号, 拨出库位, 拨出批号) 三元组维护账面库存; query_stock 一次返回组内全部命中行;create_transfer 按注入的 scenario 返回已分类的 TransferWriteResult(success / duplicate_success / business_failed / technical_failed / result_unknown)。 """ from __future__ import annotations from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from decimal import Decimal from typing import Any from zoneinfo import ZoneInfo from app.services.in_transit_transfer.capability_client import ( ExternalQueryTimeoutError, StockQueryResult, StockRow, TransferWriteResult, ) class FakeClock: """固定时钟:默认 2026-08-06 09:00:00+08:00,可推进业务日。""" def __init__(self, iso: str = "2026-08-06T09:00:00+08:00") -> None: self.now_value = datetime.fromisoformat(iso) def now(self) -> datetime: """返回当前固定时刻(带 Asia/Shanghai 时区)。""" return self.now_value def advance(self, *, seconds: int = 0, days: int = 0) -> None: """按秒或天推进固定时钟(保持 Asia/Shanghai 时区)。""" self.now_value = self.now_value.replace(tzinfo=ZoneInfo("Asia/Shanghai")) if seconds: self.now_value = self.now_value + timedelta(seconds=seconds) if days: self.now_value = self.now_value + timedelta(days=days) @dataclass(frozen=True) class ExternalCallRecord: """FakeCapabilityClient 单次调用的事实记录;测试断言优先读取该记录。""" operation_id: str external_org: str call_seq: int returned_status: str method: str # 查询调用:记录目标元组;写调用:invoice_no + 数量。 targets: tuple[tuple[str, str, str], ...] = () invoice_no: str = "" document_no: str | None = None class FakeCapabilityClient: """可注入账面库存与响应场景的外部系统客户端替身;每次调用写入 call log。""" def __init__(self) -> None: self.inventory: dict[tuple[str, str, str], Decimal] = {} self.documents: dict[str, str] = {} self.verified_posted: dict[str, bool] = {} self.query_scenario: str = "normal" self.write_scenario: str = "success" # 按 Invoice 覆盖写场景(Key=invoice_no);未配置时回落到 write_scenario。 self.write_scenarios: dict[str, str] = {} self.call_log: list[ExternalCallRecord] = [] self._seq = 0 # -- 控制注入 ---------------------------------------------------------- def seed_stock(self, material_no: str, from_warehouse: str, lot_no: str, quantity: str | int | Decimal) -> None: """设置指定 (料号, 拨出库位, 拨出批号) 的账面库存。""" key = (str(material_no).strip(), str(from_warehouse).strip(), str(lot_no).strip()) self.inventory[key] = Decimal(str(quantity)) def clear_stock(self) -> None: """清空全部账面库存(模拟 外部系统 库存被移走/未上账)。""" self.inventory.clear() def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None: """预置某 Invoice 已存在的单据(幂等重复场景)。""" self.documents[str(invoice_no).strip()] = document_no self.verified_posted[str(invoice_no).strip()] = posted def set_query_scenario(self, scenario: str) -> None: """normal | inventory_not_found | timeout | error。""" self.query_scenario = scenario def set_write_scenario(self, scenario: str) -> None: """success | duplicate_success | business_failed | timeout_before_commit | timeout_after_commit。""" self.write_scenario = scenario # -- 外部系域能力 ---------------------------------------------------------- def query_stock(self, *, operation_id: str, external_org: str, targets: list) -> StockQueryResult: """按组织批量返回库存行;timeout/error 场景按客户端语义抛错。""" self._seq += 1 target_keys = [ (str(t.material_no).strip(), str(t.from_warehouse).strip(), str(t.lot_no).strip()) for t in targets ] if self.query_scenario == "timeout": raise ExternalQueryTimeoutError(f"query timeout operation_id={operation_id}") if self.query_scenario == "error": self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, "error", "query_stock", targets=tuple(target_keys), )) raise RuntimeError("binding not found for capability query_inventory") rows: list[StockRow] = [] for key in target_keys: if self.query_scenario == "inventory_not_found": continue if key in self.inventory: rows.append(StockRow( material_no=key[0], from_warehouse=key[1], lot_no=key[2], quantity=self.inventory[key], )) self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, "success" if rows else "inventory_not_found", "query_stock", targets=tuple(target_keys), )) return StockQueryResult(rows=tuple(rows)) def create_transfer(self, *, operation_id: str, run_no: str, attempt_no: int, invoice_no: str, external_org: str, from_warehouse: str, to_warehouse: str, quantity: Decimal) -> TransferWriteResult: """原子建单/审核/过账;按注入场景返回已分类结果并记录调用。""" self._seq += 1 key = str(invoice_no).strip() scenario = self.write_scenarios.get(key, self.write_scenario) if scenario == "timeout_before_commit": self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, "timeout_before_commit", "create_transfer", invoice_no=key, )) # 可证明未落单 → 明确技术失败(不产生单据)。 return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT") if self.write_scenario == "timeout_after_commit" or scenario == "timeout_after_commit": # 已落单但无法确认:调用方必须投 result_unknown,禁止自动重试。 self.documents.setdefault(key, f"TRF-{self._seq:05d}") document_no = self.documents[key] self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, "timeout_after_commit", "create_transfer", invoice_no=key, document_no=document_no, )) return TransferWriteResult( status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT", document_no=document_no, ) if scenario == "business_failed" or self.write_scenario == "business_failed": self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, "business_failed", "create_transfer", invoice_no=key, )) return TransferWriteResult( status="business_failed", error_code="EXTERNAL_BUSINESS_REJECT", error_message="rejected by external system", ) if key in self.documents: document_no = self.documents[key] posted = self.verified_posted.get(key, False) status = "duplicate_success" if posted else "duplicate_unverified" self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, status, "create_transfer", invoice_no=key, document_no=document_no, )) return TransferWriteResult( status=status, document_no=document_no, verified_posted=posted, error_code=None if posted else "TRANSFER_DUPLICATE_NOT_VERIFIED", ) document_no = f"TRF-{self._seq:05d}" self.documents[key] = document_no self.verified_posted[key] = True self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, "success", "create_transfer", invoice_no=key, document_no=document_no, )) return TransferWriteResult(status="success", document_no=document_no, verified_posted=True) def verify_duplicate(self, *, operation_id: str, run_no: str, attempt_no: int, invoice_no: str, external_org: str, from_warehouse: str, to_warehouse: str, quantity: Decimal) -> TransferWriteResult: """核实重复 Invoice 原单状态(已审核过账/未确认)。""" self._seq += 1 key = str(invoice_no).strip() if key not in self.documents: self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, "duplicate_unverified", "verify_duplicate", invoice_no=key, )) return TransferWriteResult( status="duplicate_unverified", error_code="TRANSFER_DUPLICATE_NOT_VERIFIED", ) document_no = self.documents[key] posted = self.verified_posted.get(key, False) status = "duplicate_success" if posted else "duplicate_unverified" self.call_log.append(ExternalCallRecord( operation_id, external_org, self._seq, status, "verify_duplicate", invoice_no=key, document_no=document_no, )) return TransferWriteResult( status=status, document_no=document_no, verified_posted=posted if posted else None, error_code=None if posted else "TRANSFER_DUPLICATE_NOT_VERIFIED", ) # -- 断言辅助 ---------------------------------------------------------- def calls(self, *, invoice_no: str | None = None) -> list[ExternalCallRecord]: """按 Invoice 过滤调用记录(默认返回全部;查询调用 invoice_no 为空串)。""" if invoice_no is None: return list(self.call_log) return [record for record in self.call_log if record.invoice_no == str(invoice_no).strip()] def write_calls(self) -> list[ExternalCallRecord]: """仅返回 create_transfer 调用记录(写副作用断言)。""" return [record for record in self.call_log if record.method == "create_transfer"] class FakeRPA: """可独立按来源注入失败/延迟的收料 RPA 替身。""" def __init__(self) -> None: self.triggered: list[dict[str, Any]] = [] self.fail_on: set[str] = set() def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: """触发一次来源收料抓取并记录。""" self.triggered.append({ "source_code": source_code, "business_date": business_date, "reason": reason, }) if source_code in self.fail_on: return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"} return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"} class FakeWeCom: """企业微信通知替身;记录投递事实,可注入附件失败。""" def __init__(self) -> None: self.deliveries: list[dict[str, Any]] = [] self.attach_fail = False def send_summary(self, *, run_no: str, summary: dict[str, Any], recipients: list[str], excel_path: str | None = None) -> dict[str, Any]: """发送一次汇总通知;附件失败时返回 failed 但不抛异常。""" if self.attach_fail and excel_path: record = {"run_no": run_no, "status": "failed", "error_code": "WECOM_ATTACH_FAILED"} self.deliveries.append(record) return {"status": "failed", "error_code": "WECOM_ATTACH_FAILED"} record = {"run_no": run_no, "status": "success", "recipients": recipients, "excel": excel_path} self.deliveries.append(record) return {"status": "success"} @dataclass class FakeAuditSink: """审计落点替身;记录 before/after、Diff、Hash 与关联上下文。""" events: list[dict[str, Any]] = field(default_factory=list) def append(self, event: dict[str, Any]) -> None: """追加一条审计事件 dict。""" self.events.append(event) def utc_now_iso() -> str: """返回当前 UTC 时间的 ISO 字符串(测试断言用)。""" return datetime.now(timezone.utc).isoformat()