Files
syops/backend/tests/test_freight_rpa_outbound_callback.py
hugoandCursor 4c2a7e2a23 feat(in-transit-transfer): 落地证据流重解析并纳入货代与排程配套改动
外部单号进入异动档自然键,圈档按 T-2 成熟封顶,当前归档可单独重解析。同批带上 Crane 禁整页刷新、ODM 白名单降级、排程抽屉与执行记录日期窗,以及 YAML 库存源下线。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 00:48:37 +08:00

303 lines
13 KiB
Python
Raw Permalink 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.
"""
tests/test_freight_rpa_outbound_callback.py
用途:锁定出站 RPA 回调跨机路径契约、schema 校验与 ingest 归档投递。
依赖:pytest、app 夹具、freight_rpa.outbound.report_archive、
freight_rpa.reports.dispatch、freight_rpa API 蓝图。
逻辑:Worker(Windows)与后端(Linux)分属两机;file_path 只认 outbound drop
根内文件名。本文件先锁 Windows 绝对路径 / 裸文件名 / 穿越拒绝,再锁
schema 4xx、ingest 归档后 dispatch_report_fact,以及三条回调路由鉴权。
"""
from __future__ import annotations
import hashlib
import pytest
@pytest.fixture(autouse=True)
def _isolate_callback_registries():
"""隔离 sink / report handler 注册表,避免测内临时 register 串扰其它用例。"""
from app.services.freight_rpa.common import callback_sinks
from app.services.freight_rpa.reports import dispatch as dispatch_module
saved_sinks = dict(callback_sinks._SINKS)
saved_handlers = dict(dispatch_module._REPORT_HANDLERS)
yield
callback_sinks._SINKS.clear()
callback_sinks._SINKS.update(saved_sinks)
dispatch_module._REPORT_HANDLERS.clear()
dispatch_module._REPORT_HANDLERS.update(saved_handlers)
def test_read_outbound_callback_file_accepts_windows_absolute_path(tmp_path, app):
"""Worker 上报 C:\\...\\drop\\foo.xlsx 时,Linux 侧只按文件名拼本机 drop 根。"""
drop = tmp_path / "outbound_drop"
drop.mkdir()
target = drop / "foo.xlsx"
target.write_bytes(b"PK\x03\x04fake")
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file
data = _read_outbound_callback_file(r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx")
assert data.startswith(b"PK")
def test_read_outbound_callback_file_accepts_bare_filename(tmp_path, app):
"""file_path 仅为 foo.xlsx 时同样定位到本机 outbound drop 根内同名文件。"""
drop = tmp_path / "outbound_drop"
drop.mkdir()
target = drop / "foo.xlsx"
target.write_bytes(b"PK\x03\x04fake")
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file
data = _read_outbound_callback_file("foo.xlsx")
assert data.startswith(b"PK")
def test_read_outbound_callback_file_rejects_traversal(tmp_path, app):
"""带 ..\\ 的路径必须拒绝,禁止按 Linux 路径打开 Worker 上报串。"""
drop = tmp_path / "outbound_drop"
drop.mkdir()
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file
from app.core.errors import ValidationError
with pytest.raises(ValidationError):
_read_outbound_callback_file(r"..\..\etc\passwd")
def test_ingest_outbound_callback_rejects_invalid_schema(app):
"""错误 schema_version 必须在 commit / 投递之前以 4xx ValidationError 失败。"""
from app.core.errors import ValidationError
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
with app.app_context():
with pytest.raises(ValidationError) as excinfo:
ingest_outbound_callback({"schema_version": "freight_rpa.inbound.v1", "callback_id": "x"})
assert excinfo.value.http_status == 400
assert excinfo.value.code == "SHIPPING.OUTBOUND_CALLBACK_INVALID"
TEST_TOOL_KEY = "test-tool-key"
SEED_SOURCE_CODE = "DSV360_AWSDU"
def _awaiting_outbound_unit(*, callback_id: str):
"""构造 awaiting_rpa 出站单元,source_id 挂种子站点以满足外键。"""
from app.models import FreightRpaOutboundUnitRun, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
return FreightRpaOutboundUnitRun(
source_id=source.id,
source_code=source.source_code,
connector_type="dbs",
callback_id=callback_id,
status="awaiting_rpa",
config_snapshot_json={},
)
def test_outbound_batch_ready_sink_finalizes_schedule_even_if_fact_handler_raises(
tmp_path, app, monkeypatch,
):
"""文件归档单元终态后,事实/证据处理失败仍须收口排程(文件返回= RPA 结束)。
[断言意图] batch-ready sink 在 finally 中 finalize;不得依赖 handle_outbound_report 成功。
"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaOutboundUnitRun
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.rpa_sinks import _outbound_batch_ready_sink
drop = tmp_path / "outbound_drop"
drop.mkdir()
payload_bytes = b"PK\x03\x04fake"
(drop / "foo.xlsx").write_bytes(payload_bytes)
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
task = ScheduleTask(
schedule_no="SCH-OUTBOUND-FILE-FINAL",
name="Outbound file finalize",
schedule_type="platform_job",
platform_api_path="freight-rpa-outbound",
owner_user_id=1,
cron_expr="0 8 * * *",
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no="RUN-OUTBOUND-FILE-FINAL",
schedule_task_id=task.id,
status="running",
total_count=1,
success_count=0,
failed_count=0,
skipped_count=0,
response_summary_json={"awaiting_outbound_rpa": True},
)
db.session.add(run)
db.session.flush()
unit = _awaiting_outbound_unit(callback_id="outbound-file-final-cb")
unit.schedule_run_id = run.id
db.session.add(unit)
db.session.commit()
monkeypatch.setattr(
"app.services.freight_rpa.outbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
def _boom(_fact):
raise RuntimeError("evidence sync exploded")
register_report_handler("outbound", _boom)
payload = {
"schema_version": "freight_rpa.outbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx",
"original_filename": "foo.xlsx",
"sha256": hashlib.sha256(payload_bytes).hexdigest(),
}
with pytest.raises(RuntimeError, match="evidence sync exploded"):
_outbound_batch_ready_sink(**payload)
db.session.expire_all()
refreshed = db.session.get(ScheduleRun, run.id)
assert refreshed.status == "success"
assert (refreshed.response_summary_json or {}).get("awaiting_outbound_rpa") is False
assert db.session.get(FreightRpaOutboundUnitRun, unit.id).status == "success"
def test_ingest_outbound_callback_archives_and_dispatches_fact(tmp_path, app, monkeypatch):
"""success 回调按 Windows 绝对路径只认文件名归档,并投递 report_kind=outbound 事实。"""
from app import db
from app.models import FreightRpaOutboundReportFile
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
drop = tmp_path / "outbound_drop"
drop.mkdir()
payload_bytes = b"PK\x03\x04fake"
(drop / "foo.xlsx").write_bytes(payload_bytes)
with app.app_context():
app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop)
unit = _awaiting_outbound_unit(callback_id="outbound-cb-archive")
db.session.add(unit)
db.session.commit()
monkeypatch.setattr(
"app.services.freight_rpa.outbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
seen: list[ReportFact] = []
register_report_handler("outbound", seen.append)
result = ingest_outbound_callback({
"schema_version": "freight_rpa.outbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx",
"original_filename": "foo.xlsx",
"sha256": hashlib.sha256(payload_bytes).hexdigest(),
})
assert result["status"] == "success"
assert FreightRpaOutboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
assert len(seen) == 1
fact = seen[0]
assert fact.report_kind == "outbound"
assert fact.ok is True
assert fact.file_id == result["file_id"]
assert fact.unit_run_id == unit.id
def test_ingest_outbound_empty_dispatches_failure_fact(app):
"""empty 终态先 commit 再投递 ok=False 事实,不读 drop 文件。"""
from app import db
from app.models import FreightRpaOutboundUnitRun
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
with app.app_context():
unit = _awaiting_outbound_unit(callback_id="outbound-cb-empty")
db.session.add(unit)
db.session.commit()
seen: list[ReportFact] = []
register_report_handler("outbound", seen.append)
result = ingest_outbound_callback({
"schema_version": "freight_rpa.outbound.v1",
"callback_id": unit.callback_id,
"status": "empty",
"error_code": "no_outbound_data",
"error_message": "no_outbound_data",
})
assert result["status"] == "empty"
db.session.expire_all()
saved = db.session.get(FreightRpaOutboundUnitRun, unit.id)
assert saved.status == "empty"
assert saved.error_code == "no_outbound_data"
assert len(seen) == 1
assert seen[0].report_kind == "outbound"
assert seen[0].ok is False
assert seen[0].error_code == "no_outbound_data"
def test_outbound_callback_routes_require_auth(client, app):
"""三条出站回调路由与入站同 ToolApiKey:无 Header 必须 401。"""
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY
for path in (
"/api/freight-rpa/outbound-batch-ready",
"/api/freight-rpa/outbound-unit-progress",
"/api/freight-rpa/outbound-batch-progress",
):
assert client.post(path, json={}).status_code == 401, path
def test_outbound_callback_routes_are_registered(client, app):
"""组合根已注册 outbound sinks:空载荷不得 404 SINK_NOT_REGISTERED。
核心逻辑:batch-ready 空载荷穿透到 ingest 业务校验(400);
progress 空载荷走 schema 非法分支(200 + updated=False)。
"""
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY
headers = {"Authorization": f"Bearer {TEST_TOOL_KEY}"}
ready = client.post("/api/freight-rpa/outbound-batch-ready", json={}, headers=headers)
assert ready.status_code == 400, ready.get_json()
assert ready.get_json()["error"]["code"] == "SHIPPING.OUTBOUND_CALLBACK_INVALID"
for path in (
"/api/freight-rpa/outbound-unit-progress",
"/api/freight-rpa/outbound-batch-progress",
):
resp = client.post(path, json={}, headers=headers)
assert resp.status_code == 200, (path, resp.status_code, resp.get_json())
body = resp.get_json()
assert body["success"] is True
assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"}
def test_outbound_batch_ready_invalid_schema_is_400_when_sink_registered(client, app):
"""sink 在测内临时注册后,错误 schema 穿透到 ingest → 400 SHIPPING.OUTBOUND_CALLBACK_INVALID。"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
def _ready_sink(**payload):
return {"success": True, "data": ingest_outbound_callback(payload)}
register_sink("outbound-batch-ready", _ready_sink)
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY
resp = client.post(
"/api/freight-rpa/outbound-batch-ready",
json={},
headers={"Authorization": f"Bearer {TEST_TOOL_KEY}"},
)
assert resp.status_code == 400
assert resp.get_json()["error"]["code"] == "SHIPPING.OUTBOUND_CALLBACK_INVALID"