Files
syops/backend/tests/test_shipping_process_gate_service.py
T
hugo 1b6483a4ea feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
2026-08-20 20:23:10 +08:00

884 lines
22 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.
"""
tests/test_shipping_process_gate_service.py
用途:验证统一门禁领域服务的创建、状态机、指纹跳过、下游失效与全量 Gate 接线矩阵。
依赖:Flask testing app、process_gate_service、process_gate_bridge、process_gate_contract。
逻辑:最小 User/Task 夹具上创建 Execution;对每个 Gate 覆盖
passed / blocked_manual / failed_terminal;断言指纹未变不重跑;Gate 数量由契约驱动。
"""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any
import pytest
from app import db
from app.models import (
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingNotice,
User,
)
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES, PROCESS_GATE_DEFINITIONS
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
invalidate_downstream_gates,
queue_gate_attempt,
sync_gate_from_business_result,
)
def _seed_workflow_version(
suffix: str = '001',
*,
owner: User | None = None,
) -> tuple[User, int | None, int | None]:
"""
创建最小 User + ShippingNotice,供 Execution 绑定 review_case_id / task_id。
co8 后不再创建 Workflow 台账;保留函数名以兼容其它门禁测试模块 import。
Args:
suffix: 用于编号去重的后缀。
owner: 非空时 Task 归属该用户;否则新建 gate 测试用户。
Returns:
(user, review_case_id, task_id)
"""
tag = str(suffix or '001')[:40]
user = owner
if user is None:
user = User(username=f'gate-svc-{tag}', email=f'gate-svc-{tag}@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingNotice(
task_no=f'SN-GATE-{tag}',
user_id=int(user.id),
source_type='manual',
)
db.session.add(task)
db.session.flush()
return user, None, int(task.id)
@pytest.fixture
def gate_execution(app):
"""提供已初始化全量 Gate 的 Execution(数量由 PROCESS_GATE_DEFINITIONS 驱动)。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version()
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
actor_type='system',
actor_id='test',
)
db.session.commit()
yield execution
def test_ensure_execution_creates_all_contract_gates(gate_execution):
"""创建 Execution 时必须初始化契约定义的全部 Gate 行(禁止硬编码 19/20)。"""
gates = ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all()
assert len(gates) == len(PROCESS_GATE_CODES)
assert {g.gate_code for g in gates} == set(PROCESS_GATE_CODES)
assert gate_execution.current_gate_code == 'document_materialization'
def test_ensure_execution_for_task_ignores_superseded_execution(app):
"""Task 指针指向已替代 Execution 时必须创建新正式链,不能复用历史 Gate。"""
with app.app_context():
_user, _review_case_id, task_id = _seed_workflow_version(suffix='superseded-task')
old = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
old.status = 'superseded'
db.session.flush()
current = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
assert current.id != old.id
assert current.status == 'active'
def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeypatch):
"""首次进入库存准备没有任何 RPA Attempt 时,自动推进必须投递一次 trigger。"""
from app.services.shipping_notice import process_gate_service
for prior_gate in (
ShippingProcessGate.query
.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
)
.all()
):
prior_gate.status = 'passed'
gate = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_retryable'
gate.next_action_code = 'retry_inventory_preparation'
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
queued: list[dict[str, object]] = []
monkeypatch.setattr(
process_gate_service,
'queue_gate_attempt',
lambda **kwargs: (queued.append(kwargs), SimpleNamespace(id=1))[1],
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
lambda **_kwargs: None,
)
process_gate_service._enqueue_auto_progress_after_gate_pass(
execution=gate_execution,
gate=gate,
)
assert len(queued) == 1
assert queued[0]['gate_code'] == 'inventory_preparation'
def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch):
"""已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。"""
from app.services.shipping_notice import process_gate_service
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
for prior_gate in ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
).all():
prior_gate.status = 'passed'
gate = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_retryable'
gate.next_action_code = 'retry_inventory_preparation'
task = db.session.get(ShippingNotice, int(gate_execution.task_id))
db.session.add(ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='TEST', attempt_no=1, source_run_no='PSR-FAILED',
status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written',
))
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
queued: list[dict[str, object]] = []
monkeypatch.setattr(process_gate_service, 'queue_gate_attempt', lambda **kwargs: queued.append(kwargs))
process_gate_service._enqueue_auto_progress_after_gate_pass(execution=gate_execution, gate=gate)
assert queued == []
def test_auto_progress_does_not_queue_manual_inventory_navigation(gate_execution, monkeypatch):
"""库存已入库后的 upload_inventory_file 是导航动作,不能被自动续跑执行。"""
from app.services.shipping_notice import process_gate_service
for prior_gate in (
ShippingProcessGate.query
.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
)
.all()
):
prior_gate.status = 'passed'
gate = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'inventory_rpa_timeout'
gate.next_action_code = 'upload_inventory_file'
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
queued: list[dict[str, object]] = []
monkeypatch.setattr(
process_gate_service,
'queue_gate_attempt',
lambda **kwargs: queued.append(kwargs),
)
process_gate_service._enqueue_auto_progress_after_gate_pass(
execution=gate_execution,
gate=gate,
)
assert queued == []
def test_fingerprint_skip_does_not_rerun_passed_gate(gate_execution):
"""已通过且输入指纹未变的 Gate 不重跑。"""
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
first = apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'stage': 'ok'},
input_fingerprint='fp-doc-1',
idempotency_key='fp-skip-1',
)
attempts_before = ShippingProcessGateAttempt.query.filter_by(gate_id=int(first.id)).count()
second = apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'stage': 'ok'},
input_fingerprint='fp-doc-1',
idempotency_key='fp-skip-2',
)
attempts_after = ShippingProcessGateAttempt.query.filter_by(gate_id=int(second.id)).count()
assert second.status == 'passed'
assert attempts_after == attempts_before
def test_upstream_invalidation_only_targets_dependents(gate_execution):
"""库存源变化只失效依赖下游,不碰无关前置门禁。"""
apply_gate_outcome(
execution=gate_execution,
gate_code='inventory_matching',
passed=True,
effective_result={'matched': True},
force=True,
idempotency_key='inv-match-pass',
)
apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'ok': True},
force=True,
idempotency_key='doc-pass',
)
invalidated = invalidate_downstream_gates(
execution=gate_execution,
change_type='inventory_source_changed',
)
assert 'inventory_matching' in invalidated
assert 'document_materialization' not in invalidated
doc = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id),
gate_code='document_materialization',
).first()
assert doc.status == 'passed'
def test_invalidation_uses_target_gate_retry_action_not_inventory_reroute_fallback(gate_execution):
"""下游 Excel Gate 失效后只能保留自身的重检动作,不能落入库存源重路由兜底。"""
excel = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='excel_readiness',
).one()
excel.status = 'passed'
db.session.flush()
invalidate_downstream_gates(
execution=gate_execution,
change_type='inventory_file_changed',
)
assert excel.status == 'invalidated'
assert excel.next_action_code == 'recheck_excel_readiness'
def test_queue_gate_attempt_rejects_action_owned_by_another_gate(gate_execution):
"""任何调用方都不能把库存源路由动作创建到 Excel Gate Attempt。"""
from app.core.errors import ValidationError
with pytest.raises(ValidationError) as exc:
queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='excel_readiness',
trigger_type='auto',
actor_type='system',
actor_id='test',
idempotency_key='wrong-action-excel-gate',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
assert getattr(exc.value, 'code', None) == 'SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED'
@pytest.mark.parametrize('gate_code', [str(item['gate_code']) for item in PROCESS_GATE_DEFINITIONS])
def test_each_gate_supports_passed_manual_blocked_and_technical_failed(app, gate_code):
"""
契约定义的每个 Gate 至少覆盖 passed、blocked_manual、failed_terminal 三类结果。
核心逻辑:同一 Execution 上对目标 Gate 依次同步三类 outcome。
"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix=gate_code.replace('_', '')[:32])
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
# [STEP 1] passed
passed = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code=gate_code,
passed=True,
effective_result_json={'findings': [], 'case': 'passed'},
idempotency_key=f'{gate_code}:passed',
invalidate_change_type=None,
)
assert passed.status == 'passed'
# [STEP 2] blocked_manual(允许 repass)
blocked = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code=gate_code,
passed=False,
blocking_reason_code='gate_invalidated',
effective_result_json={'findings': [], 'case': 'blocked_manual'},
idempotency_key=f'{gate_code}:blocked',
invalidate_change_type=None,
)
assert blocked.status == 'blocked_manual'
# [STEP 3] failed_terminal via complete path after queue
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code=gate_code,
trigger_type='system_requeue',
actor_type='system',
actor_id='test',
idempotency_key=f'{gate_code}:terminal',
)
from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running
mark_attempt_running(attempt_id=int(attempt.id), worker_id='test')
terminal = complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='failed_terminal',
error_code='TECH',
error_summary='technical failed',
effective_result_json={'case': 'failed_terminal'},
)
assert terminal.status == 'failed_terminal'
def test_business_sync_reuses_same_gate_active_attempt(app):
"""Gate 执行器同步同门业务事实时不得递归创建第二个 Attempt。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='activefactsync')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='active-fact-sync',
input_snapshot={
'action_code': 'retry_inventory_preparation',
'payload': {'actor_user_id': 1},
},
)
from app.services.shipping_notice.process_gate_service import mark_attempt_running
mark_attempt_running(attempt_id=int(attempt.id), worker_id='active-fact-sync')
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=False,
blocking_reason_code='inventory_file_missing',
effective_result_json={'findings': [], 'has_inventory_lines': False},
idempotency_key='nested-fact-sync-must-not-queue',
)
assert gate.status == 'running'
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
def test_force_business_sync_uses_current_gate_version(app):
"""强制重评不得回放失效前的固定幂等 Attempt。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='forceversion')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
first = apply_gate_outcome(
execution=execution,
gate_code='task_creation',
passed=True,
effective_result={'findings': [], 'task_no': 'T-1'},
idempotency_key='fixed-task-sync',
force=True,
)
assert first is not None and first.status == 'passed'
first.status = 'invalidated'
first.blocking_reason_code = 'gate_invalidated'
first.evaluation_version = int(first.evaluation_version) + 1
db.session.flush()
second = apply_gate_outcome(
execution=execution,
gate_code='task_creation',
passed=True,
effective_result={'findings': [], 'task_no': 'T-1'},
idempotency_key='fixed-task-sync',
force=True,
)
assert second is not None and second.status == 'passed'
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(second.id)).count() == 2
def test_idempotent_queue_replays_same_attempt(gate_execution):
"""相同幂等键只产生一个 Attempt。"""
first = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='same-key-ten-times',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
for _ in range(9):
again = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='same-key-ten-times',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
assert int(again.id) == int(first.id)
count = ShippingProcessGateAttempt.query.filter_by(idempotency_key='same-key-ten-times').count()
assert count == 1
def test_idempotent_key_conflicts_across_gate_and_action(gate_execution, app):
"""同幂等键跨 Gate / 跨 action 必须 409,禁止复用其他上下文 Attempt。"""
from app.core.errors import ConflictError
first = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
with pytest.raises(ConflictError) as gate_exc:
queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='order_extraction',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
assert gate_exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
with pytest.raises(ConflictError) as action_exc:
queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'open_order_review'},
)
assert action_exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='cross-context-key').count() == 1
assert int(first.id) == int(
ShippingProcessGateAttempt.query.filter_by(idempotency_key='cross-context-key').first().id
)
def test_idempotent_key_conflicts_across_execution(app):
"""同幂等键跨 Execution 必须冲突。"""
from app.core.errors import ConflictError
with app.app_context():
_u1, rc1, task1 = _seed_workflow_version(suffix='idem-a')
_u2, rc2, task2 = _seed_workflow_version(suffix='idem-b')
exe1 = ensure_execution_for_workflow_version(
review_case_id=rc1,
task_id=task1,
actor_type='system',
actor_id='test',
)
exe2 = ensure_execution_for_workflow_version(
review_case_id=rc2,
task_id=task2,
actor_type='system',
actor_id='test',
)
db.session.commit()
queue_gate_attempt(
execution_no=exe1.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-execution-key',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
with pytest.raises(ConflictError) as exc:
queue_gate_attempt(
execution_no=exe2.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-execution-key',
input_snapshot={'action_code': 'retry_layout_parsing'},
)
assert exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
def test_superseded_execution_rejects_late_business_gate_result(app):
"""候选版本已替换后,迟到结果不得重新写回旧 Gate。"""
from app.core.errors import ConflictError
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='superseded-sync')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
execution.status = 'superseded'
db.session.flush()
with pytest.raises(ConflictError) as exc:
sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=False,
blocking_reason_code='inventory_preparation_failed',
effective_result_json={'findings': []},
idempotency_key='late-result-must-not-write-superseded-execution',
)
assert exc.value.code == 'SHIPPING.PROCESS_EXECUTION_SUPERSEDED'