Files
syops/backend/tests/test_shipping_process_gate_api.py
T

250 lines
10 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 unittest.mock import patch
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.order_extraction_plan import ensure_order_extraction_plan
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
from tests.test_shipping_order_extraction_runs import _seed_run_input
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):
"""
创建属主 Task + Execution,并将 order_freeze_readiness 置为 blocked_manual。
Args:
owner: 可选属主;非空时 Task 绑定该用户。
Returns:
(owner, execution, gate)
"""
suffix = f'api{owner.id if owner else "x"}'[:24]
user, _review_case_id, task_id = _seed_workflow_version(suffix=suffix, owner=owner)
execution = ensure_execution_for_workflow_version(
review_case_id=None,
task_id=task_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 _seed_blocked_execution_for_agent_readonly():
"""
创建带 ReviewCase 的 Execution,供同 Run.owner_agent 授权人员只读验收。
核心逻辑:ensure_run_review_cases 物化 Case → Execution 绑定 review_case_id。
Returns:
(owner, execution, gate, agent)
"""
user, agent, session, intake, _document = _seed_run_input(suffix='API-AGENT-GATE')
with patch(
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
return_value=True,
):
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
ensure_order_extraction_plan(run)
cases = ensure_run_review_cases(run=run)
assert cases, 'review case required for agent authorization path'
case = cases[0]
execution = ensure_execution_for_workflow_version(
review_case_id=int(case.id),
task_id=None,
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-agent-{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, agent
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, agent = _seed_blocked_execution_for_agent_readonly()
viewer = User(username='gate-api-viewer', email='gate-api-viewer@example.com', password_hash='x')
db.session.add(viewer)
db.session.flush()
viewer.agents = [agent]
db.session.commit()
execution_no = execution.execution_no
assert execution.review_case_id is not None
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}