Merge branch 'dev' into picture-feedback

This commit is contained in:
HTEWJ\26070045 committed 2026-10-29 11:04:59 +08:00
commit 34ad40778b
180 files changed
+13262 -5333

No files matched your search

@@ -1,16 +1,18 @@
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
用途:验证同步执行组合入口的两道门禁(①存在且可执行 ②文件版本对账,失败路径
均携带 details 列表且外部系统 写入为 0;原「行级新鲜度 TTL」门禁已于
2026-09-25 退役——items_stale 拒绝用例随之删除,TTL 降级为前端展示徽标)、
D1 五元组建单与单据级写语义(一单一次 create_transfer、单内行共享单结果)、
写前路由复查(漂移阻断)、result_unknown 不自动重试、单间失败隔离
(不同组互不影响)、匹配 scope 执行入口(execute_matching_items)与按
外部系统 单号投影。
用途:验证同步执行组合入口的执行存在性门禁(①存在且可执行,失败携带 details
列表且外部系统 写入为 0;原「文件版本对账」门禁已于 2026-10-22 退役——
文件更新/缺失不再拦执行,行装饰 file_current 徽标仅提示,防错下沉 worker
写前库存复查;原「行级新鲜度 TTL」门禁已于 2026-09-25 退役——items_stale
拒绝用例随之删除,TTL 降级为前端展示徽标)、D1 五元组建单与单据级写语义
(一单一次 create_transfer、单内行共享单结果)、写前路由复查(漂移阻断)、
result_unknown 不自动重试、单间失败隔离(不同组互不影响)、匹配 scope
执行入口(execute_matching_items)与按外部系统单号投影。
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
来源文件状态投影经 patch_source_file_status 夹具注入替身(装饰断言另打
matching_service 命名空间)。
"""
from __future__ import annotations
@@ -29,6 +31,7 @@ from app.services.in_transit_transfer.matching_service import (
RouteMapping,
TransferDeps,
create_matching,
list_executable_items,
)
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
@@ -252,35 +255,57 @@ def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_f
assert _execution_runs() == []
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
"""门禁②:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
def test_execute_items_proceeds_when_file_updated_and_decorates_not_current(
transfer_db, dbs_ready_file, patch_source_file_status, monkeypatch,
):
"""[2026-10-22 文件版本对账门禁退役] 文件已更新不再是执行门禁。
入站抓取是部分导出——新文件不含某行 ≠ 该行失效/已处理,按最新文件 sha
对账曾把大量未处理行错误卡死(业务实测 557 行积压)。执行照常写 ERP;
行装饰 file_current=False 仅提示不拦截,防错下沉 worker 写前库存复查。
"""
patch_source_file_status({"DBS-AWSBI": "e" * 64})
# 装饰读取走 matching_service 命名空间的同名投影(退役后该函数仅剩展示
# 消费方),此处同步打桩保持与执行侧替身同源。
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
lambda *, source_code, record_kind="inbound": {
"file_status": "ready", "has_ready_file": True,
"file_no": "REC-TEST", "file_sha256": "e" * 64,
},
)
deps, erp, items = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
# 断言:行当前性徽标如实提示「行评估版本戳 ≠ 最新可用文件」。
listing = list_executable_items(deps=deps)
decorated = {row.item_id: row for row in listing["items"]}
assert all(decorated[item.id].file_current is False for item in items)
with pytest.raises(ValidationError) as excinfo:
execute_items(item_ids=[item.id for item in items], deps=deps)
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
assert erp.write_calls() == []
assert _execution_runs() == []
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
# 断言:徽标不拦截执行——同组两 Invoice 合并一单、一次写调用、行全 success。
assert outcome.status == "success"
assert len(erp.write_calls()) == 1
linked = _load_items(outcome.run_no)
assert all(item.status == "success" for item in linked.values())
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
"""门禁②:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
def test_execute_items_proceeds_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
"""[2026-10-22 门禁退役] 来源无可用文件同样不拦执行。
档是镜像事实,不随当日文件可用性消失(evidence_sync 已落档的行照常可执行)。
"""
patch_source_file_status({"DBS-AWSBI": None})
deps, erp, items = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
with pytest.raises(ValidationError) as excinfo:
execute_items(item_ids=[item.id for item in items], deps=deps)
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
assert erp.write_calls() == []
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
# 断言:无可用文件不拒绝执行——照常组建单并写入外部系统。
assert outcome.status == "success"
assert len(erp.write_calls()) == 1
linked = _load_items(outcome.run_no)
assert all(item.status == "success" for item in linked.values())
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
@@ -1,7 +1,7 @@
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
匹配快照 Hash 稳定、缺文件等待与进度恢复、匹配顶替;专项用例锁生产默认 lag=2。
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
@@ -1152,3 +1152,182 @@ def test_cancel_matching_releases_ledger_occupancy(transfer_db, dbs_ready_file):
born = TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
assert len(born) == 2
assert all(row.status == "ready_to_execute" for row in born)
def test_create_matching_supersedes_covered_unwritten_matching(transfer_db, dbs_ready_file):
"""新匹配盖住同一类型、同一来源、尚未写 ERP 的旧匹配时,旧匹配取消,货出现在新匹配上。
夹具两行异动日都是 2026-08-04。第一次与第二次都用 08-01~08-04,新范围盖住旧范围。
"""
from app.models import TransferInvoiceItem, TransferMatching
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
covered = dict(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
first = create_matching(deps=deps, **covered)
# [断言意图] 顶替前旧匹配自己先圈到夹具的两张单,证明后面的 2 不是「本来就没占上」。
assert first.counts.executable_count == 2
second = create_matching(deps=deps, **covered)
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
# [断言意图] 被盖住且未写 ERP 的旧匹配不再有效,其可执行行不能留在队列里二次写 ERP。
assert first_matching.status == "cancelled"
retired = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id).all()
assert retired
assert all(row.status == "cancelled" for row in retired)
# [断言意图] 同一批货(HOM-001、HOX-002)出现在新匹配上,且仍可执行。
assert second.counts.executable_count == 2
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
reborn = {
row.invoice_no
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
}
assert reborn == {"HOM-001", "HOX-002"}
def test_create_matching_supersedes_covered_matching_with_only_blocked_rows(transfer_db, dbs_ready_file):
"""全阻断的旧匹配状态虽是 success,只要还没写 ERP,新范围盖住时仍要顶替。"""
from app.models import TransferInvoiceItem, TransferMatching
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
covered = dict(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
first = create_matching(deps=deps, **covered)
# [断言意图] 数量对不上时匹配状态是 success,不能因此被当成「已经写出单据」。
assert first.status == "success"
assert first.counts.executable_count == 0
second = create_matching(deps=deps, **covered)
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
assert first_matching.status == "cancelled"
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
reborn = {
row.invoice_no
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
}
assert reborn == {"HOM-001", "HOX-002"}
def test_create_matching_keeps_previous_when_new_range_does_not_cover(transfer_db, dbs_ready_file):
"""新范围盖不住旧范围时,旧匹配保持有效,货仍留在旧匹配上。"""
from app.models import TransferMatching
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
first = create_matching(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
deps=deps,
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
second = create_matching(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
deps=deps,
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-04",
movement_date_to="2026-08-04",
)
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
# [断言意图] 08-04~08-04 盖不住 08-01~08-04,旧匹配不能被取消。
assert first_matching.status == "ready_to_execute"
# [断言意图] 货仍被旧匹配占用,新匹配圈不到,清单不另列历史匹配编号。
assert second.counts.executable_count == 0
def test_supersede_keeps_manually_closed_goods_out_of_the_new_matching(transfer_db, dbs_ready_file):
"""顶替后,人工关闭的单号不回到新匹配。"""
from app.models import TransferInvoiceItem, TransferMatching
from app.services.in_transit_transfer.manual_close_service import manual_close_item
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
covered = dict(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
first = create_matching(deps=deps, **covered)
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
closed = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id, invoice_no="HOX-002").one()
manual_close_item(item_id=closed.id, reason="这批不再调拨")
second = create_matching(deps=deps, **covered)
# [断言意图] 人工关闭跨过顶替仍然有效,新匹配不能把 HOX-002 再圈成可执行。
assert db.session.get(TransferInvoiceItem, closed.id).status == "manually_closed"
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
reborn = {
row.invoice_no
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
}
assert reborn == {"HOM-001"}
def test_unattached_item_does_not_block_a_new_matching(transfer_db, dbs_ready_file):
"""没有挂上任何匹配的明细不占货,新匹配仍能圈到那张单。"""
from app.models import TransferInvoiceItem, TransferMatching, TransferMovementLedger
deps, erp, _ = _deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
ledger = TransferMovementLedger.query.filter_by(source_code="DBS-AWSBI", doc_no="HOM-001").first()
db.session.add(TransferInvoiceItem(
matching_id=None,
ledger_record_id=ledger.id,
source_code="DBS-AWSBI",
invoice_no="HOM-001",
material_no="MAT-001",
movement_date="2026-08-04",
from_warehouse="DBS-TRANSIT",
to_warehouse="HUB-CN01",
movement_quantity="1200",
status="matching",
result_code="pending_stock_check",
))
db.session.commit()
summary = create_matching(
source_codes=["DBS-AWSBI"],
business_date="2026-08-06",
deps=deps,
transfer_type="in_transit_to_hub",
movement_date_from="2026-08-01",
movement_date_to="2026-08-04",
)
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
# [断言意图] 悬挂行没有匹配编号,不能挡住 HOM-001;两张夹具单都进新匹配。
invoices = {
row.invoice_no
for row in TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
}
assert invoices == {"HOM-001", "HOX-002"}
@@ -3,14 +3,20 @@
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
依赖:schedule.job_registry、job_options、inbound_trigger_service、
transfer_type_config_service、in_transit_transfer_job。
逻辑:只验证注册契约与调用形态(run_auto_transfer/run_daily_recovery 打桩),
真实排程触发由 scheduler 驱动;七元组位序=(total, success, failed,
skipped, results, errors, step_logs),errors 位只放真实错误。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome
from app.services.schedule.job_options import is_known_options_source
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
@@ -22,14 +28,23 @@ def test_receipt_file_job_deregistered():
def test_transfer_job_registered_with_schedule_defaults():
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
"""自动调拨 job 注册且含类型/来源/恢复参数契约;描述不得硬编码时刻。"""
import re
job = get_platform_job("in-transit-transfer")
assert job is not None
assert job.enabled
keys = {field.get("key") for field in job.params_schema}
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
assert {
"transfer_types", "source_codes", "recover_history",
"receipt_from_offset_days", "receipt_to_offset_days",
} <= keys
# 断言:调拨类型=multi_select 动态选项源(启用中的类型配置),留空=全部。
types_field = next(f for f in job.params_schema if f.get("key") == "transfer_types")
assert types_field.get("type") == "multi_select"
assert types_field.get("options_source") == "transfer_types"
assert types_field.get("default") == []
assert is_known_options_source("transfer_types")
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
assert "notify_user_ids" not in keys
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
@@ -133,55 +148,108 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
def test_handler_empty_data_day_stays_silent(monkeypatch):
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
def test_wanted_transfer_types_falls_back_to_all_enabled(monkeypatch):
"""调拨类型留空=全部启用类型;显式选择优先;空配置/脏配置 fail-closed 落错误。"""
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
from app.services.schedule.in_transit_transfer_job import _wanted_transfer_types
errors: list[str] = []
monkeypatch.setattr(type_mod, "get_enabled", lambda: [
SimpleNamespace(code="in_transit_to_hub"), SimpleNamespace(code="hub_repair_out"),
])
assert _wanted_transfer_types({}, errors) == ["in_transit_to_hub", "hub_repair_out"]
assert errors == []
assert _wanted_transfer_types({"transfer_types": ["in_transit_to_hub"]}, errors) == ["in_transit_to_hub"]
assert _wanted_transfer_types({"transfer_types": "hub_to_hub"}, errors) == ["hub_to_hub"]
monkeypatch.setattr(type_mod, "get_enabled", lambda: [])
assert _wanted_transfer_types({}, errors) == []
# 断言:空类型配置不静默——落错误由调用方硬失败(D8 fail-closed)。
assert errors and "调拨类型" in errors[-1]
def test_transfer_types_options_provider_lists_enabled(app, transfer_db):
"""transfer_types 选项源:仅启用类型,label 取 names zh-CN,value=类型编码。"""
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
from app.services.schedule.job_options import list_job_options
seed_transfer_type_config("in_transit_to_hub", enabled=True)
seed_transfer_type_config("hub_repair_out", enabled=False)
transfer_db.session.commit()
options = list_job_options("transfer_types")
codes = {option["value"] for option in options}
# 断言:停用类型不进选项(与排程留空=全部启用类型的口径一致)。
assert "in_transit_to_hub" in codes
assert "hub_repair_out" not in codes
label = next(o["label"] for o in options if o["value"] == "in_transit_to_hub")
assert label == "类型 in_transit_to_hub"
def _patch_schedule_env(monkeypatch, *, types=None, sources=("CRANE_SGP",)):
"""handler 单测公共打桩:来源/类型缺省口径 + 依赖与恢复隔离(不触库)。"""
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
import app.services.schedule.in_transit_transfer_job as job_mod
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: list(sources))
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
monkeypatch.setattr(
type_mod, "get_enabled",
lambda: [SimpleNamespace(code=code) for code in (types if types is not None else ["in_transit_to_hub"])],
)
return job_mod
def test_handler_empty_data_day_stays_silent(monkeypatch):
"""空数据日(全部类型均无 run 且无 errors):置静默标记抑制框架完成卡(C5)。"""
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome()
return AutoTransferOutcome()
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
run = ScheduleRun(run_no="RUNR-1", status="running")
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
total, success, failed, skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
assert "sender" not in captured
assert "recipients" not in captured
# 断言:恢复在循环外只跑一次;run_auto_transfer 恒收 recover_history=False。
assert captured["recover_history"] is False
assert captured["movement_date_from"] is None
assert captured["movement_date_to"] is None
assert captured["source_codes"] == ["CRANE_SGP"]
assert captured["recover_history"] is True
assert captured["transfer_type"] == "in_transit_to_hub"
assert run.response_summary_json["domain_notification_managed"] is True
assert (total, success, failed, skipped) == (0, 0, 0, 0)
assert results == []
assert any("no executable items" in w for w in warnings)
assert results == [] and errors == []
# 断言:恢复汇总与空数据说明落 step_logs(dict),errors 位不受污染。
assert step_logs[0]["step"] == "recovery"
assert any(item.get("step") == "auto_transfer" for item in step_logs)
def test_handler_converts_t_minus_offsets(monkeypatch):
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
from datetime import date
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome()
return AutoTransferOutcome()
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
run = ScheduleRun(run_no="RUNR-4", status="running")
@@ -195,79 +263,227 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
def _must_not_run(**kwargs):
raise AssertionError("run_auto_transfer must not run with invalid offsets")
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
run = ScheduleRun(run_no="RUNR-5", status="running")
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
_total, _success, _failed, _skipped, results, _warnings, errors = (
total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名;
# failed_count=1 使终态为 failed(total=0+errors 会被框架误判 success,禁用)。
assert (total, failed) == (1, 1)
assert results == []
assert any("异动日期起点" in e for e in errors)
assert not (run.response_summary_json or {}).get("domain_notification_managed")
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
_total, _success, _failed, _skipped, _results, _warnings, errors = (
_total, _success, _failed, _skipped, _results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:小数偏移同样快速失败。
assert any("异动日期终点" in e for e in errors)
def test_handler_run_day_uses_framework_notification(monkeypatch):
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
import app.services.schedule.in_transit_transfer_job as job_mod
def test_handler_runs_each_type_once_and_recovery_once(monkeypatch):
"""多类型逐轮执行:每类型一次 run_auto_transfer(recover_history=False),恢复只跑一次。"""
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch, types=["in_transit_to_hub", "hub_repair_out"])
recovery_calls: list[dict] = []
def _fake_recovery(**kwargs):
recovery_calls.append(kwargs)
return RecoveryOutcome(recovered_count=2)
monkeypatch.setattr(job_mod, "run_daily_recovery", _fake_recovery)
calls: list[dict] = []
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
calls.append(kwargs)
return AutoTransferOutcome(run_no=f"TR-{len(calls)}", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={"transfer_types": ["in_transit_to_hub", "hub_repair_out"]})
run = ScheduleRun(run_no="RUNR-6", status="running")
total, success, failed, skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:逐类型各跑一轮且带类型编码;恢复与类型无关只跑一次。
assert [c["transfer_type"] for c in calls] == ["in_transit_to_hub", "hub_repair_out"]
assert all(c["recover_history"] is False for c in calls)
assert len(recovery_calls) == 1
# 断言:total=success+failed+recovered(2 成功 Run + 2 恢复行)。
assert (total, success, failed, skipped) == (4, 2, 0, 0)
assert [r["run_no"] for r in results] == ["TR-1", "TR-2"]
assert errors == []
# 断言:恢复汇总落 step_logs(recovered=2),errors 位只放真实错误。
assert step_logs[0]["step"] == "recovery"
assert step_logs[0]["detail"]["recovered"] == 2
def test_handler_empty_type_config_fails_hard(monkeypatch):
"""类型配置为空:fail-closed 硬失败(failed=1 → 框架 failed 终态),不执行。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch, types=[])
def _must_not_run(**kwargs):
raise AssertionError("run_auto_transfer must not run without transfer types")
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-7", status="running")
total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:空配置硬失败不执行、不静默,错误信息指向类型配置缺失。
assert (total, failed) == (1, 1)
assert results == []
assert any("调拨类型" in e for e in errors)
assert not (run.response_summary_json or {}).get("domain_notification_managed")
def test_handler_run_day_uses_framework_notification(monkeypatch):
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
return AutoTransferOutcome(run_no="TR-1", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-2", status="running")
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
total, success, failed, skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
# 断言:有 run 不抑制框架通知;run_no+类型落入 results 供完成卡/留痕展示。
assert not (run.response_summary_json or {}).get("domain_notification_managed")
assert results and results[0]["run_no"] == "TR-1"
assert results[0]["transfer_type"] == "in_transit_to_hub"
assert (total, success, failed, skipped) == (1, 1, 0, 0)
assert errors == []
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
import app.services.schedule.in_transit_transfer_job as job_mod
def test_handler_recovery_failure_counts_as_failed(monkeypatch):
"""恢复复核抛异常:计一个 failed 单元——防止「恢复失败+空数据日」被框架判 success。"""
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
def _boom(**_kwargs):
raise RuntimeError("stock source offline")
monkeypatch.setattr(job_mod, "run_daily_recovery", _boom)
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
return AutoTransferOutcome() # 各类型均空数据(无 Run 无错误)
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-9", status="running")
total, success, failed, _skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:恢复失败落 errors 且计 failed(终态 failed 交框架失败通知),
# 恢复 step_log 标 failed;不置静默标记。
assert (total, success, failed) == (1, 0, 1)
assert results == []
assert errors == ["recovery_failed: stock source offline"]
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "failed"
assert not (run.response_summary_json or {}).get("domain_notification_managed")
def test_handler_recovery_skipped_marks_step_log(monkeypatch):
"""recover_history=false:恢复不执行,step_log 标 skipped 且不计 failed。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch)
def _must_not_recover(**_kwargs):
raise AssertionError("run_daily_recovery must not run when recover_history is false")
monkeypatch.setattr(job_mod, "run_daily_recovery", _must_not_recover)
monkeypatch.setattr(
job_mod, "run_auto_transfer",
lambda **_kwargs: AutoTransferOutcome(run_no="TR-10", run_status="success"),
)
task = ScheduleTask(job_params={"recover_history": False})
run = ScheduleRun(run_no="RUNR-10", status="running")
total, success, failed, _skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:恢复被跳过(step_log=skipped、无恢复错误),Run 照常产出。
assert (total, success, failed) == (1, 1, 0)
assert results and results[0]["run_no"] == "TR-10"
assert errors == []
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "skipped"
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
return AutoTransferOutcome(errors=["match pipeline boom"])
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-3", status="running")
_total, _success, _failed, _skipped, results, _warnings, errors = (
_total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results,
# 该类型计入 failed_count(终态 failed 交框架失败通知)。
assert not (run.response_summary_json or {}).get("domain_notification_managed")
assert results == []
assert errors == ["match pipeline boom"]
assert failed == 1
def test_handler_type_failure_isolated_per_type(monkeypatch):
"""单类型硬失败不阻断其余类型;失败类型计入 failed,成功类型照常出 Run。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch, types=["bad_type", "in_transit_to_hub"])
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
if kwargs["transfer_type"] == "bad_type":
return AutoTransferOutcome(errors=["type config disabled"])
return AutoTransferOutcome(run_no="TR-9", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-8", status="running")
total, success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:好类型照常执行出 Run;坏类型落 errors 并计入 failed(部分失败终态)。
assert (total, success, failed) == (2, 1, 1)
assert len(results) == 1 and results[0]["transfer_type"] == "in_transit_to_hub"
assert errors == ["type config disabled"]