feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa

把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-19 10:46:06 +08:00
1 parent ffc0d4a430
commit 39fe3c05f2
453 files changed
+17945 -8646

No files matched your search

@@ -1,9 +1,12 @@
"""freight_rpa 包 import 边界适应度测试。
用途:锁死阶段 A 验收标准——freight_rpa 不寄生业务编排。
用途:锁死阶段 B 验收标准——freight_rpa 不寄生业务编排。
依赖:app/services/freight_rpa 包、ast。
逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败;
白名单是 RPA 归档/凭据所需的两块业务工具(阶段 B 收敛为零)。
白名单为空集(批次 B Task 6 起审计写入已下沉本包
common/report_audit,包内不再引用任何 shipping_notice 业务模块;
历史 file_assets 白名单条目随迁移一并删除——包内只引用
app.services.file_assets,不属 shipping_notice 命名空间)。
"""
from __future__ import annotations
@@ -12,10 +15,9 @@ from pathlib import Path
PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa"
ALLOWED_SHIPPING_NOTICE = {
"app.services.shipping_notice.audit_service",
"app.services.shipping_notice.file_assets",
}
# 空集:freight_rpa 禁止 import 任何 app.services.shipping_notice.* 模块
# (审计写入走本包 common/report_audit;模型 import 走 app.models,不在此列)。
ALLOWED_SHIPPING_NOTICE: set[str] = set()
def _imported_modules(path: Path) -> set[str]:
@@ -28,7 +30,6 @@ def _imported_modules(path: Path) -> set[str]:
mods.add(node.module)
return mods
def test_freight_rpa_import_boundary():
assert PKG.exists(), "freight_rpa 包不存在"
violations: list[str] = []
@@ -0,0 +1,196 @@
"""tests/services/freight_rpa/test_report_fact_dispatch.py
用途:锁定阶段 B Task 6——inbound 回调「先提交文件/终态,再投递事实」的顺序契约。
依赖:pytest、tests/conftest 的 app 夹具(种子站点 DSV360_AWSDU)、
app.core.errors.AppError、app.services.freight_rpa.reports.facts.ReportFact、
freight_rpa.reports.dispatch.register_report_handler(Task 6 新增)、
freight_rpa.inbound.report_archive.ingest_inbound_callback。
逻辑:(1)处理函数抛异常时已 commit 的归档文件行仍在(不回滚)且异常原样外抛;
(2)同一 unit_run_id + sha256 重复回调不插第二行,事实仍重复投递 ok=True
(供处理函数重试);(3)kind 未注册处理函数时 404
FREIGHT_RPA.SINK_NOT_REGISTERED,已提交文件行不受影响;
(4)empty 终态同样先 commit 再投递 ok=False 事实。
"""
from __future__ import annotations
import hashlib
import pytest
from app.services.freight_rpa.reports.facts import ReportFact
SEED_SOURCE_CODE = "DSV360_AWSDU"
# 归档 IO 替身的注入字节:_fake_archive_io 夹具把它喂给
# _read_inbound_callback_file,_success_payload 按需覆写。
_FAKE_FILE_BYTES: dict[str, bytes] = {"data": b"abc"}
# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。
_CALLBACK_SEQ: dict[str, int] = {"n": 0}
@pytest.fixture
def db_session(app):
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
@pytest.fixture(autouse=True)
def _reset_report_handlers():
"""每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。
[断言意图] 缺处理器用例必须跑在"干净注册表"上——否则前序用例注册的
inbound 处理函数会让 404 用例假绿。
"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
saved = dict(dispatch_module._REPORT_HANDLERS)
dispatch_module._REPORT_HANDLERS.clear()
yield
dispatch_module._REPORT_HANDLERS.clear()
dispatch_module._REPORT_HANDLERS.update(saved)
@pytest.fixture(autouse=True)
def _fake_archive_io(monkeypatch):
"""替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。
核心逻辑:与旧回调测试同一 monkeypatch 姿态(patch report_archive 模块属性),
使 ingest 的 success 分支可脱离真实文件系统与对象存储走完全程。
"""
from app.services.freight_rpa.inbound import report_archive
monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: _FAKE_FILE_BYTES["data"])
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
def _next_callback_id(prefix: str) -> str:
"""生成跨用例唯一的 callback_id(满足 unit run 唯一约束)。"""
_CALLBACK_SEQ["n"] += 1
return f"{prefix}-{_CALLBACK_SEQ['n']}"
def _awaiting_unit(*, source_code: str = "DSV"):
"""构造一个处于 awaiting_rpa 的 inbound 执行单元(挂种子站点满足外键)。
核心逻辑:source_code 列允许测试值(如 "DSV"),source_id 外键挂种子站点
DSV360_AWSDU——与 test_report_queries.py 的 _inbound_file 同构。
"""
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
return FreightRpaInboundUnitRun(
source_id=source.id,
source_code=source_code,
connector_type="dbs",
callback_id=_next_callback_id("report-fact-dispatch"),
status="awaiting_rpa",
config_snapshot_json={},
)
def _success_payload(unit, *, sha256_file: bytes = b"abc") -> dict:
"""构造通过 schema 校验的 success 回调载荷;sha256_file 即被模拟读取的 xlsx 字节。"""
_FAKE_FILE_BYTES["data"] = sha256_file
return {
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": f"receipt_{unit.id or 'x'}.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(sha256_file).hexdigest(),
}
def test_handler_failure_keeps_committed_file(app, db_session, monkeypatch):
"""处理函数失败绝不回滚已 commit 的归档文件行,异常原样外抛(不吞)。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
def boom(fact: ReportFact) -> None:
raise RuntimeError("handler down")
register_report_handler("inbound", boom)
with pytest.raises(RuntimeError, match="handler down"):
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
# [断言意图] 异常外抛但文件行已提交:count==1 锁死「先 commit 再投递」顺序。
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
def test_second_delivery_does_not_insert_another_file(app, db_session):
"""同一回调重放不插第二行文件,事实仍重复投递(同一 file_id、ok=True)。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
seen: list[ReportFact] = []
register_report_handler("inbound", seen.append)
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
payload = _success_payload(unit, sha256_file=b"abc")
ingest_inbound_callback(payload)
ingest_inbound_callback(payload)
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
# [断言意图] 幂等重放仍两次投递 ok=True 事实(同一 file_id),供处理函数重试。
assert [fact.file_id for fact in seen] == [seen[0].file_id, seen[0].file_id]
assert all(fact.ok is True for fact in seen)
def test_missing_handler_raises_sink_not_registered(app, db_session):
"""kind 未注册处理函数 → 404 FREIGHT_RPA.SINK_NOT_REGISTERED,文件行已提交。"""
from app.core.errors import AppError
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
with pytest.raises(AppError) as exc:
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
# [断言意图] 分发失败不回滚归档:文件行保留,Worker 重试整笔回调即可补投递。
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
def test_empty_callback_dispatches_failure_fact(app, db_session):
"""empty 终态同样先 commit 再投递 ok=False 事实(error_code 随载荷落库值)。"""
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
seen: list[ReportFact] = []
register_report_handler("inbound", seen.append)
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
result = ingest_inbound_callback(
{
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "empty",
"error_code": "no_receipt_data",
"error_message": "no_receipt_data",
}
)
assert result["status"] == "empty"
assert len(seen) == 1
fact = seen[0]
# [断言意图] empty 是合法业务结果 → ok=False + error_code=no_receipt_data 的事实。
assert fact.report_kind == "inbound"
assert fact.source_code == "DSV"
assert fact.ok is False
assert fact.file_id is None
assert fact.sha256 is None
assert fact.error_code == "no_receipt_data"
assert fact.error_message == "no_receipt_data"
@@ -0,0 +1,282 @@
"""tests/services/freight_rpa/test_report_queries.py
用途:锁定阶段 B Task 3——freight_rpa.reports 只读查询模块的行为契约。
依赖:pytest、app fixture(tests/conftest)、app.core.errors、
app.services.freight_rpa.reports(待实现模块)。
逻辑:覆盖(1)latest_usable_inbound_file 的可用门禁——未删除、当天
(Asia/Shanghai 业务日)抓取、未过期、最新优先;(2)require_report_kind 的
白名单校验;(3)站点/在手/入站配置只读视图;(4)按 storage_key 读文件
字节 + 缺文件 NotFoundError;(5)解析失败三列的标记与清除(仅 flush
不 commit)。(6)业务日窗口内外的定向拒收/放行。
时间口径:查询的 now 参数显式传 naive UTC;文件 created_at 也按 naive UTC
存入,两者用同一业务日窗口锚点(now=2026-10-05 12:00 UTC → 上海业务日
10-05,UTC 窗口 [10-04 16:00, 10-05 16:00))。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app.core.errors import NotFoundError, ValidationError
from app.services.freight_rpa.reports import (
clear_inbound_parse_failure,
get_inbound_config,
get_onhand_config,
get_site,
latest_usable_inbound_file,
mark_inbound_parse_failure,
read_inbound_file_bytes,
require_report_kind,
)
SEED_SOURCE_CODE = "DSV360_AWSDU"
# 业务日窗口锚点(naive UTC):2026-10-05 12:00 UTC = 上海 10-05 20:00,
# 对应业务日 2026-10-05 的 UTC 存储窗口 [10-04 16:00, 10-05 16:00)。
FROZEN_NOW = datetime(2026, 10, 5, 12, 0, 0)
@pytest.fixture
def db_session(app):
"""复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
def _inbound_file(*, source_code: str, sha256: str, created_at: datetime, **overrides):
"""构造一条挂在指定 source_code 执行单元下的入站归档文件(含 unit run)。
核心逻辑:外键要求文件必须挂在 FreightRpaInboundUnitRun 下,unit run 再挂
种子站点(DSV360_AWSDU);source_code 写进 unit run 列(非外键,允许 "DSV"
等测试值),便于验证查询按 unit run 的 source_code 过滤。
"""
from app import db
from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
unit = FreightRpaInboundUnitRun(
source_id=source.id,
source_code=source_code,
connector_type="dbs",
callback_id=f"test-callback:{source_code}:{sha256[:8]}",
status="success",
config_snapshot_json={},
**overrides,
)
db.session.add(unit)
db.session.flush()
report_file = FreightRpaInboundReportFile(
unit_run_id=unit.id,
storage_provider="minio",
storage_bucket="test",
storage_key=f"freight_rpa/inbound/{source_code}/{sha256[:12]}.xlsx",
original_filename=f"{sha256[:8]}.xlsx",
file_size=16,
sha256=sha256,
created_at=created_at,
)
db.session.add(report_file)
return report_file
def test_latest_usable_inbound_file_returns_newest(app, db_session):
"""同一业务日窗口内的两份可用文件 → 按 created_at 倒序取最新一份。
[断言意图] 两份文件的 created_at 均落在 FROZEN_NOW 的业务日 UTC 窗口
([10-04 16:00, 10-05 16:00))内,证明「最新优先」在当天门禁内生效,
而不是因为当天新鲜度被丢掉才命中。
"""
older = _inbound_file(source_code="DSV", sha256="a" * 64, created_at=datetime(2026, 10, 4, 18, 0, 0))
newer = _inbound_file(source_code="DSV", sha256="b" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0))
db_session.add_all([older, newer])
db_session.commit()
view = latest_usable_inbound_file("DSV", now=FROZEN_NOW)
assert view is not None
assert view.file_id == newer.id
assert view.sha256 == "b" * 64
def test_latest_usable_inbound_file_rejects_out_of_business_day(app, db_session):
"""「当天(Asia/Shanghai 业务日)抓取」是可用门禁的一部分:隔日文件不可用。
[断言意图] 同一份文件(expries 为空、未删除)在非当天业务日查 → None;
把判定时刻推回文件被抓取的那个业务日 → 又可用;差异只能来自当天窗口,
锁死修复轮补回的新鲜度条件。
"""
report = _inbound_file(source_code="STL", sha256="0" * 64, created_at=datetime(2026, 10, 3, 10, 0, 0))
db_session.commit()
# FROZEN_NOW(业务日 10-05)下,10-03 抓取的文件是隔日旧文件 → 不可用。
assert latest_usable_inbound_file("STL", now=FROZEN_NOW) is None
# 业务日 10-03 的窗口为 UTC [10-02 16:00, 10-03 16:00):10-03 10:00 UTC 在窗口内 → 可用。
in_day_now = datetime(2026, 10, 3, 12, 0, 0)
view = latest_usable_inbound_file("STL", now=in_day_now)
assert view is not None
assert view.file_id == report.id
def test_latest_usable_inbound_file_skips_deleted_and_expired(app, db_session):
"""已删除/已过期的文件不得被当作可用文件返回;同来源保留最新可用一份。"""
# [断言意图] 三份文件都在 FROZEN_NOW 的业务日窗口内,且已删除/已过期两份
# 更新——若门禁失效,“最新优先”会先命中它们;断言只能命中唯一的可用文件。
usable = _inbound_file(source_code="CRN", sha256="c" * 64, created_at=datetime(2026, 10, 4, 20, 0, 0))
deleted = _inbound_file(source_code="CRN", sha256="d" * 64, created_at=datetime(2026, 10, 5, 1, 0, 0))
deleted.archive_deleted_at = datetime(2026, 10, 5, 5, 0, 0)
expired = _inbound_file(source_code="CRN", sha256="e" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0))
# 保留期早于判定时刻(仍未被清理任务删除)→ 过期不可用。
expired.archive_expires_at = FROZEN_NOW - timedelta(hours=1)
db_session.add_all([usable, deleted, expired])
db_session.commit()
view = latest_usable_inbound_file("CRN", now=FROZEN_NOW)
assert view is not None
assert view.sha256 == "c" * 64
assert view.source_code == "CRN"
assert view.storage_key.endswith(f"{'c' * 12}.xlsx")
assert view.original_filename == f"{'c' * 8}.xlsx"
assert view.created_at == datetime(2026, 10, 4, 20, 0, 0)
def test_latest_usable_inbound_file_no_match_returns_none(app, db_session):
"""来源无任何归档文件(或全部不可用)时返回 None,不抛异常。"""
assert latest_usable_inbound_file("NOPE") is None
def test_report_kind_rejects_shipment():
with pytest.raises(ValidationError):
require_report_kind("shipment")
assert require_report_kind("outbound") == "outbound"
def test_get_site_returns_view_of_seeded_source(app):
"""get_site 返回站点连接与模板绑定的只读视图;未知来源返回 None。"""
view = get_site(SEED_SOURCE_CODE)
assert view is not None
assert view.source_code == SEED_SOURCE_CODE
assert view.display_name == "DBS Dublin AWSDU"
assert view.connector_type == "dbs"
assert view.excel_template_id is not None
assert view.enabled is True
assert get_site("NOPE") is None
def test_get_onhand_config_returns_report_definition(app):
"""get_onhand_config 返回 s18 起挂在配置行上的报表路径/查询条件/解析方案。"""
config = get_onhand_config(SEED_SOURCE_CODE)
assert config is not None
assert config.report_path_json.get("program_group") == "Bison"
assert config.query_parameters_json == [
{"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "required": True, "select_all": False},
]
assert config.parsing_profile_id is not None
# [断言意图] 未知来源与存在但未配置报表的来源都必须返回 None(fail-closed)。
assert get_onhand_config("NOPE") is None
def test_get_inbound_config_returns_none_without_config_row(app):
"""种子站点没有入站报表配置行 → get_inbound_config 返回 None。"""
from app import db
from app.models import FreightRpaInboundReportConfig, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
assert get_inbound_config(SEED_SOURCE_CODE) is None
# [断言意图] 补一条配置行后即可读出三个字段(与在手配置视图同构)。
db.session.add(FreightRpaInboundReportConfig(
source=source,
report_path_json={"program_group": "Bison", "report_name": "Receipt"},
query_parameters_json=[{"name": "Date", "mode": "range"}],
parsing_profile_id=None,
))
db.session.commit()
config = get_inbound_config(SEED_SOURCE_CODE)
assert config is not None
assert config.report_path_json["report_name"] == "Receipt"
assert config.query_parameters_json == [{"name": "Date", "mode": "range"}]
assert config.parsing_profile_id is None
def test_read_inbound_file_bytes_reads_by_storage_key(app, db_session, monkeypatch):
"""read_inbound_file_bytes 按文件的 storage_key 调 file_asset_storage 读取。"""
from app.services.freight_rpa.reports import queries as queries_module
report_file = _inbound_file(source_code="DSV", sha256="f" * 64, created_at=datetime(2026, 10, 6))
db_session.commit()
captured: dict[str, bytes] = {}
def fake_get_bytes(storage_key):
captured["key"] = storage_key
return b"xlsx-bytes"
monkeypatch.setattr(queries_module.file_asset_storage, "get_bytes", fake_get_bytes)
assert read_inbound_file_bytes(report_file.id) == b"xlsx-bytes"
assert captured["key"] == report_file.storage_key
def test_read_inbound_file_bytes_missing_file_raises(app):
"""文件 id 不存在 → NotFoundError(fail-closed,不吞 404)。"""
with pytest.raises(NotFoundError):
read_inbound_file_bytes(999999)
def test_mark_and_clear_inbound_parse_failure_roundtrip(app, db_session):
"""mark 写入三列并 flush(不 commit 由调用方决定);clear 清空恢复。"""
from datetime import timedelta
report_file = _inbound_file(source_code="DSV", sha256="9" * 64, created_at=datetime(2026, 10, 7))
db_session.commit()
file_id = report_file.id
mark_inbound_parse_failure(
file_id,
error_code="X" * 80,
error_message="m" * 2500,
)
# [断言意图] 只 flush 不 commit——新开的同一事务查询立即可见,且列宽截断生效。
from app import db
from app.models import FreightRpaInboundReportFile
marked = db.session.get(FreightRpaInboundReportFile, file_id)
assert marked.parse_failed_at is not None
assert marked.parse_failed_at > datetime.utcnow() - timedelta(minutes=1)
assert marked.parse_error_code == "X" * 64
assert marked.parse_error_message == "m" * 2000
db_session.commit()
clear_inbound_parse_failure(file_id)
cleared = db.session.get(FreightRpaInboundReportFile, file_id)
assert cleared.parse_failed_at is None
assert cleared.parse_error_code is None
assert cleared.parse_error_message is None
db_session.commit()
def test_mark_inbound_parse_failure_missing_file_raises(app):
"""文件 id 不存在 → NotFoundError,与其他按 id 操作一致。"""
with pytest.raises(NotFoundError):
mark_inbound_parse_failure(999999, error_code="E", error_message="m")
def test_import_boundary_no_business_module_imports():
"""本模块(发货与调拨读报表唯一入口)不得 import shipping_notice / in_transit_transfer。"""
import ast
from pathlib import Path
pkg = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" / "reports"
assert pkg.exists()
for py in pkg.rglob("*.py"):
tree = ast.parse(py.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
mods = [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom) and node.module:
mods = [node.module]
else:
continue
for mod in mods:
assert not mod.startswith("app.services.shipping_notice"), f"{py.name}: {mod}"
assert not mod.startswith("app.services.in_transit_transfer"), f"{py.name}: {mod}"
@@ -0,0 +1,59 @@
"""
backend/tests/services/freight_rpa/test_upload_trigger_contract.py
用途:锁死 upload trigger 写入契约——action 与心跳能力 freight_rpa_upload 对齐,schema 为 freight_rpa.upload.v1。
依赖:app.services.freight_rpa.upload.trigger_io、Flask app fixture。
逻辑:断言模块常量;write_upload_trigger 落盘后 JSON 的 action/schema_version 与常量一致。
"""
from __future__ import annotations
import json
from pathlib import Path
from app.services.freight_rpa.common.worker_heartbeat import FREIGHT_RPA_UPLOAD_CAPABILITY
from app.services.freight_rpa.upload import trigger_io
def test_upload_trigger_constants_align_with_heartbeat_capability():
"""upload action 必须与 Worker 心跳能力串 freight_rpa_upload 一致。"""
assert trigger_io.SCHEMA == "freight_rpa.upload.v1"
assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == "freight_rpa_upload"
assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == FREIGHT_RPA_UPLOAD_CAPABILITY
assert "outbound_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD
assert "shipment_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD
def test_write_upload_trigger_persists_freight_upload_action(app, tmp_path):
"""落盘 trigger JSON 的 action/schema_version 须与模块常量一致。"""
export_file = tmp_path / "queue_src" / "SN-001.xlsx"
export_file.parent.mkdir(parents=True)
export_file.write_bytes(b"fake-xlsx")
upload_queue = tmp_path / "upload_queue"
upload_trigger = tmp_path / "upload_triggers"
upload_queue.mkdir()
upload_trigger.mkdir()
with app.app_context():
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
queue_path, trigger_path, callback_id = trigger_io.write_upload_trigger(
"TASK-UP-1",
str(export_file),
attempt_id=10,
artifact_id=20,
connector_type="dbs",
callback_id="upload-cb-1",
)
assert queue_path
assert trigger_path
assert callback_id == "upload-cb-1"
payload = json.loads(Path(trigger_path).read_text(encoding="utf-8"))
# [断言意图] Worker 侧不校验 action 字面量,但双侧契约文档须与心跳能力 freight_rpa_upload 对齐。
assert payload["action"] == trigger_io.ACTION_FREIGHT_RPA_UPLOAD
assert payload["schema_version"] == trigger_io.SCHEMA
assert payload["action"] == "freight_rpa_upload"
assert payload["schema_version"] == "freight_rpa.upload.v1"
@@ -15,7 +15,7 @@ import pytest
from app.core.errors import ServiceUnavailableError
from app.services.freight_rpa.common.worker_heartbeat import (
FREIGHT_UPLOAD_CAPABILITY,
FREIGHT_RPA_UPLOAD_CAPABILITY,
ONHAND_EXPORT_CAPABILITY,
INBOUND_EXPORT_CAPABILITY,
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
@@ -306,7 +306,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
from app.services.freight_rpa.common.worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
@@ -337,7 +337,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
db.session.add(run)
db.session.commit()
total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
total, success, failed, skipped, _details, errors, logs = run_freight_rpa_onhand_schedule(task, run)
assert total >= 1
assert success == 0
assert failed >= 1
@@ -461,20 +461,20 @@ def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app,
)
)
result = check_freight_upload_rpa_ready()
# 关键断言:缺少 freight_upload 能力必须阻断自动上传。
# 关键断言:缺少 freight_rpa_upload 能力必须阻断自动上传。
assert result.ready is False
assert any("missing_freight_upload_capability" in reason for reason in result.reasons)
assert any("missing_freight_rpa_upload_capability" in reason for reason in result.reasons)
def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
"""Worker 声明 freight_upload 且目录/凭据齐全时应 ready。"""
"""Worker 声明 freight_rpa_upload 且目录/凭据齐全时应 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_RPA_UPLOAD_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()