feat(shipping-process-gates): 落地全门禁中断恢复并消除双真相
纳入 Execution/Gate/Attempt 模型与迁移、Worker/API/前端恢复卡片与 Admin 诊断, Gate 阻断时清零旧 action_buttons,异常摘要统一脱敏,并为运维筛选与 Attempt Diff 补齐入口。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b352c281d5
commit
323928626b
92 files changed
+11930
-458
No files matched your search
@@ -0,0 +1,208 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_api.py
|
||||
|
||||
用途:Phase 5 Workspace/Admin 门禁 API 的 Envelope、403/404、禁止控制字段与幂等行为。
|
||||
依赖:Flask test client、JWT、process_gate_service / bridge 夹具、Agent 授权关系。
|
||||
逻辑:属主可读可写;同 Agent 授权人员只读;未授权他人 403;forbidden payload 400;
|
||||
同幂等键 POST 不产生第二 Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import Agent, ShippingProcessGate, ShippingProcessGateAttempt, User
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
from tests.test_shipping_process_gate_service import _seed_workflow_version
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""构造 Bearer 头。"""
|
||||
return {'Authorization': f'Bearer {issue_local_access_token(user)}', 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def _seed_blocked_execution(owner: User | None = None):
|
||||
"""
|
||||
创建属主 WorkflowItem + Execution,并将 order_freeze_readiness 置为 blocked_manual。
|
||||
|
||||
Returns:
|
||||
(owner, execution, gate)
|
||||
"""
|
||||
suffix = f'api{owner.id if owner else "x"}'[:24]
|
||||
user, item, version = _seed_workflow_version(suffix=suffix)
|
||||
if owner is not None:
|
||||
item.owner_user_id = int(owner.id)
|
||||
db.session.flush()
|
||||
user = owner
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
actor_type='system',
|
||||
actor_id=int(user.id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='order_freeze_readiness',
|
||||
passed=False,
|
||||
blocking_reason_code='auto_freeze_not_enabled',
|
||||
effective_result={'findings': []},
|
||||
force=True,
|
||||
idempotency_key=f'api-freeze-{execution.execution_no}',
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='order_freeze_readiness',
|
||||
).first()
|
||||
db.session.commit()
|
||||
return user, execution, gate
|
||||
|
||||
|
||||
def test_workspace_get_execution_owner_ok_other_forbidden(app, client):
|
||||
"""属主可 GET Execution;未授权他人返回 403。"""
|
||||
with app.app_context():
|
||||
owner, execution, _gate = _seed_blocked_execution()
|
||||
other = User(username='gate-api-other', email='gate-api-other@example.com', password_hash='x')
|
||||
db.session.add(other)
|
||||
db.session.commit()
|
||||
execution_no = execution.execution_no
|
||||
|
||||
ok = client.get(
|
||||
f'/api/workspace/shipping-notice/process-executions/{execution_no}',
|
||||
headers=_auth_headers(owner),
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
body = ok.get_json()
|
||||
assert body.get('success') is True
|
||||
assert body['data']['execution_no'] == execution_no
|
||||
|
||||
denied = client.get(
|
||||
f'/api/workspace/shipping-notice/process-executions/{execution_no}',
|
||||
headers=_auth_headers(other),
|
||||
)
|
||||
assert denied.status_code == 403
|
||||
err = denied.get_json()
|
||||
assert err.get('success') is False
|
||||
assert err.get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_PERMISSION_DENIED'
|
||||
|
||||
|
||||
def test_workspace_agent_authorized_readonly_cannot_write(app, client):
|
||||
"""同 Agent 授权人员可 GET,但 POST 恢复仍 403。"""
|
||||
with app.app_context():
|
||||
owner, execution, gate = _seed_blocked_execution()
|
||||
agent = Agent(
|
||||
name='Gate Readonly Agent',
|
||||
agent_code='gate_readonly_agent',
|
||||
dify_app_id='gate-readonly-app',
|
||||
dify_api_key='test-key',
|
||||
)
|
||||
viewer = User(username='gate-api-viewer', email='gate-api-viewer@example.com', password_hash='x')
|
||||
db.session.add_all([agent, viewer])
|
||||
db.session.flush()
|
||||
from app.models import ShippingNoticeWorkflow, ShippingNoticeWorkflowItem
|
||||
|
||||
item = db.session.get(ShippingNoticeWorkflowItem, int(execution.workflow_item_id))
|
||||
assert item is not None
|
||||
workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id))
|
||||
assert workflow is not None
|
||||
workflow.owner_agent_id = int(agent.id)
|
||||
viewer.agents = [agent]
|
||||
db.session.commit()
|
||||
execution_no = execution.execution_no
|
||||
|
||||
read_ok = client.get(
|
||||
f'/api/workspace/shipping-notice/process-executions/{execution_no}',
|
||||
headers=_auth_headers(viewer),
|
||||
)
|
||||
assert read_ok.status_code == 200
|
||||
assert read_ok.get_json()['data']['execution_no'] == execution_no
|
||||
|
||||
write_denied = client.post(
|
||||
f'/api/workspace/shipping-notice/process-executions/{execution_no}'
|
||||
f'/gates/order_freeze_readiness/actions',
|
||||
headers=_auth_headers(viewer),
|
||||
json={
|
||||
'action_code': 'open_order_review',
|
||||
'expected_gate_version': int(gate.evaluation_version),
|
||||
'idempotency_key': 'api-readonly-write-1',
|
||||
},
|
||||
)
|
||||
assert write_denied.status_code == 403
|
||||
assert write_denied.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_PERMISSION_DENIED'
|
||||
|
||||
|
||||
def test_workspace_post_action_rejects_forbidden_controls(app, client):
|
||||
"""POST 含 target_status 必须 400 且无 Attempt 副作用。"""
|
||||
with app.app_context():
|
||||
owner, execution, gate = _seed_blocked_execution()
|
||||
execution_no = execution.execution_no
|
||||
before = ShippingProcessGateAttempt.query.count()
|
||||
resp = client.post(
|
||||
f'/api/workspace/shipping-notice/process-executions/{execution_no}'
|
||||
f'/gates/order_freeze_readiness/actions',
|
||||
headers=_auth_headers(owner),
|
||||
json={
|
||||
'action_code': 'open_order_review',
|
||||
'expected_gate_version': int(gate.evaluation_version),
|
||||
'idempotency_key': 'api-forbidden-1',
|
||||
'target_status': 'passed',
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN'
|
||||
assert ShippingProcessGateAttempt.query.count() == before
|
||||
|
||||
|
||||
def test_workspace_post_action_idempotent(app, client):
|
||||
"""相同幂等键连续 POST 只产生一个 Attempt,并返回成功 Envelope。"""
|
||||
with app.app_context():
|
||||
owner, execution, gate = _seed_blocked_execution()
|
||||
execution_no = execution.execution_no
|
||||
payload = {
|
||||
'action_code': 'open_order_review',
|
||||
'expected_gate_version': int(gate.evaluation_version),
|
||||
'idempotency_key': 'api-idempotent-1',
|
||||
'payload': {'note': 'first'},
|
||||
}
|
||||
url = (
|
||||
f'/api/workspace/shipping-notice/process-executions/{execution_no}'
|
||||
f'/gates/order_freeze_readiness/actions'
|
||||
)
|
||||
first = client.post(url, headers=_auth_headers(owner), json=payload)
|
||||
assert first.status_code == 200
|
||||
first_body = first.get_json()
|
||||
assert first_body.get('success') is True
|
||||
attempt_id = first_body['data']['attempt']['id']
|
||||
|
||||
# 版本已前进时,回放同幂等键仍应返回首次 Attempt,不新建。
|
||||
second = client.post(url, headers=_auth_headers(owner), json=payload)
|
||||
assert second.status_code == 200
|
||||
second_body = second.get_json()
|
||||
assert second_body['data']['attempt']['id'] == attempt_id
|
||||
assert second_body['data'].get('dispatch') == 'idempotent_replay'
|
||||
assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='api-idempotent-1').count() == 1
|
||||
|
||||
|
||||
def test_workspace_get_missing_execution_404(app, client):
|
||||
"""不存在的 execution_no 返回 404。"""
|
||||
with app.app_context():
|
||||
user = User(username='gate-api-404', email='gate-api-404@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
resp = client.get(
|
||||
'/api/workspace/shipping-notice/process-executions/SPE-NOT-EXIST',
|
||||
headers=_auth_headers(user),
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_EXECUTION_NOT_FOUND'
|
||||
|
||||
|
||||
def test_admin_list_executions_requires_admin(app, client):
|
||||
"""Admin 列表接口拒绝普通用户。"""
|
||||
with app.app_context():
|
||||
owner, _execution, _gate = _seed_blocked_execution()
|
||||
resp = client.get(
|
||||
'/api/admin/shipping-notice/process-executions',
|
||||
headers=_auth_headers(owner),
|
||||
)
|
||||
assert resp.status_code in {401, 403}
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_contract.py
|
||||
|
||||
用途:锁定全门禁中断恢复 Phase 1/1.5 契约与依赖图完整性(编码、动作、失效范围、原因归属)。
|
||||
依赖:process_gate_contract、process_gate_dependency。
|
||||
逻辑:调用 assert_*_integrity;断言 19 个唯一门禁、原因码唯一 owning_gate、
|
||||
字段阻断资格与 Excel 仅重生失效范围。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
AUTO_BUILD_LEGACY_GATE_OWNING_MAP,
|
||||
PROCESS_GATE_CODES,
|
||||
PROCESS_GATE_CODE_SET,
|
||||
PROCESS_GATE_DEFINITIONS,
|
||||
PROCESS_GATE_REASON_OWNING_GATE,
|
||||
assert_process_gate_contract_integrity,
|
||||
field_quality_may_block,
|
||||
owning_gate_for_reason,
|
||||
primary_next_action_for_gate,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_dependency import (
|
||||
PROCESS_GATE_INVALIDATION_RULES,
|
||||
assert_process_gate_dependency_integrity,
|
||||
compute_invalidated_gates,
|
||||
)
|
||||
|
||||
|
||||
def test_process_gate_contract_integrity():
|
||||
"""
|
||||
校验门禁契约无重复编码、序号连续且动作/状态闭环。
|
||||
|
||||
核心逻辑:直接调用契约自检;再断言恰好 19 个唯一 gate_code。
|
||||
"""
|
||||
# [STEP 1] 契约自检(重复码 / 序号 / 动作归属)
|
||||
assert_process_gate_contract_integrity()
|
||||
|
||||
# [STEP 2] 冻结规模:19 门禁且集合与有序列表一致
|
||||
assert len(PROCESS_GATE_DEFINITIONS) == 19
|
||||
assert len(PROCESS_GATE_CODES) == 19
|
||||
assert len(PROCESS_GATE_CODE_SET) == 19
|
||||
assert set(PROCESS_GATE_CODES) == PROCESS_GATE_CODE_SET
|
||||
|
||||
|
||||
def test_inventory_source_routing_primary_retry_action():
|
||||
"""
|
||||
库存源路由在 blocked_retryable 时主恢复动作必须为按最新规则重试。
|
||||
|
||||
核心逻辑:primary_next_action_for_gate 禁止前端本地推导。
|
||||
"""
|
||||
action = primary_next_action_for_gate(
|
||||
gate_code='inventory_source_routing',
|
||||
status='blocked_retryable',
|
||||
)
|
||||
assert action == 'retry_with_latest_rules'
|
||||
|
||||
|
||||
def test_process_gate_reason_ownership_is_unique():
|
||||
"""
|
||||
每个阻断原因码恰好映射一个 owning_gate,覆盖率 100%。
|
||||
|
||||
核心逻辑:契约自检 + 显式抽查自动冻结与字段完整性归属。
|
||||
"""
|
||||
assert_process_gate_contract_integrity()
|
||||
assert owning_gate_for_reason('profile_manual_confirmation_required') == 'order_freeze_readiness'
|
||||
assert owning_gate_for_reason('required_field_missing') == 'field_completeness'
|
||||
assert owning_gate_for_reason('customer_unresolved') == 'customer_resolution'
|
||||
assert owning_gate_for_reason('evidence_missing') == 'order_field_extraction'
|
||||
# 旧五门禁键不得再各自成为用户阻断真相。
|
||||
assert AUTO_BUILD_LEGACY_GATE_OWNING_MAP['quality_gate_passed'] == 'order_freeze_readiness'
|
||||
assert AUTO_BUILD_LEGACY_GATE_OWNING_MAP['approved_template'] == 'order_freeze_readiness'
|
||||
assert len(PROCESS_GATE_REASON_OWNING_GATE) == len(set(PROCESS_GATE_REASON_OWNING_GATE.keys()))
|
||||
|
||||
|
||||
def test_field_quality_block_eligibility():
|
||||
"""仅 required 或 auto_create_key_field 可因字段质量阻断。"""
|
||||
assert field_quality_may_block(required=True, auto_create_key_field=False) is True
|
||||
assert field_quality_may_block(required=False, auto_create_key_field=True) is True
|
||||
assert field_quality_may_block(required=False, auto_create_key_field=False) is False
|
||||
|
||||
|
||||
def test_process_gate_dependency_integrity_and_excel_only_scope():
|
||||
"""
|
||||
校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。
|
||||
|
||||
核心逻辑:依赖自检 + excel_regeneration_only 显式排除 inventory_matching。
|
||||
"""
|
||||
# [STEP 1] 前置依赖与失效规则仅引用已知门禁
|
||||
assert_process_gate_dependency_integrity()
|
||||
|
||||
# [STEP 2] 仅重生 Excel:失效 artifact + 人工上传,不碰库存匹配
|
||||
excel_only = compute_invalidated_gates('excel_regeneration_only')
|
||||
assert 'inventory_matching' not in excel_only
|
||||
assert 'artifact_generation' in excel_only
|
||||
assert 'manual_upload_handoff' in excel_only
|
||||
assert set(excel_only) == set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only'])
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_error_sanitizer.py
|
||||
|
||||
用途:验证门禁异常摘要脱敏会剥离 URL、路径与凭据片段。
|
||||
依赖:process_gate_error_sanitizer.sanitize_gate_error_text。
|
||||
逻辑:对含敏感片段的样本文本断言输出不含原值且保留可读业务提示。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
|
||||
|
||||
|
||||
def test_sanitize_gate_error_text_redacts_url_path_and_secret():
|
||||
"""URL、Windows 路径与 password= 片段必须被遮蔽。"""
|
||||
raw = (
|
||||
'failed call https://erp.example.com/api?token=abc '
|
||||
r'at C:\service\worker.py password=super-secret '
|
||||
'detail=timeout'
|
||||
)
|
||||
cleaned = sanitize_gate_error_text(raw, max_len=500)
|
||||
assert cleaned is not None
|
||||
assert 'https://' not in cleaned
|
||||
assert 'erp.example.com' not in cleaned
|
||||
assert r'C:\service' not in cleaned
|
||||
assert 'super-secret' not in cleaned
|
||||
assert '[url]' in cleaned
|
||||
assert '[path]' in cleaned
|
||||
assert 'timeout' in cleaned
|
||||
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_fault_injection.py
|
||||
|
||||
用途:Phase 7 故障注入——幂等连点、审计失败回滚语义、租约冲突、双路径不双写。
|
||||
依赖:process_gate_service、process_gate_recovery_service、Flask testing app。
|
||||
逻辑:在最小 Execution 夹具上模拟重复恢复请求与审计异常,断言无副作用双写。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ServiceUnavailableError
|
||||
from app.models import ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
from app.services.shipping_notice.process_gate_recovery_service import request_gate_action
|
||||
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 test_ten_identical_recovery_clicks_create_one_attempt(app):
|
||||
"""同一幂等键连点十次只产生一个 Attempt。"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='fault1')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='layout_parsing',
|
||||
passed=False,
|
||||
blocking_reason_code='layout_parse_failed',
|
||||
effective_result={'findings': []},
|
||||
force=True,
|
||||
idempotency_key='layout-fail-seed',
|
||||
)
|
||||
gate = (
|
||||
db.session.query(__import__('app.models', fromlist=['ShippingProcessGate']).ShippingProcessGate)
|
||||
.filter_by(execution_id=int(execution.id), gate_code='layout_parsing')
|
||||
.first()
|
||||
)
|
||||
key = 'fault-ten-clicks'
|
||||
first = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='user_retry',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
idempotency_key=key,
|
||||
expected_gate_version=int(gate.evaluation_version),
|
||||
)
|
||||
for _ in range(9):
|
||||
again = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='user_retry',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
idempotency_key=key,
|
||||
expected_gate_version=int(gate.evaluation_version),
|
||||
)
|
||||
assert int(again.id) == int(first.id)
|
||||
assert ShippingProcessGateAttempt.query.filter_by(idempotency_key=key).count() == 1
|
||||
|
||||
|
||||
def test_active_attempt_blocks_second_queue(app):
|
||||
"""已有活动 Attempt 时第二次不同幂等键必须 Conflict。"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='fault2')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='layout_parsing',
|
||||
passed=False,
|
||||
blocking_reason_code='layout_parse_failed',
|
||||
effective_result={},
|
||||
force=True,
|
||||
idempotency_key='layout-fail-2',
|
||||
)
|
||||
from app.models import ShippingProcessGate
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='layout_parsing',
|
||||
).first()
|
||||
queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='user_retry',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
idempotency_key='active-a',
|
||||
expected_gate_version=int(gate.evaluation_version),
|
||||
)
|
||||
db.session.refresh(gate)
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='user_retry',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
idempotency_key='active-b',
|
||||
expected_gate_version=int(gate.evaluation_version),
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING.PROCESS_GATE_BUSY'
|
||||
|
||||
|
||||
def test_audit_failure_rolls_back_gate_queue(app, monkeypatch):
|
||||
"""
|
||||
审计失败时业务事务应整体失败,不留下半成品 Attempt。
|
||||
|
||||
核心逻辑:monkeypatch record_fulfillment_audit 抛错,断言 queue 抛出且无 Attempt 行。
|
||||
"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='fault3')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='layout_parsing',
|
||||
passed=False,
|
||||
blocking_reason_code='layout_parse_failed',
|
||||
effective_result={},
|
||||
force=True,
|
||||
idempotency_key='layout-fail-3',
|
||||
)
|
||||
from app.models import ShippingProcessGate
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='layout_parsing',
|
||||
).first()
|
||||
version_before = int(gate.evaluation_version)
|
||||
|
||||
def _boom(**kwargs):
|
||||
raise ServiceUnavailableError('audit down', code='SHIPPING.AUDIT_UNAVAILABLE')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_service.record_fulfillment_audit',
|
||||
_boom,
|
||||
)
|
||||
with pytest.raises(ServiceUnavailableError):
|
||||
queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='user_retry',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
idempotency_key='audit-fail-key',
|
||||
expected_gate_version=version_before,
|
||||
)
|
||||
db.session.rollback()
|
||||
assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='audit-fail-key').count() == 0
|
||||
|
||||
|
||||
def test_request_gate_action_rejects_forbidden_controls(app):
|
||||
"""客户端提交 target_status / worker_name 必须被拒绝。"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='fault4')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='order_freeze_readiness',
|
||||
passed=False,
|
||||
blocking_reason_code='auto_freeze_not_enabled',
|
||||
effective_result={},
|
||||
force=True,
|
||||
idempotency_key='freeze-block-fault',
|
||||
)
|
||||
from app.models import ShippingProcessGate
|
||||
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='order_freeze_readiness',
|
||||
).first()
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
request_gate_action(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='order_freeze_readiness',
|
||||
action_code='open_order_review',
|
||||
expected_gate_version=int(gate.evaluation_version),
|
||||
idempotency_key='forbidden-payload',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
payload={'target_status': 'passed', 'worker_name': 'evil'},
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING.PROCESS_GATE_ACTION_FORBIDDEN'
|
||||
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_lease.py
|
||||
|
||||
用途:验证门禁 Attempt 租约竞争、心跳续租与超时接管。
|
||||
依赖:process_gate_job_service、process_gate_service、Flask testing app。
|
||||
逻辑:创建 queued Attempt 后双 Worker claim,仅一方持有租约;心跳超时后 recover 接管。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_job_service import (
|
||||
claim_and_run_gate_attempt,
|
||||
heartbeat_gate_attempt,
|
||||
recover_stale_gate_attempts,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
mark_attempt_running,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
from tests.test_shipping_process_gate_service import _seed_workflow_version
|
||||
|
||||
|
||||
def test_lease_takeover_after_stale_heartbeat(app, monkeypatch):
|
||||
"""心跳超过接管阈值后,recover_stale_gate_attempts 必须接管。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service._takeover_seconds',
|
||||
lambda: 30,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
|
||||
lambda **kwargs: 0,
|
||||
)
|
||||
_user, item, version = _seed_workflow_version(suffix='lease1')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='user_retry',
|
||||
actor_type='system',
|
||||
actor_id='w1',
|
||||
idempotency_key='lease-takeover-1',
|
||||
)
|
||||
mark_attempt_running(
|
||||
attempt_id=int(attempt.id),
|
||||
worker_id='worker-a',
|
||||
lease_token='token-a',
|
||||
lease_expires_at=datetime.utcnow() - timedelta(seconds=120),
|
||||
)
|
||||
# 心跳早于接管阈值(默认/补丁 30s)即可被 recover 选中。
|
||||
attempt.heartbeat_at = datetime.utcnow() - timedelta(seconds=120)
|
||||
db.session.flush()
|
||||
|
||||
taken = recover_stale_gate_attempts(worker_id='worker-b')
|
||||
assert int(attempt.id) in taken
|
||||
db.session.refresh(attempt)
|
||||
assert attempt.status == 'queued'
|
||||
assert attempt.worker_id is None
|
||||
assert attempt.lease_token is None
|
||||
|
||||
|
||||
def test_heartbeat_rejects_foreign_lease(app):
|
||||
"""租约 Token 不匹配时心跳必须 Conflict。"""
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='lease2')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='w1',
|
||||
idempotency_key='lease-hb-1',
|
||||
)
|
||||
mark_attempt_running(
|
||||
attempt_id=int(attempt.id),
|
||||
worker_id='worker-a',
|
||||
lease_token='token-a',
|
||||
lease_expires_at=datetime.utcnow() + timedelta(seconds=60),
|
||||
)
|
||||
try:
|
||||
heartbeat_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
worker_id='worker-b',
|
||||
lease_token='wrong',
|
||||
)
|
||||
assert False, 'expected ConflictError'
|
||||
except ConflictError as err:
|
||||
assert err.code == 'SHIPPING.PROCESS_GATE_LEASE_CONFLICT'
|
||||
|
||||
|
||||
def test_sync_manual_open_via_claim_and_run(app, monkeypatch):
|
||||
"""claim_and_run 对同步人工入口动作可完成 Attempt。"""
|
||||
with app.app_context():
|
||||
# enqueue 在 recover 空跑时无副作用;claim 路径执行 open_order_review。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
|
||||
lambda **kwargs: 0,
|
||||
)
|
||||
_user, item, version = _seed_workflow_version(suffix='lease3')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
# 先阻断冻结门禁,再排队人工打开动作。
|
||||
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
|
||||
|
||||
apply_gate_outcome(
|
||||
execution=execution,
|
||||
gate_code='order_freeze_readiness',
|
||||
passed=False,
|
||||
blocking_reason_code='auto_freeze_not_enabled',
|
||||
effective_result={'findings': []},
|
||||
force=True,
|
||||
idempotency_key='freeze-block-1',
|
||||
)
|
||||
gate = db.session.query(__import__('app.models', fromlist=['ShippingProcessGate']).ShippingProcessGate).filter_by(
|
||||
execution_id=int(execution.id),
|
||||
gate_code='order_freeze_readiness',
|
||||
).first()
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='order_freeze_readiness',
|
||||
trigger_type='user_manual',
|
||||
actor_type='user',
|
||||
actor_id=1,
|
||||
idempotency_key='open-review-1',
|
||||
expected_gate_version=int(gate.evaluation_version),
|
||||
input_snapshot={'action_code': 'open_order_review', 'payload': {'actor_user_id': 1}},
|
||||
)
|
||||
result = claim_and_run_gate_attempt(attempt_id=int(attempt.id), worker_id='worker-sync')
|
||||
assert result.get('skipped') is False
|
||||
db.session.refresh(attempt)
|
||||
assert attempt.status in {'succeeded', 'failed'}
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_migration.py
|
||||
|
||||
用途:验证门禁恢复迁移 upgrade/downgrade 往返及关键索引存在。
|
||||
依赖:Alembic Operations、SQLite 内存库、d0e1f2a3b4c6 迁移。
|
||||
逻辑:构造最小父表 → upgrade 断言三表与活动 Attempt 唯一索引 → downgrade 断言表消失。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_shipping_process_gate_migration_round_trip(monkeypatch):
|
||||
"""upgrade 创建三表与索引;downgrade 完整删除。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.d0e1f2a3b4c6_add_shipping_process_gate_recovery',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('jobs', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_order_review_cases', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('shipping_notice_workflow_items', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_notice_workflow_item_versions',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
# 迁移会放宽 shipping_audit_events.actor_type CHECK,测试库需有最小表桩。
|
||||
sa.Table(
|
||||
'shipping_audit_events',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('actor_type', sa.String(length=32), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')",
|
||||
name='ck_shipping_audit_events_actor_type',
|
||||
),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
tables = set(inspector.get_table_names())
|
||||
assert 'shipping_process_executions' in tables
|
||||
assert 'shipping_process_gates' in tables
|
||||
assert 'shipping_process_gate_attempts' in tables
|
||||
|
||||
attempt_indexes = {
|
||||
item['name'] for item in inspector.get_indexes('shipping_process_gate_attempts')
|
||||
}
|
||||
assert 'uq_shipping_process_gate_attempts_one_active' in attempt_indexes
|
||||
assert 'uq_shipping_process_gate_attempts_idempotency' in {
|
||||
*(item['name'] for item in inspector.get_indexes('shipping_process_gate_attempts')),
|
||||
*(
|
||||
item['name']
|
||||
for item in inspector.get_unique_constraints('shipping_process_gate_attempts')
|
||||
),
|
||||
}
|
||||
|
||||
execution_indexes = {
|
||||
item['name'] for item in inspector.get_indexes('shipping_process_executions')
|
||||
}
|
||||
assert 'ix_shipping_process_executions_status_updated' in execution_indexes
|
||||
assert 'ix_shipping_process_executions_current_gate' in execution_indexes
|
||||
|
||||
gate_indexes = {
|
||||
item['name'] for item in inspector.get_indexes('shipping_process_gates')
|
||||
}
|
||||
assert 'ix_shipping_process_gates_execution_status' in gate_indexes
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
tables_after = set(inspector.get_table_names())
|
||||
assert 'shipping_process_executions' not in tables_after
|
||||
assert 'shipping_process_gates' not in tables_after
|
||||
assert 'shipping_process_gate_attempts' not in tables_after
|
||||
@@ -0,0 +1,191 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_models.py
|
||||
|
||||
用途:验证门禁恢复三模型的唯一约束、活动 Attempt 部分唯一索引与编号不可覆盖。
|
||||
依赖:Alembic Operations、SQLite 内存库、d0e1f2a3b4c6 迁移建表结果。
|
||||
逻辑:在最小父表桩上 upgrade 后插入 Execution/Gate/Attempt,断言重复 Execution、
|
||||
重复幂等键与双活动 Attempt 被数据库拒绝;终态后可创建下一 Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def _prepare_gate_tables(monkeypatch):
|
||||
"""
|
||||
创建迁移所需最小父表并执行 upgrade,返回 connection 与表对象。
|
||||
"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.d0e1f2a3b4c6_add_shipping_process_gate_recovery',
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table('jobs', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_tasks', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_review_cases', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notice_workflows', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notice_documents', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notice_workflow_items', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_notice_workflow_item_versions', metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_audit_events',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('actor_type', sa.String(length=32), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')",
|
||||
name='ck_shipping_audit_events_actor_type',
|
||||
),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
connection = engine.connect()
|
||||
connection.execute(sa.text('INSERT INTO shipping_notice_workflow_items (id) VALUES (1)'))
|
||||
connection.execute(sa.text('INSERT INTO shipping_notice_workflow_item_versions (id) VALUES (1)'))
|
||||
connection.execute(sa.text('INSERT INTO shipping_notice_workflow_item_versions (id) VALUES (2)'))
|
||||
connection.commit()
|
||||
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
migration.upgrade()
|
||||
|
||||
executions = sa.Table('shipping_process_executions', sa.MetaData(), autoload_with=connection)
|
||||
gates = sa.Table('shipping_process_gates', sa.MetaData(), autoload_with=connection)
|
||||
attempts = sa.Table('shipping_process_gate_attempts', sa.MetaData(), autoload_with=connection)
|
||||
return connection, migration, executions, gates, attempts
|
||||
|
||||
|
||||
def test_duplicate_execution_constraints_rejected(monkeypatch):
|
||||
"""重复 execution_no 与同一 version 的第二 Execution 必须被拒绝。"""
|
||||
connection, _migration, executions, gates, _attempts = _prepare_gate_tables(monkeypatch)
|
||||
now = datetime.utcnow()
|
||||
connection.execute(executions.insert().values(
|
||||
id=1, execution_no='SPE-1', workflow_item_id=1, workflow_item_version_id=1,
|
||||
status='active', lock_version=1, created_at=now, updated_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
|
||||
with pytest.raises(sa.exc.IntegrityError):
|
||||
connection.execute(executions.insert().values(
|
||||
id=2, execution_no='SPE-1', workflow_item_id=1, workflow_item_version_id=2,
|
||||
status='active', lock_version=1, created_at=now, updated_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
connection.rollback()
|
||||
|
||||
with pytest.raises(sa.exc.IntegrityError):
|
||||
connection.execute(executions.insert().values(
|
||||
id=3, execution_no='SPE-2', workflow_item_id=1, workflow_item_version_id=1,
|
||||
status='active', lock_version=1, created_at=now, updated_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
connection.rollback()
|
||||
|
||||
connection.execute(gates.insert().values(
|
||||
id=1, execution_id=1, gate_code='inventory_source_routing', sequence_no=10,
|
||||
status='blocked_retryable', evaluation_version=1, lock_version=1,
|
||||
created_at=now, updated_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
connection.close()
|
||||
|
||||
|
||||
def test_active_attempt_partial_unique_and_idempotency(monkeypatch):
|
||||
"""同一 Gate 不能有两个 queued/running Attempt;幂等键全局唯一。"""
|
||||
connection, _migration, executions, gates, attempts = _prepare_gate_tables(monkeypatch)
|
||||
now = datetime.utcnow()
|
||||
connection.execute(executions.insert().values(
|
||||
id=1, execution_no='SPE-ACTIVE', workflow_item_id=1, workflow_item_version_id=1,
|
||||
status='active', lock_version=1, created_at=now, updated_at=now,
|
||||
))
|
||||
connection.execute(gates.insert().values(
|
||||
id=1, execution_id=1, gate_code='inventory_source_routing', sequence_no=10,
|
||||
status='blocked_retryable', evaluation_version=1, lock_version=1,
|
||||
created_at=now, updated_at=now,
|
||||
))
|
||||
connection.execute(attempts.insert().values(
|
||||
id=1, gate_id=1, attempt_no=1, status='running', trigger_type='user_retry',
|
||||
actor_type='user', actor_id='1', idempotency_key='idem-1', created_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
|
||||
with pytest.raises(sa.exc.IntegrityError):
|
||||
connection.execute(attempts.insert().values(
|
||||
id=2, gate_id=1, attempt_no=2, status='queued', trigger_type='user_retry',
|
||||
actor_type='user', actor_id='1', idempotency_key='idem-2', created_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
connection.rollback()
|
||||
|
||||
with pytest.raises(sa.exc.IntegrityError):
|
||||
connection.execute(attempts.insert().values(
|
||||
id=3, gate_id=1, attempt_no=2, status='failed', trigger_type='user_retry',
|
||||
actor_type='user', actor_id='1', idempotency_key='idem-1', created_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
connection.rollback()
|
||||
connection.close()
|
||||
|
||||
|
||||
def test_succeeded_attempt_allows_next_number_not_reuse(monkeypatch):
|
||||
"""成功 Attempt 后可创建下一编号;不得复用同一 attempt_no。"""
|
||||
connection, _migration, executions, gates, attempts = _prepare_gate_tables(monkeypatch)
|
||||
now = datetime.utcnow()
|
||||
connection.execute(executions.insert().values(
|
||||
id=1, execution_no='SPE-OK', workflow_item_id=1, workflow_item_version_id=1,
|
||||
status='active', lock_version=1, created_at=now, updated_at=now,
|
||||
))
|
||||
connection.execute(gates.insert().values(
|
||||
id=1, execution_id=1, gate_code='task_creation', sequence_no=12,
|
||||
status='passed', evaluation_version=1, lock_version=1,
|
||||
created_at=now, updated_at=now,
|
||||
))
|
||||
connection.execute(attempts.insert().values(
|
||||
id=1, gate_id=1, attempt_no=1, status='succeeded', trigger_type='auto',
|
||||
actor_type='system', idempotency_key='idem-ok-1', finished_at=now, created_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
|
||||
connection.execute(attempts.insert().values(
|
||||
id=2, gate_id=1, attempt_no=2, status='queued', trigger_type='user_retry',
|
||||
actor_type='user', actor_id='9', idempotency_key='idem-ok-2', created_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
count = connection.execute(sa.text(
|
||||
'SELECT COUNT(*) FROM shipping_process_gate_attempts WHERE gate_id = 1'
|
||||
)).scalar_one()
|
||||
assert count == 2
|
||||
|
||||
with pytest.raises(sa.exc.IntegrityError):
|
||||
connection.execute(attempts.insert().values(
|
||||
id=3, gate_id=1, attempt_no=1, status='failed', trigger_type='auto',
|
||||
actor_type='system', idempotency_key='idem-ok-3', created_at=now,
|
||||
))
|
||||
connection.commit()
|
||||
connection.rollback()
|
||||
connection.close()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_requeue.py
|
||||
|
||||
用途:验证门禁 Job 技术重试 / 外部等待轮询不会复用仍 running 的旧 Job。
|
||||
依赖:process_gate_job_service.enqueue_gate_attempt_job、jobs.queue、Flask testing app。
|
||||
逻辑:先创建 running Job 绑定 Attempt,再 force_new 入队,必须得到不同 job_id 且新 Job 为 queued。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.process_gate_job_service import (
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
enqueue_gate_attempt_job,
|
||||
)
|
||||
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 test_force_new_enqueue_does_not_reuse_running_job(app):
|
||||
"""
|
||||
force_new=True 时即使存在同 attempt 的 running Job,也必须新建可领取 queued Job。
|
||||
"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix='requeue1')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='user_retry',
|
||||
actor_type='system',
|
||||
actor_id='requeue-worker',
|
||||
idempotency_key='requeue-force-new-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
# [STEP] 模拟旧 Job 仍为 running(重试前未结束)。
|
||||
running = Job(
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||||
status='running',
|
||||
business_ref=f'attempt:{int(attempt.id)}',
|
||||
payload_json={'attempt_id': int(attempt.id)},
|
||||
progress=10,
|
||||
message='running',
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(running)
|
||||
db.session.flush()
|
||||
attempt.job_id = int(running.id)
|
||||
db.session.flush()
|
||||
|
||||
# 若无 force_new,默认去重可能复用 running;此处必须新建。
|
||||
new_job_id = enqueue_gate_attempt_job(
|
||||
attempt_id=int(attempt.id),
|
||||
delay_seconds=5,
|
||||
force_new=True,
|
||||
)
|
||||
assert int(new_job_id) != int(running.id)
|
||||
new_job = db.session.get(Job, int(new_job_id))
|
||||
assert new_job is not None
|
||||
assert new_job.status == 'queued'
|
||||
assert str(new_job.business_ref or '').startswith(f'attempt:{int(attempt.id)}:r')
|
||||
db.session.refresh(attempt)
|
||||
assert int(attempt.job_id) == int(new_job_id)
|
||||
@@ -0,0 +1,371 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_service.py
|
||||
|
||||
用途:验证统一门禁领域服务的创建、状态机、指纹跳过、下游失效与 19 Gate 接线矩阵。
|
||||
依赖:Flask testing app、process_gate_service、process_gate_bridge、process_gate_contract。
|
||||
逻辑:最小 Workflow/Item/Version 夹具上创建 Execution;对每个 Gate 覆盖
|
||||
passed / blocked_manual / failed_terminal;断言指纹未变不重跑。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingNoticeWorkflow,
|
||||
ShippingNoticeWorkflowItem,
|
||||
ShippingNoticeWorkflowItemVersion,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
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') -> tuple[Any, Any, Any]:
|
||||
"""
|
||||
创建最小 User → Workflow → Item → Version 链。
|
||||
|
||||
Args:
|
||||
suffix: 用于编号去重的后缀。
|
||||
|
||||
Returns:
|
||||
(user, item, version)
|
||||
"""
|
||||
tag = str(suffix or '001')[:40]
|
||||
user = User(username=f'gate-svc-{tag}', email=f'gate-svc-{tag}@example.com', password_hash='x')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-GATE-{tag}',
|
||||
owner_user_id=int(user.id),
|
||||
original_filename='gate.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets',
|
||||
storage_key=f'temporary/{user.id}/gate-{tag}.pdf',
|
||||
content_hash=(tag.ljust(64, '0'))[:64],
|
||||
file_size=10,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no=f'SNI-GATE-{tag}',
|
||||
asset_id=int(asset.id),
|
||||
user_id=int(user.id),
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=int(intake.id),
|
||||
document_type='attachment',
|
||||
attachment_key='gate.pdf',
|
||||
filename='gate.pdf',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
content_hash=(f'h{tag}'.ljust(64, '1'))[:64],
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
workflow = ShippingNoticeWorkflow(
|
||||
workflow_no=f'WF-GATE-{tag}',
|
||||
conversation_id=f'conv-gate-{tag}',
|
||||
owner_user_id=int(user.id),
|
||||
status='open',
|
||||
current_stage='extracting',
|
||||
)
|
||||
db.session.add(workflow)
|
||||
db.session.flush()
|
||||
item = ShippingNoticeWorkflowItem(
|
||||
item_no=f'WFI-GATE-{tag}',
|
||||
workflow_id=int(workflow.id),
|
||||
workflow_no=workflow.workflow_no,
|
||||
conversation_id=f'conv-gate-{tag}',
|
||||
owner_user_id=int(user.id),
|
||||
root_document_id=int(document.id),
|
||||
current_document_id=int(document.id),
|
||||
lifecycle_status='extracting',
|
||||
current_stage='extracting',
|
||||
current_version_no=1,
|
||||
)
|
||||
db.session.add(item)
|
||||
db.session.flush()
|
||||
version = ShippingNoticeWorkflowItemVersion(
|
||||
workflow_item_id=int(item.id),
|
||||
item_no=item.item_no,
|
||||
workflow_id=int(workflow.id),
|
||||
workflow_no=workflow.workflow_no,
|
||||
document_id=int(document.id),
|
||||
version_no=1,
|
||||
status='active',
|
||||
is_current=True,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
item.current_version_id = int(version.id)
|
||||
db.session.flush()
|
||||
return user, item, version
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gate_execution(app):
|
||||
"""提供已初始化 19 Gate 的 Execution。"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version()
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
)
|
||||
db.session.commit()
|
||||
yield execution
|
||||
|
||||
|
||||
def test_ensure_execution_creates_nineteen_gates(gate_execution):
|
||||
"""创建 Execution 时必须初始化全部 19 个 Gate 行。"""
|
||||
gates = ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all()
|
||||
assert len(gates) == 19
|
||||
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):
|
||||
"""
|
||||
19 Gate 每个至少覆盖 passed、blocked_manual、failed_terminal 三类结果。
|
||||
|
||||
核心逻辑:同一 Execution 上对目标 Gate 依次同步三类 outcome。
|
||||
"""
|
||||
with app.app_context():
|
||||
_user, item, version = _seed_workflow_version(suffix=gate_code.replace('_', '')[:32])
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.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_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, item1, ver1 = _seed_workflow_version(suffix='idem-a')
|
||||
_u2, item2, ver2 = _seed_workflow_version(suffix='idem-b')
|
||||
exe1 = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item1.id),
|
||||
workflow_item_version_id=int(ver1.id),
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
)
|
||||
exe2 = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item2.id),
|
||||
workflow_item_version_id=int(ver2.id),
|
||||
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'
|
||||
Reference in new issue
Block a user