Files
syops/backend/tests/test_freight_receipt_rpa_callback.py
T
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

416 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""收料 RPA callback 的归档和幂等契约测试。"""
from __future__ import annotations
import hashlib
import pytest
def _register_inbound_report_handler():
"""注册生产用 inbound 事实处理函数(调拨侧 handle_inbound_report)。
核心逻辑:归档入口终态 commit 后经 dispatch_report_fact 投递;测试在调用
ingest_inbound_callback 前显式注册,避免依赖 create_app 全局状态顺序。
"""
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
register_report_handler('inbound', handle_inbound_report)
return handle_inbound_report
def test_receipt_unit_processing_and_batch_progress(app):
"""开始导出标记 processing;每笔完成后 batch-progress 抬升排程计数。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import (
mark_inbound_unit_processing,
report_inbound_batch_progress,
)
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(
schedule_no='SCH-RECEIPT-LIVE', name='Receipt live progress', schedule_type='platform_job',
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUN-RECEIPT-LIVE', schedule_task_id=task.id, status='running',
total_count=2, success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_inbound_rpa': True},
)
db.session.add(run)
db.session.flush()
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id, source_id=source.id, source_code=source.source_code,
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-live-progress',
status='awaiting_rpa', config_snapshot_json={},
)
db.session.add(unit)
db.session.commit()
marked = mark_inbound_unit_processing({
'schema_version': 'freight_rpa.inbound.v1',
'callback_id': unit.callback_id,
'status': 'processing',
})
assert marked['updated'] is True
db.session.expire_all()
assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'processing'
progressed = report_inbound_batch_progress({
'schema_version': 'freight_rpa.inbound.v1',
'schedule_run_id': run.id,
'batch_run_no': run.run_no,
'success_count': 1,
'skipped_count': 0,
'failed_count': 0,
})
assert progressed['updated'] is True
db.session.expire_all()
refreshed = db.session.get(ScheduleRun, run.id)
assert int(refreshed.success_count or 0) == 1
assert refreshed.response_summary_json['progress']['success_count'] == 1
def test_inbound_batch_ready_sink_finalizes_schedule_even_if_fact_handler_raises(
app, monkeypatch,
):
"""文件归档单元终态后,事实/证据处理失败仍须收口排程(文件返回= RPA 结束)。
[断言意图] batch-ready sink 在 finally 中 finalize;不得依赖 handle_inbound_report 成功。
"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.rpa_sinks import _inbound_batch_ready_sink
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(
schedule_no='SCH-INBOUND-FILE-FINAL',
name='Inbound file finalize',
schedule_type='platform_job',
platform_api_path='freight-rpa-inbound',
owner_user_id=1,
cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUN-INBOUND-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_inbound_rpa': True},
)
db.session.add(run)
db.session.flush()
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id,
source_id=source.id,
source_code=source.source_code,
connector_type='dbs',
warehouse_id='AWSDU',
callback_id='inbound-file-final-cb',
status='awaiting_rpa',
config_snapshot_json={},
)
db.session.add(unit)
db.session.commit()
monkeypatch.setattr(
'app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file',
lambda _path: b'receipt-bytes',
)
monkeypatch.setattr(
'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes',
lambda **_kwargs: None,
)
def _boom(_fact):
raise RuntimeError('evidence sync exploded')
register_report_handler('inbound', _boom)
payload = {
'schema_version': 'freight_rpa.inbound.v1',
'callback_id': unit.callback_id,
'status': 'success',
'file_path': 'Z:/receipt.xlsx',
'original_filename': 'receipt.xlsx',
'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(),
}
with pytest.raises(RuntimeError, match='evidence sync exploded'):
_inbound_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_inbound_rpa') is False
assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'success'
def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
"""success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(
schedule_no='SCH-RECEIPT-PROG', name='Receipt progress', schedule_type='platform_job',
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUN-RECEIPT-PROG', schedule_task_id=task.id, status='running',
total_count=1, success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_inbound_rpa': True},
)
db.session.add(run)
db.session.flush()
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id, source_id=source.id, source_code=source.source_code,
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-progress',
status='awaiting_rpa', config_snapshot_json={},
)
db.session.add(unit)
db.session.commit()
monkeypatch.setattr(
'app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file',
lambda _path: b'receipt-bytes',
)
monkeypatch.setattr(
'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes',
lambda **_kwargs: None,
)
_register_inbound_report_handler()
payload = {
'schema_version': 'freight_rpa.inbound.v1',
'callback_id': unit.callback_id,
'status': 'success',
'file_path': 'Z:/receipt.xlsx',
'original_filename': 'receipt.xlsx',
'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(),
}
ingest_inbound_callback(payload)
db.session.expire_all()
refreshed = db.session.get(ScheduleRun, run.id)
# [断言意图] success 后进度至少抬升 success_count;终态可能已 finalize 清 awaiting。
assert int(refreshed.success_count or 0) >= 1
def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch):
"""同一 callback 重放只归档一条收料文件,绝不创建库存快照。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-CB', schedule_task_id=task.id, status='running')
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={})
db.session.add(unit); db.session.commit()
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
_register_inbound_report_handler()
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
first = ingest_inbound_callback(payload)
second = ingest_inbound_callback(payload)
assert first['file_id'] == second['file_id']
assert FreightRpaOnhandReportFile.query.count() == 0
def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
"""收料回调 success 落归档后,必须推进调拨 waiting 来源任务(B3 接线)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-CB2', schedule_task_id=task.id, status='running')
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge', status='awaiting_rpa', config_snapshot_json={})
db.session.add(unit)
transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E', business_date='2026-09-17', status='preparing_files', trigger_type='manual')
db.session.add(transfer_run); db.session.flush()
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
db.session.add(job); db.session.commit()
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
_register_inbound_report_handler()
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
result = ingest_inbound_callback(payload)
# [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id
db.session.expire_all()
advanced = db.session.get(TransferSourceJob, job.id)
assert advanced.status == "file_ready"
assert advanced.file_no == str(result["file_id"])
def test_ingest_failed_advance_is_durable(app):
"""failed 回调推进调拨任务后必须已 commit——rollback 不得丢弃该推进(B3 持久性)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
db.session.add(task); db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-CB3', schedule_task_id=task.id, status='running')
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={})
db.session.add(unit)
transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E-FAIL', business_date='2026-09-17', status='preparing_files', trigger_type='manual')
db.session.add(transfer_run); db.session.flush()
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
db.session.add(job); db.session.commit()
_register_inbound_report_handler()
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
result = ingest_inbound_callback(payload)
assert result['status'] == 'failed'
# [断言意图] 推进必须已落库而非仅 flush:rollback 丢弃会话内未提交变更,
# 只有真正 commit 过的推进才能在 expire_all 后被新查询读到。
db.session.rollback()
db.session.expire_all()
advanced = db.session.get(TransferSourceJob, job.id)
assert advanced.status == 'failed'
assert advanced.error_code == 'RPA_TEST_FAIL'
def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
"""Callback cannot read arbitrary local xlsx files outside the receipt-only drop root."""
from app.core.errors import ValidationError
from app.services.freight_rpa.inbound.report_archive import _read_inbound_callback_file
with app.app_context():
allowed_root = tmp_path / 'receipt-drop'
allowed_root.mkdir()
app.config['FREIGHT_RPA_SHARED_INBOUND_DROP_DIR'] = str(allowed_root)
outside = tmp_path / 'outside.xlsx'
outside.write_bytes(b'not-a-real-xlsx')
with pytest.raises(ValidationError, match='inbound callback file'):
_read_inbound_callback_file(str(outside))
def test_ingest_empty_persists_no_inbound_data(app):
"""
empty 回调须落库 no_inbound_data(对齐库存 no_inventory_data)。
[断言意图] 单元 status=empty 且 error_code/error_message 为 no_inbound_data,供管理端展示跳过原因。
"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
task = ScheduleTask(
schedule_no='SCH-RECEIPT-EMPTY',
name='Receipt empty',
schedule_type='platform_job',
platform_api_path='freight-rpa-inbound',
owner_user_id=1,
cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-EMPTY', schedule_task_id=task.id, status='running')
db.session.add(run)
db.session.flush()
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id,
source_id=source.id,
source_code=source.source_code,
connector_type='dbs',
warehouse_id='AWSDU',
callback_id='receipt-callback-empty',
status='awaiting_rpa',
config_snapshot_json={},
)
db.session.add(unit)
db.session.commit()
_register_inbound_report_handler()
result = ingest_inbound_callback({
'schema_version': 'freight_rpa.inbound.v1',
'callback_id': unit.callback_id,
'status': 'empty',
'error_code': 'no_inbound_data',
'error_message': 'no_inbound_data',
})
assert result['status'] == 'empty'
db.session.expire_all()
saved = db.session.get(FreightRpaInboundUnitRun, unit.id)
assert saved is not None
assert saved.status == 'empty'
assert saved.error_code == 'no_inbound_data'
assert saved.error_message == 'no_inbound_data'
def test_receipt_progress_routes_are_registered(app):
"""回归锁:inbound-unit-progress / inbound-batch-progress 必须注册在 freight-rpa 蓝图上。
2026-10-08 事故:重构分叉合并丢失两路由,Worker 上报全程 404、活动锚失效、
在飞批次被超时对账误杀——本用例保证路由缺失在任何部署前即红。
(批次 R:路由自旧 shipping-notice rpa 回调前缀迁至 /api/freight-rpa/inbound-*,
处理函数不变,本回归锁同步改指新 URL。)
"""
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = 'test-tool-key'
client = app.test_client()
headers = {'X-Integration-Key': 'test-tool-key'}
for path, payload in (
('/api/freight-rpa/inbound-unit-progress',
{'schema_version': 'freight_rpa.inbound.v1', 'callback_id': 'no-such-callback'}),
('/api/freight-rpa/inbound-batch-progress',
{'schema_version': 'freight_rpa.inbound.v1', 'schedule_run_id': 999999999}),
):
# [断言意图] 路由必须存在且鉴权通过(非 401/403/404);无匹配数据时服务层
# 返回 200 + updated=False(注册性探针,不依赖任何夹具数据)。
resp = client.post(path, json=payload, headers=headers)
assert resp.status_code == 200, (path, resp.status_code, resp.get_json())
assert resp.get_json()['data']['updated'] is False
def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path):
"""跨机路径契约:Worker 只上报文件名(或历史 Windows 绝对路径),后端按自身 drop 根定位。"""
from app.core.errors import ValidationError
from app.services.freight_rpa.inbound.report_archive import _read_inbound_callback_file
with app.app_context():
drop_root = tmp_path / 'receipt-drop'
drop_root.mkdir()
app.config['FREIGHT_RPA_SHARED_INBOUND_DROP_DIR'] = str(drop_root)
target = drop_root / 'receipt_RUN_X_SITE_NA_2026.xlsx'
target.write_bytes(b'receipt-bytes')
# [断言意图] 裸文件名(新 Worker 契约)与 Windows 本机绝对路径(历史载荷)都
# 必须解析到后端 drop 根内同一文件;根外文件依旧拒绝(任意本机文件读取护栏不变)。
assert _read_inbound_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes'
assert _read_inbound_callback_file(
r'C:\HxopsRpaTest\data\freight_rpa\receipt\drop\receipt_RUN_X_SITE_NA_2026.xlsx'
) == b'receipt-bytes'
outside = tmp_path / 'outside.xlsx'
outside.write_bytes(b'x')
with pytest.raises(ValidationError, match='inbound callback file'):
_read_inbound_callback_file(str(outside))