Files
syops/backend/tests/test_shipping_process_gate_api.py
T
hugoandCursor 323928626b feat(shipping-process-gates): 落地全门禁中断恢复并消除双真相
纳入 Execution/Gate/Attempt 模型与迁移、Worker/API/前端恢复卡片与 Admin 诊断,
Gate 阻断时清零旧 action_buttons,异常摘要统一脱敏,并为运维筛选与 Attempt Diff 补齐入口。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:08:32 +08:00

209 lines
8.6 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_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}