Files
syops/backend/tests/test_shipping_process_gate_api.py
hugoandCursor 39fe3c05f2 feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与
枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa
持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀,
上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 10:46:06 +08:00

312 lines
13 KiB
Python
Raw Permalink 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()
# 夹具显式将阻断 Gate 设为 Execution.current_gate,覆盖前置 Gate 默认初始状态,
# 以便 API 测试验证当前 Gate 的统一写校验。
execution.current_gate_code = gate.gate_code
execution.primary_next_action_code = gate.next_action_code
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)
if not cases:
# 当前最小 API 夹具可能没有完整 Worker Candidate;仍创建只读授权所需的
# 正式 Case 绑定,测试只验证权限边界,不把缺失 Candidate 伪装成业务成功。
from app.models import ShippingOrderReviewCase
unit = run.extraction_plan.units[0] if run.extraction_plan and run.extraction_plan.units else None
if unit is not None and unit.document_id:
case = ShippingOrderReviewCase(
case_no=f'SORC-API-FALLBACK-{run.id}', run_id=int(run.id), unit_id=int(unit.id),
document_id=int(unit.document_id), owner_user_id=int(user.id), status='draft',
)
db.session.add(case)
db.session.flush()
cases = [case]
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_post_action_rejects_non_current_gate_for_all_gate_actions(app, client):
"""所有阶段统一禁止绕过 current_gate 写入其他 Gate。"""
with app.app_context():
owner, execution, gate = _seed_blocked_execution()
# order_freeze_readiness 是当前阻断;请求另一个正式 Gate 必须 fail-closed。
other_gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='onhand_matching',
).first()
assert other_gate is not None
resp = client.post(
f'/api/workspace/shipping-notice/process-executions/{execution.execution_no}'
'/gates/inventory_matching/actions',
headers=_auth_headers(owner),
json={
'action_code': 'open_onhand_match_review',
'expected_gate_version': int(other_gate.evaluation_version),
'idempotency_key': 'api-non-current-gate-1',
},
)
assert resp.status_code == 400
assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_NOT_CURRENT'
def test_workspace_post_action_rejects_terminal_execution_for_all_gate_actions(app, client):
"""所有阶段统一禁止 completed/cancelled Execution 写动作。"""
with app.app_context():
owner, execution, gate = _seed_blocked_execution()
execution.status = 'completed'
db.session.commit()
resp = client.post(
f'/api/workspace/shipping-notice/process-executions/{execution.execution_no}'
f'/gates/{gate.gate_code}/actions',
headers=_auth_headers(owner),
json={
'action_code': 'open_order_review',
'expected_gate_version': int(gate.evaluation_version),
'idempotency_key': 'api-terminal-execution-1',
},
)
assert resp.status_code == 400
assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_EXECUTION_TERMINAL'
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}