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:
1 parent
ffc0d4a430
commit
39fe3c05f2
453 files changed
+17945
-8646
No files matched your search
+26
-26
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
tests/services/shipping_notice/test_inventory_candidate_projection.py
|
||||
tests/services/shipping_notice/test_onhand_candidate_projection.py
|
||||
|
||||
用途:验证正式 Task 的 active CandidateSet 读取、缺失阻断与版本化候选事实投影。
|
||||
依赖:Flask app fixture、ShippingNotice / CandidateSet / CandidateLine ORM、候选 projector。
|
||||
@@ -10,19 +10,19 @@ from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingOnhandCandidateLine,
|
||||
ShippingOnhandCandidateSet,
|
||||
ShippingOnhandCandidateSource,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingInventoryFile,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
FreightRpaOnhandReportFile,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||
project_inventory_candidate_facts,
|
||||
)
|
||||
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
|
||||
from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines
|
||||
|
||||
|
||||
def _task(task_no: str) -> ShippingOrderTask:
|
||||
@@ -36,8 +36,8 @@ def _task(task_no: str) -> ShippingOrderTask:
|
||||
return task
|
||||
|
||||
|
||||
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet:
|
||||
row = ShippingInventoryCandidateSet(
|
||||
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingOnhandCandidateSet:
|
||||
row = ShippingOnhandCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=version,
|
||||
lifecycle_status='frozen',
|
||||
@@ -50,12 +50,12 @@ def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInvento
|
||||
return row
|
||||
|
||||
|
||||
def test_prepare_candidate_inventory_lines_blocks_without_active_set(app):
|
||||
def test_prepare_candidate_onhand_lines_blocks_without_active_set(app):
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-001')
|
||||
db.session.commit()
|
||||
|
||||
result = prepare_candidate_inventory_lines(task)
|
||||
result = prepare_candidate_onhand_lines(task)
|
||||
|
||||
assert result['status'] == 'blocked'
|
||||
assert result['error_code'] == 'inventory_candidates_missing'
|
||||
@@ -66,13 +66,13 @@ def test_project_inventory_candidate_facts_reads_current_structured_set(app):
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-002')
|
||||
candidate_set = _candidate_set(task, version=2)
|
||||
source = ShippingInventoryCandidateSource(
|
||||
source = ShippingOnhandCandidateSource(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
source_code='DBS_DUB',
|
||||
candidate_order=1,
|
||||
candidate_origin='rule',
|
||||
)
|
||||
line = ShippingInventoryCandidateLine(
|
||||
line = ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
line_no=1,
|
||||
source_line_no='00010',
|
||||
@@ -99,14 +99,14 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-003')
|
||||
old_set = _candidate_set(task, version=1)
|
||||
old_line = ShippingInventoryCandidateLine(
|
||||
old_line = ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(old_set.id),
|
||||
line_no=1,
|
||||
source_codes_json=['DBS_OLD'],
|
||||
)
|
||||
db.session.add(old_line)
|
||||
db.session.flush()
|
||||
new_set = ShippingInventoryCandidateSet(
|
||||
new_set = ShippingOnhandCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=2,
|
||||
lifecycle_status='frozen',
|
||||
@@ -116,7 +116,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
db.session.flush()
|
||||
task.active_inventory_candidate_set_id = int(new_set.id)
|
||||
db.session.flush()
|
||||
new_line = ShippingInventoryCandidateLine(
|
||||
new_line = ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(new_set.id),
|
||||
line_no=1,
|
||||
source_codes_json=['DBS_NEW'],
|
||||
@@ -132,7 +132,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=int(task.id),
|
||||
snapshot_line_id=int(snapshot_line.id),
|
||||
line_no=1,
|
||||
@@ -141,8 +141,8 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
candidate_set_version=1,
|
||||
candidate_line_id=int(old_line.id),
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
inventory_source_code='DBS_OLD',
|
||||
onhand_status='ready',
|
||||
source_code='DBS_OLD',
|
||||
is_current=True,
|
||||
allowed_source_codes_snapshot=['DBS_OLD'],
|
||||
detail_json={'disposition': 'ok'},
|
||||
@@ -161,12 +161,12 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
|
||||
with app.app_context():
|
||||
task = _task('SN-CAND-EVIDENCE')
|
||||
candidate_set = _candidate_set(task)
|
||||
db.session.add(ShippingInventoryCandidateLine(
|
||||
db.session.add(ShippingOnhandCandidateLine(
|
||||
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
|
||||
))
|
||||
db.session.flush()
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
|
||||
source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64,
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
@@ -180,11 +180,11 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
|
||||
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1,
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched',
|
||||
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no,
|
||||
candidate_set_version=1, onhand_snapshot_id=int(inventory_file.id), match_result='matched',
|
||||
onhand_status='ready', source_code='DBS_DUB', matched_file_no=inventory_file.onhand_file_no,
|
||||
matched_row_index=9, is_current=True, detail_json={},
|
||||
))
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,791 @@
|
||||
"""tests/services/shipping_notice/test_onhand_report_handler.py
|
||||
|
||||
用途:阶段 B Task 7 修复轮——onhand 报表事实投递接线与处理函数契约测试:
|
||||
单回调/批量 worker 在文件行 commit 后投递事实(先 commit 再投递、处理函数
|
||||
失败外抛且文件行保留)、success 事实 settle 等待中的候选准备并同步门禁
|
||||
(处理函数自行 commit、重放不重复候选行)、失败事实不发明候选行;
|
||||
修复轮 2 补批量契约:单文件处理函数失败不跳过其余文件投递与排程收口、
|
||||
Job 意外异常 requeue 可重试;修复轮 3 补:失败点回滚半途写(不被后续
|
||||
commit 持久化)、drop 文件清理先于错误外抛、Job 重试「只重投失败文件」
|
||||
通道(callback_id 已消费拦不住重投、未完成绝不返回 ok)。
|
||||
依赖:app(SQLite)fixture、freight_rpa.reports.dispatch / facts、
|
||||
freight_rpa.onhand.report_store(候选 settle 所绑文件行的唯一插入入口)、
|
||||
onhand_rpa_workflow(回调入口 + 重试通道/专用异常)、onhand_recovery_service
|
||||
(候选准备表)、jobs.handlers.freight_rpa_onhand_callback_process(Job 收口)。
|
||||
逻辑:直接处理函数用例以 monkeypatch 替身 gate 同步记录调用(不断言 Gate 全链);
|
||||
e2e 投递用例复用 test_shipping_notice_inventory_rpa_workflow 的动态订单/
|
||||
客户确认/库存源种子 harness,跑通 rpa_report_inventory /
|
||||
process_rpa_report_inventory_batch 全程后在注册表注入记录器断言事实字段;
|
||||
批量失败用例以替身 finalize 记录收口调用(内部预存在 NameError 与本契约无关)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import inventory_xlsx_with_warehouse
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(app):
|
||||
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
|
||||
from app import db
|
||||
|
||||
return db.session
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fake_gate_sync(monkeypatch):
|
||||
"""替身门禁同步:记录 (execution_id) 调用序列,不跑 Gate 全链(聚焦候选/提交契约)。"""
|
||||
calls: list[int] = []
|
||||
|
||||
def _record(**kwargs):
|
||||
calls.append(int(kwargs['execution'].id))
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
_record,
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _seed_waiting_preparation(db_session, *, task_no: str, execution_no: str):
|
||||
"""构造「任务 + 活动执行 + 等待中候选准备轮次(waiting SourceAttempt)」。
|
||||
|
||||
Returns:
|
||||
(task, execution, preparation, source_row) 四元组。
|
||||
"""
|
||||
from app.models import (
|
||||
ShippingOnhandPreparationAttempt,
|
||||
ShippingOnhandPreparationSourceAttempt,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
)
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no, user_id=1, source_type='direct_pdf', status='ready',
|
||||
)
|
||||
db_session.add(task)
|
||||
db_session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no=execution_no, task_id=task.id, status='active',
|
||||
)
|
||||
db_session.add(execution)
|
||||
db_session.flush()
|
||||
task.active_process_execution_id = execution.id
|
||||
preparation = ShippingOnhandPreparationAttempt(
|
||||
task_id=task.id, attempt_no=1, status='waiting_external',
|
||||
)
|
||||
db_session.add(preparation)
|
||||
db_session.flush()
|
||||
source_row = ShippingOnhandPreparationSourceAttempt(
|
||||
preparation_attempt_id=preparation.id, source_code='DSV360_AWSDU', status='waiting',
|
||||
)
|
||||
db_session.add(source_row)
|
||||
db_session.commit()
|
||||
return task, execution, preparation, source_row
|
||||
|
||||
|
||||
def _onhand_file_id(*, source_code: str = 'DSV360_AWSDU') -> int:
|
||||
"""经唯一插入入口 report_store 落一行 ready onhand 报表文件并 commit,返回 file_id。"""
|
||||
from app import db
|
||||
from app.services.freight_rpa.onhand.report_store import insert_onhand_report
|
||||
from app.services.shipping_notice.onhand_file_store import generate_inventory_file_no
|
||||
|
||||
file_id = insert_onhand_report(
|
||||
onhand_file_no=generate_inventory_file_no(),
|
||||
storage_path='handler://onhand-report-fact.xlsx',
|
||||
source_code=source_code,
|
||||
snapshot_status='ready',
|
||||
file_sha256='a' * 64,
|
||||
)
|
||||
db.session.commit()
|
||||
return file_id
|
||||
|
||||
|
||||
def test_onhand_fact_settles_waiting_candidates_and_syncs_gates(app, db_session, _fake_gate_sync):
|
||||
"""success 事实:settle 等待候选(ready + 绑文件)→ 聚合准备轮次 → 门禁同步 → 自行 commit。"""
|
||||
from app.models import ShippingOnhandPreparationAttempt, ShippingOnhandPreparationSourceAttempt
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
|
||||
|
||||
task, execution, preparation, source_row = _seed_waiting_preparation(
|
||||
db_session, task_no='OT-ONHAND-FACT-SETTLE', execution_no='EX-ONHAND-FACT-SETTLE',
|
||||
)
|
||||
file_id = _onhand_file_id()
|
||||
|
||||
handle_onhand_report(ReportFact(
|
||||
report_kind='onhand', source_code='DSV360_AWSDU',
|
||||
file_id=file_id, sha256='a' * 64, ok=True,
|
||||
))
|
||||
|
||||
# [断言意图] 处理函数必须自行 commit:rollback + expire_all 后 settle 仍可见。
|
||||
db_session.rollback()
|
||||
db_session.expire_all()
|
||||
refreshed_source = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
|
||||
assert refreshed_source.status == 'ready'
|
||||
assert refreshed_source.onhand_file_id == file_id
|
||||
refreshed_prep = db_session.get(ShippingOnhandPreparationAttempt, preparation.id)
|
||||
assert refreshed_prep.status == 'succeeded'
|
||||
assert refreshed_prep.completed_at is not None
|
||||
# [断言意图] 门禁同步覆盖 settle 受影响的准备轮次任务(execution 绑定同任务)。
|
||||
assert _fake_gate_sync == [execution.id]
|
||||
|
||||
# [重放] 同一事实重复投递:等待集已空——不重复 settle、不重复候选行(幂等)。
|
||||
handle_onhand_report(ReportFact(
|
||||
report_kind='onhand', source_code='DSV360_AWSDU',
|
||||
file_id=file_id, sha256='a' * 64, ok=True,
|
||||
))
|
||||
db_session.rollback()
|
||||
db_session.expire_all()
|
||||
assert ShippingOnhandPreparationSourceAttempt.query.count() == 1
|
||||
assert db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id).onhand_file_id == file_id
|
||||
assert db_session.get(ShippingOnhandPreparationAttempt, preparation.id).status == 'succeeded'
|
||||
|
||||
|
||||
def test_onhand_failure_fact_invents_no_candidate_rows(app, db_session, _fake_gate_sync):
|
||||
"""失败/空事实:无文件可挂——不发明候选行(SourceAttempt 保持 waiting、不绑文件),仅重投影门禁。"""
|
||||
from app.models import ShippingOnhandPreparationSourceAttempt
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
|
||||
|
||||
task, execution, preparation, source_row = _seed_waiting_preparation(
|
||||
db_session, task_no='OT-ONHAND-FACT-FAIL', execution_no='EX-ONHAND-FACT-FAIL',
|
||||
)
|
||||
|
||||
handle_onhand_report(ReportFact(
|
||||
report_kind='onhand', source_code='DSV360_AWSDU',
|
||||
file_id=None, sha256=None, ok=False,
|
||||
error_code='rpa_export_failed', error_message='boom',
|
||||
))
|
||||
|
||||
db_session.rollback()
|
||||
db_session.expire_all()
|
||||
# [断言意图] 失败事实没有文件身份:不得发明/改写候选行——仍是唯一一行、
|
||||
# 状态保持 waiting、未绑定任何文件;门禁重投影(失败路径门禁更新归处理函数)。
|
||||
assert ShippingOnhandPreparationSourceAttempt.query.count() == 1
|
||||
refreshed = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
|
||||
assert refreshed.status == 'waiting'
|
||||
assert refreshed.onhand_file_id is None
|
||||
assert _fake_gate_sync == [execution.id]
|
||||
|
||||
|
||||
def _seed_direct_rpa_task(db, *, task_no: str, run_no: str, sample) -> None:
|
||||
"""复用动态订单 harness:直建 OT + 动态订单 + 客户确认 + 库存源种子 + RPA 触发种子。"""
|
||||
from app.models import ShippingOrderTask
|
||||
from tests.conftest import seed_rpa_inventory_trigger, seed_task_inventory_source
|
||||
from tests.test_shipping_notice_inventory_rpa_workflow import (
|
||||
_attach_dynamic_order,
|
||||
_confirm_direct_rpa_task_customer,
|
||||
)
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no, user_id=1, source_type='direct_pdf', status='ready',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
|
||||
seed_rpa_inventory_trigger(task, run_no=run_no)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _stub_structure_validation(monkeypatch):
|
||||
"""替身结构校验:onhand_structure_drift 仍读已删站点列(Task 2 已记录的 deferred
|
||||
minor,legacy 套件待 s18 改写)——与本修复无关;本测试聚焦 commit 后投递接线。
|
||||
|
||||
返回与真实 validate_production_inventory_structure 同形状的确定性解析参数:
|
||||
field_mapping 用 conftest 种子字段 ID 对齐样例 xlsx 列头
|
||||
(Warehouse ID / SKU / Reservation ID / Qty,表头行 1,默认 sheet)。
|
||||
"""
|
||||
from app.models import FreightRpaOnhandField
|
||||
|
||||
fields = {
|
||||
row.field_code: row
|
||||
for row in FreightRpaOnhandField.query.filter(
|
||||
FreightRpaOnhandField.field_code.in_(
|
||||
['part_number', 'reservation_id', 'available_qty', 'warehouse_id'],
|
||||
)
|
||||
)
|
||||
}
|
||||
structure_check = {
|
||||
'field_mapping': {
|
||||
str(fields['part_number'].id): 'SKU',
|
||||
str(fields['reservation_id'].id): 'Reservation ID',
|
||||
str(fields['available_qty'].id): 'Qty',
|
||||
str(fields['warehouse_id'].id): 'Warehouse ID',
|
||||
},
|
||||
'header_row_index': 1,
|
||||
'sheet_name': 'Sheet',
|
||||
'level': 'exact',
|
||||
'difference': {},
|
||||
'warnings': [],
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.onhand_structure_drift.validate_production_inventory_structure',
|
||||
lambda **_kwargs: structure_check,
|
||||
)
|
||||
|
||||
|
||||
def test_single_callback_dispatches_onhand_fact_after_file_commit(app, tmp_path, monkeypatch):
|
||||
"""rpa_report_inventory:文件行 commit 后同请求投递 onhand 事实,字段与已提交行对齐。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory
|
||||
from tests.conftest import rpa_callback_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'onhand-fact.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
register_report_handler('onhand', seen.append)
|
||||
|
||||
with app.app_context():
|
||||
from app.models import ShippingOrderTask
|
||||
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-DISPATCH', run_no='RUN-ONHAND-FACT', sample=sample)
|
||||
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-DISPATCH').one()
|
||||
result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT'))
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='RUN-ONHAND-FACT', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
assert result.get('status') == 'ok'
|
||||
# [断言意图] commit 后投递:恰好一条事实、字段与已提交文件行逐项对齐。
|
||||
assert len(seen) == 1
|
||||
fact = seen[0]
|
||||
assert fact.report_kind == 'onhand'
|
||||
assert fact.ok is True
|
||||
assert fact.file_id == snap.id
|
||||
assert fact.source_code == 'DSV360_AWSDU'
|
||||
assert fact.sha256 == snap.file_sha256
|
||||
# 文件行已提交:rollback 后重查仍在(先 commit 再投递的顺序契约)。
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
|
||||
|
||||
|
||||
def test_single_callback_handler_failure_propagates_and_keeps_file_row(app, tmp_path, monkeypatch):
|
||||
"""处理函数抛错:异常原样外抛(不折进 post_commit_warnings),已提交文件行保留。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingOrderTask
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory
|
||||
from tests.conftest import rpa_callback_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'onhand-fact-fail.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
def boom(_fact) -> None:
|
||||
raise RuntimeError('onhand handler down')
|
||||
|
||||
register_report_handler('onhand', boom)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-RAISE', run_no='RUN-ONHAND-FACT-RAISE', sample=sample)
|
||||
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-RAISE').one()
|
||||
|
||||
# [断言意图] 异常必须外抛(供 Worker 重试整笔回调),绝不折进 warnings 后返回 ok。
|
||||
with pytest.raises(RuntimeError, match='onhand handler down'):
|
||||
rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT-RAISE'))
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='RUN-ONHAND-FACT-RAISE', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
# [断言意图] 处理函数失败不回滚已提交文件行。
|
||||
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
|
||||
|
||||
|
||||
def test_batch_worker_dispatches_onhand_fact_after_commit(app, tmp_path, monkeypatch):
|
||||
"""process_rpa_report_inventory_batch:整批事务 commit 后逐文件投递 onhand 事实。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'onhand-fact-batch.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
register_report_handler('onhand', seen.append)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-BATCH', run_no='RUN-ONHAND-FACT-BATCH', sample=sample)
|
||||
task_no = 'OT-ONHAND-FACT-BATCH'
|
||||
|
||||
result = process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-FACT-BATCH',
|
||||
'trigger_type': 'on_demand',
|
||||
'results': [scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample), task_no=task_no,
|
||||
)],
|
||||
}))
|
||||
assert result.get('status') == 'ok'
|
||||
assert result.get('data', {}).get('success_count') == 1
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='RUN-ONHAND-FACT-BATCH', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
# [断言意图] 整批 commit 后逐文件投递:恰一条 ok=True 事实,file_id 对齐已提交行。
|
||||
assert [fact.file_id for fact in seen] == [snap.id]
|
||||
assert all(fact.report_kind == 'onhand' and fact.ok is True for fact in seen)
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
|
||||
|
||||
|
||||
def test_batch_handler_failure_does_not_skip_remaining_dispatch_or_finalize(app, tmp_path, monkeypatch):
|
||||
"""批量内单文件处理函数失败:其余已提交文件仍投递、排程收口仍执行、错误仍外抛、文件行保留。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample_a = drop_dir / 'onhand-fact-batch-a.xlsx'
|
||||
sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
sample_b = drop_dir / 'onhand-fact-batch-b.xlsx'
|
||||
sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
# [断言意图·观测点] 排程收口必须仍被调用(内部预存在 NameError 与本契约无关)。
|
||||
finalize_calls: list = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_rpa_onhand_finalize.finalize_shipping_inventory_schedule_run',
|
||||
lambda schedule_run_id, **_kwargs: (
|
||||
finalize_calls.append(schedule_run_id)
|
||||
or {'ok': True, 'schedule_finalize_status': 'finalized'}
|
||||
),
|
||||
)
|
||||
# [断言意图·观测点] 首个文件处理函数失败,第二个必须照常收到事实。
|
||||
seen: list[ReportFact] = []
|
||||
calls = {'n': 0}
|
||||
|
||||
def flaky(fact: ReportFact) -> None:
|
||||
calls['n'] += 1
|
||||
seen.append(fact)
|
||||
if calls['n'] == 1:
|
||||
raise RuntimeError('onhand handler down mid-batch')
|
||||
|
||||
register_report_handler('onhand', flaky)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-ONHAND-BATCH-FAIL', name='Onhand batch fail', schedule_type='platform_job',
|
||||
platform_api_path='freight-rpa-onhand', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ONHAND-BATCH-FAIL', schedule_task_id=task.id, status='running',
|
||||
total_count=2, success_count=0, failed_count=0, skipped_count=0,
|
||||
response_summary_json={'awaiting_rpa': True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
# [断言意图] 处理函数异常必须外抛(调用方/Job 见到失败)——但不得因此跳过
|
||||
# 其余文件投递与排程收口(断言在 pytest.raises 之后进行)。
|
||||
with pytest.raises(RuntimeError, match='onhand handler down mid-batch'):
|
||||
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-BATCH-FAIL',
|
||||
'schedule_run_id': run.id,
|
||||
'trigger_type': 'scheduled',
|
||||
'results': [
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-BATCH-FAIL-A',
|
||||
),
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-BATCH-FAIL-B',
|
||||
),
|
||||
],
|
||||
}))
|
||||
|
||||
snaps = FreightRpaOnhandReportFile.query.filter(
|
||||
FreightRpaOnhandReportFile.snapshot_status == 'ready',
|
||||
FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B')),
|
||||
).order_by(FreightRpaOnhandReportFile.id).all()
|
||||
# [断言意图] 两个文件行都已落库并保留(commit 先于投递,失败不回滚)。
|
||||
assert [snap.rpa_run_no for snap in snaps] == ['SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B']
|
||||
# [断言意图] 两个文件的事实都投递了(首文件失败不跳过次文件投递)。
|
||||
assert [fact.file_id for fact in seen] == [snap.id for snap in snaps]
|
||||
# [断言意图] 排程收口仍执行(不被处理函数失败跳过)。
|
||||
assert finalize_calls == [run.id]
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
assert {db.session.get(FreightRpaOnhandReportFile, snap.id) is not None for snap in snaps} == {True}
|
||||
|
||||
|
||||
def test_callback_process_job_requeues_on_unexpected_exception(app, monkeypatch):
|
||||
"""Job 意外异常(含批量 commit 后处理函数失败重抛)必须可重试 requeue,而非终态 failed。"""
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import freight_rpa_onhand_callback_process as handler
|
||||
from app.models import Job
|
||||
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type='freight_rpa_onhand_callback_process',
|
||||
status='running',
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
business_ref='inventory-callback:retryable-check',
|
||||
payload_json={'callback_id': 'retryable-check'},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
def _boom(_payload):
|
||||
raise RuntimeError('dispatch re-raise after commit')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch',
|
||||
_boom,
|
||||
)
|
||||
|
||||
handler.run_shipping_inventory_callback_process(
|
||||
JobContext(config={}, logger=None, extras={}), {'job_id': job.id},
|
||||
)
|
||||
db_session = db.session
|
||||
db_session.expire_all()
|
||||
# [断言意图] retryable=True → requeue(attempts 未耗尽时回到 queued 等待重试),
|
||||
# 绝不落终态 failed——批量文件行已提交,重放按幂等契约补齐收口。
|
||||
refreshed = db_session.get(Job, job.id)
|
||||
assert refreshed.status == 'queued'
|
||||
|
||||
|
||||
def test_batch_handler_failure_rolls_back_partial_writes_and_next_file_dispatches(app, db_session, tmp_path, monkeypatch):
|
||||
"""批量内处理函数「先 bind 候选再抛错」:半途 flush 写必须回滚(不得被后续 commit 持久化),次文件照常投递。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingOnhandPreparationSourceAttempt
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample_a = drop_dir / 'rollback-a.xlsx'
|
||||
sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
sample_b = drop_dir / 'rollback-b.xlsx'
|
||||
sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
calls = {'n': 0}
|
||||
|
||||
def bind_then_raise_or_settle(fact: ReportFact) -> None:
|
||||
calls['n'] += 1
|
||||
seen.append(fact)
|
||||
if calls['n'] == 1:
|
||||
# [RED 场景] 模拟「先 bind 候选再抛错」的处理函数:半途 flush(不 commit)。
|
||||
from app.models import ShippingOnhandPreparationSourceAttempt as _Row
|
||||
|
||||
row = (
|
||||
_Row.query.filter_by(source_code='DSV360_AWSDU')
|
||||
.order_by(_Row.id)
|
||||
.first()
|
||||
)
|
||||
row.status = 'ready'
|
||||
row.onhand_file_id = int(fact.file_id)
|
||||
db.session.flush()
|
||||
raise RuntimeError('bind then raise mid-batch')
|
||||
# 次文件走真实处理函数:内部 settle(等待集)→ 门禁同步 → 自行 commit。
|
||||
handle_onhand_report(fact)
|
||||
|
||||
register_report_handler('onhand', bind_then_raise_or_settle)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_task, _execution, _preparation, source_row = _seed_waiting_preparation(
|
||||
db_session, task_no='OT-ONHAND-ROLLBACK', execution_no='EX-ONHAND-ROLLBACK',
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match='bind then raise mid-batch'):
|
||||
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-ROLLBACK',
|
||||
'trigger_type': 'on_demand',
|
||||
'results': [
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-ROLLBACK-A',
|
||||
),
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-ROLLBACK-B',
|
||||
),
|
||||
],
|
||||
}))
|
||||
|
||||
snaps = FreightRpaOnhandReportFile.query.filter(
|
||||
FreightRpaOnhandReportFile.snapshot_status == 'ready',
|
||||
FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-ROLLBACK-A', 'SR-ROLLBACK-B')),
|
||||
).order_by(FreightRpaOnhandReportFile.id).all()
|
||||
# [断言意图] 次文件照常投递:两个已提交文件的事实都送达处理函数。
|
||||
assert [fact.file_id for fact in seen] == [snap.id for snap in snaps]
|
||||
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
# [断言意图] 首文件半途 bind 已回滚——不得被次文件处理函数的 commit 持久化成
|
||||
# file-A 绑定;次文件真实 settle 落到 file B(等待集在回滚后原样可 settle)。
|
||||
refreshed = db.session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
|
||||
assert refreshed.status == 'ready'
|
||||
assert refreshed.onhand_file_id == snaps[1].id
|
||||
|
||||
|
||||
def test_batch_handler_failure_still_flushes_drop_file_cleanup_before_raise(app, tmp_path, monkeypatch):
|
||||
"""处理函数抛错:drop 文件清理(消费标记+移动/入队)必须先于错误外抛完成。"""
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'cleanup-before-raise.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
def boom(_fact) -> None:
|
||||
raise RuntimeError('onhand handler down cleanup')
|
||||
|
||||
register_report_handler('onhand', boom)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-CLEANUP', run_no='RUN-ONHAND-CLEANUP', sample=sample)
|
||||
|
||||
with pytest.raises(RuntimeError, match='onhand handler down cleanup'):
|
||||
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-CLEANUP',
|
||||
'trigger_type': 'on_demand',
|
||||
'results': [scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-CLEANUP',
|
||||
)],
|
||||
}))
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='RUN-ONHAND-CLEANUP', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
# [断言意图] 错误已外抛,但 drop 文件清理先行完成:消费标记/移动先于重抛,
|
||||
# 文件离开 drop 根、落入 processed 归档(移动失败时则入持久化 cleanup 队列)。
|
||||
assert not sample.exists()
|
||||
assert (drop_dir / 'processed' / sample.name).exists()
|
||||
|
||||
|
||||
def test_batch_retry_channel_redispatches_file_despite_consumed_callback_id(app, tmp_path, monkeypatch):
|
||||
"""重试通道:task-linked 项 Attempt 已消费 callback_id(整批重放必被跳过)时,失败文件仍重投事实。"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingOrderTask, FreightRpaOnhandTaskAttempt
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import (
|
||||
OnhandReportDispatchAfterCommitError,
|
||||
process_rpa_report_inventory_batch,
|
||||
)
|
||||
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
|
||||
|
||||
drop_dir = tmp_path / 'drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
|
||||
sample = drop_dir / 'retry-callback-id.xlsx'
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
|
||||
|
||||
seen: list[ReportFact] = []
|
||||
calls = {'n': 0}
|
||||
|
||||
def flaky(fact: ReportFact) -> None:
|
||||
calls['n'] += 1
|
||||
seen.append(fact)
|
||||
if calls['n'] == 1:
|
||||
raise RuntimeError('onhand handler down first pass')
|
||||
|
||||
register_report_handler('onhand', flaky)
|
||||
|
||||
with app.app_context():
|
||||
_stub_structure_validation(monkeypatch)
|
||||
_seed_direct_rpa_task(db, task_no='OT-ONHAND-RETRY', run_no='RUN-ONHAND-RETRY', sample=sample)
|
||||
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-RETRY').one()
|
||||
candidate_set_id = int(task.active_inventory_candidate_set_id or 1)
|
||||
# [RED 场景] 结构化 per-source Attempt(v2 身份字段与回调 item 对齐):
|
||||
# pass 1 的回调确认会把 attempt.callback_id 写入——整批重放随即被 replay 检查跳过。
|
||||
# source_run_no 用与批量 run_no 不同的 PSR 轮次号(与真实 Worker 形态一致:
|
||||
# run_no=批量轮次、source_run_no=逐源轮次——run_no 消费标记按 source_run_no
|
||||
# 匹配,不会误吞本 Attempt)。
|
||||
attempt = FreightRpaOnhandTaskAttempt(
|
||||
task_no='OT-ONHAND-RETRY',
|
||||
source_code='DSV360_AWSDU',
|
||||
attempt_no=1,
|
||||
source_run_no='PSR-ONHAND-RETRY-1',
|
||||
status='queued',
|
||||
triggered_at=datetime.utcnow(),
|
||||
lease_token='test-lease-token',
|
||||
execution_phase='trigger_written',
|
||||
extra_json={
|
||||
'trigger_mode': 'test',
|
||||
'candidate_set_id': candidate_set_id,
|
||||
'execution_id': 1,
|
||||
'gate_id': 1,
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.commit()
|
||||
|
||||
batch_payload = v2_inventory_batch_payload({
|
||||
'run_no': 'RUN-ONHAND-RETRY',
|
||||
'trigger_type': 'on_demand',
|
||||
'results': [dict(
|
||||
scheduled_rpa_batch_item(
|
||||
'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-RETRY',
|
||||
),
|
||||
callback_id='test-callback:RUN-ONHAND-RETRY',
|
||||
source_run_no='PSR-ONHAND-RETRY-1',
|
||||
attempt_no=1,
|
||||
lease_token='test-lease-token',
|
||||
candidate_set_id=candidate_set_id,
|
||||
execution_id=1,
|
||||
gate_id=1,
|
||||
)],
|
||||
})
|
||||
|
||||
# [STEP 1] 首轮:文件落地+回调确认(写 callback_id)+投递失败 → 专用异常携带清单外抛。
|
||||
with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo:
|
||||
process_rpa_report_inventory_batch(batch_payload)
|
||||
|
||||
snap = FreightRpaOnhandReportFile.query.filter_by(
|
||||
rpa_run_no='PSR-ONHAND-RETRY-1', snapshot_status='ready',
|
||||
).first()
|
||||
assert snap is not None
|
||||
assert excinfo.value.failed_files == [{
|
||||
'source_code': 'DSV360_AWSDU',
|
||||
'file_id': snap.id,
|
||||
'sha256': (snap.file_sha256 or None),
|
||||
}]
|
||||
# [断言意图·RED 场景] Attempt 已消费 callback_id——整批重放会被 replay 检查跳过。
|
||||
db.session.expire(attempt)
|
||||
assert str(attempt.callback_id or '').strip()
|
||||
armed_callback_id = str(attempt.callback_id)
|
||||
|
||||
# [STEP 2] 整批重放(不带重试清单):item 被 replay 检查跳过——不落地、不投递,
|
||||
# 证明整批重放无法补投(这正是「只重投失败文件」通道存在的原因)。
|
||||
replay_result = process_rpa_report_inventory_batch(dict(batch_payload))
|
||||
assert [fact.file_id for fact in seen] == [snap.id]
|
||||
assert replay_result.get('data', {}).get('created') == []
|
||||
assert armed_callback_id == str(
|
||||
FreightRpaOnhandTaskAttempt.query.filter_by(
|
||||
task_no='OT-ONHAND-RETRY', source_code='DSV360_AWSDU',
|
||||
).order_by(FreightRpaOnhandTaskAttempt.id.desc()).first().callback_id or '',
|
||||
)
|
||||
|
||||
# [STEP 3] 重试通道(Job 处理器写回的 retry_dispatch_files):只重投失败文件。
|
||||
retry_payload = {**batch_payload, 'retry_dispatch_files': excinfo.value.failed_files}
|
||||
result = process_rpa_report_inventory_batch(retry_payload)
|
||||
assert result.get('status') == 'ok'
|
||||
assert result.get('data', {}).get('result_status') == 'retried'
|
||||
# [断言意图] 同一 file_id 的事实再次送达处理函数(callback_id 已消费拦不住重投)。
|
||||
assert [fact.file_id for fact in seen] == [snap.id, snap.id]
|
||||
|
||||
|
||||
def test_batch_retry_channel_reraises_while_handler_still_failing(app, monkeypatch):
|
||||
"""重试通道:处理函数仍未成功时必须继续携带清单重抛,绝不在未完成时返回 ok。"""
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import (
|
||||
OnhandReportDispatchAfterCommitError,
|
||||
process_rpa_report_inventory_batch,
|
||||
)
|
||||
|
||||
def boom(_fact) -> None:
|
||||
raise RuntimeError('onhand handler still down')
|
||||
|
||||
register_report_handler('onhand', boom)
|
||||
|
||||
with app.app_context():
|
||||
file_id = _onhand_file_id()
|
||||
marker = {'source_code': 'DSV360_AWSDU', 'file_id': file_id, 'sha256': None}
|
||||
|
||||
# [断言意图] 处理函数持续失败:重试通道继续抛专用异常(携带同一未成功清单,
|
||||
# Job 据此继续 requeue 直至 attempts 耗尽落终态 failed)——绝不返回 ok。
|
||||
with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo:
|
||||
process_rpa_report_inventory_batch({'retry_dispatch_files': [marker]})
|
||||
assert excinfo.value.failed_files == [marker]
|
||||
|
||||
|
||||
def test_callback_process_job_records_failed_files_for_retry(app, monkeypatch):
|
||||
"""Job 收口:投递失败重抛的清单写回 payload(retry_dispatch_files)并 requeue 可重试。"""
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import freight_rpa_onhand_callback_process as handler
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import OnhandReportDispatchAfterCommitError
|
||||
|
||||
marker = {'source_code': 'DSV360_AWSDU', 'file_id': 4242, 'sha256': 'a' * 64}
|
||||
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain='shipping_notice',
|
||||
job_type='freight_rpa_onhand_callback_process',
|
||||
status='running',
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
business_ref='inventory-callback:dispatch-retry-check',
|
||||
payload_json={'callback_id': 'dispatch-retry-check'},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
|
||||
def _raise_dispatch_error(_payload):
|
||||
raise OnhandReportDispatchAfterCommitError(
|
||||
'onhand handler down after commit', failed_files=[dict(marker)],
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch',
|
||||
_raise_dispatch_error,
|
||||
)
|
||||
|
||||
handler.run_shipping_inventory_callback_process(
|
||||
JobContext(config={}, logger=None, extras={}), {'job_id': job.id},
|
||||
)
|
||||
db.session.expire_all()
|
||||
# [断言意图] 清单写回 payload(重试只重投这些文件)+ requeue 可重试。
|
||||
refreshed = db.session.get(Job, job.id)
|
||||
assert refreshed.status == 'queued'
|
||||
assert refreshed.payload_json['retry_dispatch_files'] == [marker]
|
||||
@@ -418,7 +418,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta
|
||||
|
||||
facts = _project_case_formal_gate_facts({
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_source_routing',
|
||||
'gate_code': 'onhand_source_routing',
|
||||
'status': 'pending',
|
||||
'blocking_reason_code': None,
|
||||
'next_action_code': None,
|
||||
@@ -430,7 +430,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta
|
||||
|
||||
assert facts is not None
|
||||
current_gate, blocking_reason, user_status = facts
|
||||
assert current_gate['gate_code'] == 'inventory_source_routing'
|
||||
assert current_gate['gate_code'] == 'onhand_source_routing'
|
||||
assert blocking_reason['code'] is None
|
||||
assert user_status == 'running'
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
tests/services/shipping_notice/test_report_model_boundary.py
|
||||
|
||||
用途:阶段 B Task 5 边界门禁——禁止发货域(shipping_notice)源码直接构造
|
||||
货代 RPA 报表模型行(FreightRpaOnhandReportFile / FreightRpaInboundReportFile /
|
||||
FreightRpaInboundReportConfig 的构造调用)。插入必须经
|
||||
freight_rpa/onhand/report_store,读取/下载必须走 freight_rpa/reports 查询面。
|
||||
依赖:无运行时依赖(纯文件系统扫描);backend/app/services/shipping_notice 源码。
|
||||
逻辑:rglob 全部 *.py 逐文件搜禁词构造片段;命中即失败并列出文件与片段,
|
||||
保证违规时能一眼定位,而不是只报一个计数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_shipping_notice_does_not_construct_rpa_report_rows():
|
||||
root = Path(__file__).resolve().parents[3] / "app" / "services" / "shipping_notice"
|
||||
banned_snippets = ("FreightRpaOnhandReportFile(", "FreightRpaInboundReportFile(", "FreightRpaInboundReportConfig(")
|
||||
hits = []
|
||||
for path in root.rglob("*.py"):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
for snippet in banned_snippets:
|
||||
if snippet in text:
|
||||
hits.append(f"{path.name}: {snippet}")
|
||||
# 关键断言:三类 RPA 报表行的构造调用必须全部消失(插入已收敛进 report_store)。
|
||||
assert hits == []
|
||||
Reference in new issue
Block a user