Merge branch 'hugo-auto-transfer' into dev

This commit is contained in:
hugo committed 2026-10-26 17:58:09 +08:00
commit 00c52fdaae
44 files changed
+1487 -524

No files matched your search

@@ -3,7 +3,7 @@ tests/services/admin/test_shipping_inventory_service.py
用途:验证库存主数据管理服务的安全性和关键业务约束。
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
逻辑:管理后台写配置前锁定用户名可回显、密码与密文不回传、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
"""
from __future__ import annotations
@@ -22,6 +22,7 @@ from app.models import (
FreightRpaSource,
FreightRpaSourceParsingBindingAudit,
FreightRpaOnhandStructureAnalysis,
FreightRpaProfile,
)
@@ -160,15 +161,50 @@ def _published_route_field_id() -> str:
)
def test_profile_credentials_are_not_returned(app):
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
def test_profile_returns_username_and_keeps_password_secret(app):
"""Profile 回执返回用户名明文,密码与密文不得出现。相同用户名再次保存不轮换密文。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
# 用户名是账号标识,管理端需要明文辨认;密码只报告已配置。
assert payload['username'] == 'test-user'
assert payload['password_configured'] is True
assert payload['username_masked'] == 'configured'
assert 'password' not in payload
assert 'ciphertext' not in payload
stored = db.session.get(FreightRpaProfile, payload['id'])
original_username = stored.username_ciphertext
original_password = stored.password_ciphertext
original_updated_at = stored.credential_updated_at
unchanged = _profile_data()
unchanged.pop('password')
unchanged['display_name'] = 'DBS EU renamed'
again = freight_rpa_source_admin_service.save_profile(unchanged, actor_id=None, profile_id=payload['id'])
# 回显后的原用户名随表单提交时,不得重加密或刷新凭据时间。
assert again['username'] == 'test-user'
db.session.refresh(stored)
assert stored.username_ciphertext == original_username
assert stored.password_ciphertext == original_password
assert stored.credential_updated_at == original_updated_at
assert stored.display_name == 'DBS EU renamed'
def test_profile_username_change_reencrypts_without_touching_password(app):
"""只改用户名时重写用户名密文,密码密文保持不变。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
stored = db.session.get(FreightRpaProfile, payload['id'])
original_username = stored.username_ciphertext
original_password = stored.password_ciphertext
changed = _profile_data()
changed.pop('password')
changed['username'] = 'other-user'
updated = freight_rpa_source_admin_service.save_profile(changed, actor_id=None, profile_id=payload['id'])
assert updated['username'] == 'other-user'
db.session.refresh(stored)
assert stored.username_ciphertext != original_username
assert stored.password_ciphertext == original_password
def test_profile_rejects_page_operation_configuration(app):
@@ -620,29 +656,23 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
base_version = profile['config_version']
upload_cfg = {
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
'enabled': True, 'entry_url': 'https://evil.example/steal',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file',
}
updated = freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
)
assert updated['config_version'] == base_version
assert updated['upload_config_json']['enabled'] is True
assert updated['upload_config_json'] == {'enabled': True}
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
bumped = freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
actor_id=None, profile_id=profile['id'],
)
assert bumped['config_version'] == base_version + 1
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
# 上传配置必须是对象;页面字段不再作为校验对象。
with pytest.raises(ValidationError):
freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
actor_id=None, profile_id=profile['id'],
)
with pytest.raises(ValidationError):
freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
{**_profile_data(), 'upload_config_json': 'not-an-object'},
actor_id=None, profile_id=profile['id'],
)
@@ -0,0 +1,100 @@
"""
backend/tests/services/freight_rpa/test_crane_upload_recheck.py
用途:验证上传配置只保留开关,以及 Crane 分配中只排一次定时回查。
依赖:page_contract、upload_attempt_service、crane_recheck、Flask 测试库。
逻辑:先断言入口 URL 和行分类,再走 complete_attempt、定时回查和手动刷新。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app import db
from app.core.errors import ConflictError
from app.services.freight_rpa.upload.crane_recheck import (
fire_scheduled_crane_recheck,
request_manual_crane_refresh,
)
from app.services.freight_rpa.upload.page_contract import (
build_upload_entry_url,
classify_crane_order_row,
)
from app.services.shipping_notice.upload_attempt_service import (
complete_attempt,
project_notice_upload_status,
start_rpa_attempt,
)
from tests.test_shipping_upload_attempt import _ready_artifact
def test_upload_entry_url_comes_from_login_host_and_crane_row_is_classified():
"""DBS/Crane 上传页由登录主机拼接;只有两句固定文案分别表示已分配和分配中。"""
assert build_upload_entry_url('dbs', 'https://s360.dbschenker.com/login') == (
'https://s360.dbschenker.com/main/portal/frame/WMSUpload2'
)
assert build_upload_entry_url('crane', 'https://wms-portal.craneww.com/') == (
'https://wms-portal.craneww.com/#/shipping-order-upload'
)
assert classify_crane_order_row('Processing', 'Shipping Order Allocated') == 'allocated'
assert classify_crane_order_row('Processing', 'Allocating the Shipping Order') == 'allocating'
assert classify_crane_order_row('Completed', 'Shipping Order Allocated') == 'other'
def test_allocating_schedules_one_recheck_and_blocks_another_upload(app):
"""首次分配中写下 10 分钟回查;第二次回调不改到期时间,也不能重新上传。"""
with app.app_context():
notice, artifact, _reservation = _ready_artifact()
artifact.file_name = 'MXI26082801.xlsx'
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key')
started = datetime(2026, 10, 23, 3, 0, 0)
complete_attempt(attempt, success=False, callback_id='upload-1', result='allocating')
# remember 使用 utcnow;这里只断言间隔为 10 分钟,不绑定测试开始时刻。
due_at = datetime.fromisoformat(attempt.success_evidence_json['crane_recheck']['due_at'])
assert timedelta(minutes=9) < due_at - datetime.utcnow() <= timedelta(minutes=10)
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
assert project_notice_upload_status(notice) == 'allocating'
complete_attempt(attempt, success=False, callback_id='recheck-1', result='allocating')
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at.isoformat(timespec='seconds')
with pytest.raises(ConflictError) as blocked:
start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key-2')
assert blocked.value.code == 'SHIPPING.UPLOAD_CRANE_ALLOCATING'
assert started < due_at
def test_manual_refresh_does_not_move_the_one_scheduled_recheck(app):
"""手动刷新另写一条状态回查,不改定时到期时间,也不把定时标记成已触发。"""
with app.app_context():
notice, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-manual')
complete_attempt(attempt, success=False, callback_id='upload-manual', result='allocating')
due_at = attempt.success_evidence_json['crane_recheck']['due_at']
source = {'login_url': 'https://wms-portal.craneww.com/', 'connector_type': 'crane'}
first = request_manual_crane_refresh(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
)
assert first.endswith(f'upload_recheck_{notice.task_no}_manual.json')
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
with pytest.raises(ConflictError) as inflight:
request_manual_crane_refresh(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
)
assert inflight.value.code == 'SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT'
future = datetime.fromisoformat(due_at) + timedelta(seconds=1)
assert fire_scheduled_crane_recheck(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
) is True
assert fire_scheduled_crane_recheck(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
) is False
db.session.refresh(attempt)
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
assert attempt.success_evidence_json['crane_recheck']['fired'] is True
@@ -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):
@@ -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"]
+1 -1
View File
@@ -1410,7 +1410,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
assert events[0] == ("session", "https://s360.dbschenker.com/")
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
assert ("file", "#file2") in events
assert ("file", "input#file2") in events
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events