Files
syops/backend/tests/services/in_transit_transfer/fakes.py
T
hugo 1ba38e1685 feat(shipping-notice): 调拨预检解析增强与批号列交互完善
- 异动解析跳过无异动日期的在途/执行中行,兼容 datetime 日期单元格
- ERP 网关故障降级为逐票阻断并带原因,不再炸整来源
- 预检明细唯一约束升粒度:(预检,来源,单号,料号,收料日期)
- Invoice 恢复单号锚定并移至料号前;批号 lot_no 全链贯通,
  拨出/拨入批号按 WTP→HOW 转换展示;新增收料日期列
- 预检表格筛选/全选;单行与批量重查 ERP 库存
- 收料日期范围作为预检查询范围,截止卡控不超出 D+1 规则
- 来源多选打包下载收料文件;调拨消息与子流程容器放宽宽度
- 预检恢复明细补齐收料日期与批号字段(修复卡片三列空值)
2026-09-21 19:29:52 +08:00

248 lines
12 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.
"""在途调拨测试的可控外部系统替身:FakeERP / FakeRPA / FakeWeCom / FakeClock。
用途:让 L0/L1 测试在不接触真实 RPA、ERP、企业微信的前提下覆盖全部业务分支,
并把每一次外部调用完整记录到 call log,供断言副作用与调用次数。
依赖:标准库(dataclasses / decimal / zoneinfo)。
逻辑:FakeERP 以 invoice_no 为业务键维护账面库存与已生成单据;
create_transfer 按注入的 scenario 返回 success / duplicate_success /
business_failed / timeout_before_commit / timeout_after_commit;
所有调用均追加一条 ErpCallRecord(operation_id、invoice_no、erp_org、
来源仓、目标仓、数量、调用序号、方法、返回状态、ERP 单号)。
"""
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.erp_adapter import ErpWriteTimeoutError
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 ErpCallRecord:
"""FakeERP 单次调用的事实记录;测试断言优先读取该记录。"""
operation_id: str
invoice_no: str
erp_org: str
from_warehouse: str
to_warehouse: str
quantity: Decimal
call_seq: int
returned_status: str
method: str
document_no: str | None = None
class FakeERP:
"""可注入账面库存与响应场景的 ERP 替身;每次调用写入 call log。"""
def __init__(self) -> None:
self.inventory: dict[str, dict[str, Any]] = {}
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[ErpCallRecord] = []
self._seq = 0
# -- 控制注入 ----------------------------------------------------------
def seed_inventory(self, invoice_no: str, quantity: str | int | Decimal) -> None:
"""设置指定 Invoice 的账面库存。"""
self.inventory[str(invoice_no).strip()] = {"quantity": Decimal(str(quantity))}
def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None:
"""预置某 Invoice 已存在的 ERP 单据(幂等重复场景)。"""
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。"""
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
# -- ERP 能力 ----------------------------------------------------------
def query_inventory(self, *, operation_id: str, run_no: str, attempt_no: int,
invoice_no: str, erp_org: str, from_warehouse: str,
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
"""按 Invoice 返回账面库存;timeout 场景抛超时异常。"""
self._seq += 1
key = str(invoice_no).strip()
if self.query_scenario == "timeout":
raise TimeoutError(f"query timeout operation_id={operation_id}")
if self.query_scenario == "error":
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "error", "query_inventory")
self.call_log.append(record)
raise RuntimeError("binding not found for capability query_inventory")
if self.query_scenario == "inventory_not_found" or key not in self.inventory:
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "inventory_not_found", "query_inventory")
self.call_log.append(record)
return {"found": False, "quantity": Decimal("0")}
qty = self.inventory[key]["quantity"]
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "success", "query_inventory")
self.call_log.append(record)
return {"found": True, "quantity": qty}
def create_transfer(self, *, operation_id: str, run_no: str, attempt_no: int,
invoice_no: str, erp_org: str, from_warehouse: str,
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
"""原子建单/审核/过账;按注入场景返回结果并记录调用。"""
self._seq += 1
key = str(invoice_no).strip()
scenario = self.write_scenarios.get(key, self.write_scenario)
if scenario == "timeout_before_commit":
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "timeout_before_commit", "create_transfer")
self.call_log.append(record)
raise ErpWriteTimeoutError(
"write timeout before commit", committed=False, operation_id=operation_id,
)
if self.write_scenario == "timeout_after_commit" or scenario == "timeout_after_commit":
# 已落单但无法确认:调用方必须投 result_unknown,禁止自动重试。
self.documents.setdefault(key, f"TRF-{self._seq:05d}")
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "timeout_after_commit", "create_transfer",
self.documents[key])
self.call_log.append(record)
raise ErpWriteTimeoutError(
"write timeout after commit", committed=True,
document_no=self.documents[key], operation_id=operation_id,
)
if scenario == "business_failed" or self.write_scenario == "business_failed":
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "business_failed", "create_transfer")
self.call_log.append(record)
return {"status": "business_failed", "code": "ERP_BUSINESS_REJECT", "rolled_back": True}
if key in self.documents:
document_no = self.documents[key]
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "duplicate_success", "create_transfer",
document_no)
self.call_log.append(record)
return {
"status": "duplicate_success",
"document_no": document_no,
"verified_posted": self.verified_posted.get(key, False),
}
document_no = f"TRF-{self._seq:05d}"
self.documents[key] = document_no
self.verified_posted[key] = True
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "success", "create_transfer", document_no)
self.call_log.append(record)
return {"status": "success", "document_no": document_no, "posted": True}
def verify_duplicate(self, *, operation_id: str, run_no: str, attempt_no: int,
invoice_no: str, erp_org: str, from_warehouse: str,
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
"""核实重复 Invoice 原单状态(已审核过账/未确认)。"""
self._seq += 1
key = str(invoice_no).strip()
if key not in self.documents:
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, "duplicate_unverified", "verify_duplicate")
self.call_log.append(record)
return {"status": "duplicate_unverified", "document_no": None, "verified_posted": False}
document_no = self.documents[key]
posted = self.verified_posted.get(key, False)
status = "duplicate_success" if posted else "duplicate_unverified"
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
quantity, self._seq, status, "verify_duplicate", document_no)
self.call_log.append(record)
return {"status": status, "document_no": document_no, "verified_posted": posted}
# -- 断言辅助 ----------------------------------------------------------
def calls(self, *, invoice_no: str | None = None) -> list[ErpCallRecord]:
"""按 Invoice 过滤调用记录(默认返回全部)。"""
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[ErpCallRecord]:
"""仅返回 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()