Files
syops/backend/tests/test_shipping_process_gate_service.py
T
hugo c94d173f92 feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口
完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
2026-08-11 14:04:39 +08:00

688 lines
15 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 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',
process_status='waiting_inventory',
)
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_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'
@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_with_latest_rules'},
)
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_with_latest_rules'},
)
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_with_latest_rules'},
)
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_with_latest_rules'},
)
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_with_latest_rules'},
)
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_with_latest_rules'},
)
assert exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'