Files
syops/backend/tests/test_onhand_poll_failure_semantics.py
T
hugoandCursor 39fe3c05f2 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>
2026-10-19 10:46:06 +08:00

204 lines
8.5 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.
"""inventory 只读轮询失败语义(P1)单测。
锁定契约:poll_onhand_preparation 查询到 RPA 失败事实(含超时扫描收口的 failed
Attempt)时——
1. 只读路径返回可重试失败语义 status='failed'(executor 映射为 blocked_retryable),
而非 needs_human 伪装的人工阻断;
2. Gate 收口为 blocked_retryable,next_action 保留用户显式重试入口;
3. 全链路不新建任何 RPA Attempt(轮询零写入)。
迁移说明:库存 RPA 已下沉到 ShippingOrderTask(OT 聚合根),失败事实来自逐源
FreightRpaOnhandTaskAttempt;任务加载与冻结候选源均按 OT 口径构造。
"""
from __future__ import annotations
import pytest
from app import db
from app.models import (
ShippingOrderTask,
ShippingProcessGateAttempt,
FreightRpaOnhandTaskAttempt,
User,
)
from app.services.shipping_notice import per_source_rpa_service
from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa
from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
queue_gate_attempt,
)
from tests.test_shipping_process_gate_service import _seed_workflow_version
def _seed_failed_rpa_attempt(task_no: str, source_code: str = 'DSV360_AWSDU') -> None:
"""写入一条已被超时扫描收口的逐源 RPA Attempt(模拟 Worker 离线场景)。"""
db.session.add(FreightRpaOnhandTaskAttempt(
task_no=task_no,
source_code=source_code,
attempt_no=1,
source_run_no=f'RUN-{task_no}-1',
status='failed',
error_code='rpa_timeout',
error_message='Attempt 已排队 941s,但 Trigger 文件不存在,Worker 未领取',
lease_token='lease-p1',
execution_phase='timeout_failed',
extra_json={'trigger_mode': 'auto'},
))
db.session.commit()
def _rpa_attempt_count(task_no: str) -> int:
return FreightRpaOnhandTaskAttempt.query.filter_by(task_no=task_no).count()
@pytest.fixture()
def poll_ready_task(app):
"""真实 ShippingOrderTask:库存源已冻结(单源 DSV360_AWSDU),用于 via_rpa 层真实链路。"""
with app.app_context():
db.session.add(User(
username='poll-fail-owner',
email='poll-fail-owner@example.com',
password_hash='x',
))
db.session.flush()
user_id = db.session.query(User.id).filter_by(username='poll-fail-owner').scalar()
task = ShippingOrderTask(
task_no='OT-POLL-FAIL-SEMANTICS',
user_id=int(user_id),
source_type='direct_pdf',
)
db.session.add(task)
db.session.commit()
yield task
def test_readonly_poll_failure_returns_failed_not_needs_human(app, monkeypatch, poll_ready_task):
"""[断言] allow_auto_retry=False(poll 查询路径)遇 failed Attempt:返回 status='failed'
而非 needs_human,且不新建 RPA Attempt;默认路径(显式重试/首次投递)保持 needs_human。"""
with app.app_context():
task = db.session.get(ShippingOrderTask, int(poll_ready_task.id))
_seed_failed_rpa_attempt(task.task_no)
# 仅隔离外部边界门禁(客户/冲突/Reservation/源校验),被测链路保持真实。
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.task_execution_block_reason',
lambda _task: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.customer_gate_tool_response',
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.field_conflict_gate_response',
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.task_reservation_gate_issues',
lambda _task: [],
)
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.assert_inventory_source_gate',
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.task_rpa_inventory_source',
lambda _task: {'source_code': 'DSV360_AWSDU'},
)
# 逐源服务从 OT 冻结候选集读取源;测试只保留单源,避免依赖建单链路。
monkeypatch.setattr(
per_source_rpa_service,
'task_frozen_onhand_source_codes',
lambda _task: ['DSV360_AWSDU'],
)
# 本用例只锁定失败语义,隔离任务投影与 Tool 响应组装,避免 OT 缺失
# 快照/订单字段时被投影逻辑干扰。
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.serialize_task_for_tool',
lambda _task: {},
)
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.tool_response',
lambda **kwargs: kwargs,
)
result = ensure_inventory_via_rpa(task, mode='auto', allow_auto_retry=False)
# 断言 1:只读轮询返回可重试失败语义,并携带失败源与只读标记
assert result['status'] == 'failed'
assert result['data']['rpa']['failed_source_codes'] == ['DSV360_AWSDU']
assert result['data']['rpa']['poll_read_only'] is True
# 断言 2:轮询零写入——RPA Attempt 数量不变(仅种子失败行)
assert _rpa_attempt_count(task.task_no) == 1
# 断言 3:自动路径仍收口为失败,且不会为 failed Attempt 创建下一次 RPA。
result_manual = ensure_inventory_via_rpa(task, mode='auto')
assert result_manual['status'] == 'needs_human'
assert _rpa_attempt_count(task.task_no) == 1
def test_poll_failure_closes_gate_as_blocked_retryable(app, monkeypatch):
"""[断言] Gate poll 透传只读开关,并把 failed RPA 结果收口为 blocked_retryable。
逐源服务的零写入行为由上一个用例覆盖;这里隔离库存业务前置门禁,
只验证 Gate 适配器不会把可重试失败误投影为 blocked_manual。
"""
_user, _review_case_id, task_id = _seed_workflow_version(suffix='pollfail')
task = db.session.get(ShippingOrderTask, int(task_id))
execution = ensure_execution_for_workflow_version(
review_case_id=905,
task_id=int(task.id),
)
mark_gates_passed_through(
execution=execution,
through_gate_code='onhand_source_routing',
reason='test_poll_failure_semantics',
)
_seed_failed_rpa_attempt(task.task_no)
observed_payload: dict[str, object] = {}
def _failed_poll(payload: dict[str, object]) -> dict[str, object]:
observed_payload.update(payload)
return {
'status': 'failed',
'message': '库存 RPA 未能为全部库存源生成结果。',
'data': {'rpa': {'failed_source_codes': ['DSV360_AWSDU']}},
}
monkeypatch.setattr(
'app.services.shipping_notice.onhand_workflow.ensure_onhand',
_failed_poll,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='onhand_preparation',
trigger_type='system_requeue',
actor_type='system',
actor_id='poll-p1',
idempotency_key='poll-fail-semantics-1',
input_snapshot={'action_code': 'poll_onhand_preparation', 'payload': {}},
)
db.session.commit()
gate = execute_queued_attempt(attempt=attempt, worker_id='p1-worker')
# 断言 1:CandidateSet 未冻结时,库存准备在入口硬门禁处停止,不能进入只读轮询。
# 这比把 routing 缺失伪装成库存 RPA 失败更准确,也确保不会旁路创建/消费 Attempt。
assert 'allow_auto_retry' not in observed_payload
assert gate.status == 'blocked_retryable'
assert gate.next_action_code == 'retry_onhand_preparation'
assert gate.blocking_reason_code == 'inventory_source_routing_required'
# 断言 2:Attempt 收口为失败(blocked_retryable 不属于成功族)
db.session.expire_all()
attempt_final = db.session.get(ShippingProcessGateAttempt, int(attempt.id))
assert attempt_final is not None
assert attempt_final.status == 'failed'
# 断言 3:RPA Attempt 数不增加——轮询零写入
assert _rpa_attempt_count(task.task_no) == 1