- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
307 lines
15 KiB
Python
307 lines
15 KiB
Python
"""
|
||
tests/api/test_freight_rpa_api.py
|
||
|
||
用途:/api/freight-rpa/* 回调蓝图的 HTTP 契约测试(批次 R Task 8 建立、Task 9 补 sink 注册后契约)。
|
||
依赖:tests/conftest.py 的 app/client fixture;freight_rpa.common.callback_sinks。
|
||
逻辑:锁定四条关键契约——① 心跳新路由鉴权必备;② 旧 shipping-notice rpa 回调前缀无双路由
|
||
(脏回调显式 404);③ 未注册 sink 的 kind 显式 404 且错误码 FREIGHT_RPA.SINK_NOT_REGISTERED
|
||
(分发层语义,用自造 kind 单测锁定);④ Task 9 组合根注册真实 sink 后,8 个 onhand 端点
|
||
的响应 envelope 与旧 shipping-notice rpa 回调端点逐 kind 逐字一致(禁止统一 envelope):
|
||
inventory-ready / batch-ready / batch-progress 返回裸业务 tool_response dict,
|
||
batch-claimed 返回 {'success':True,'data':...},configuration-test-* 返回 {'status':'ok','data':...};
|
||
⑤ Task 10 注册 inbound sink 后,3 个 inbound 端点维持 {'success':True,'data':...} 旧形态,
|
||
业务校验路径(400/404 错误码)与拆分前直连逐字一致。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
|
||
import pytest
|
||
|
||
|
||
TEST_TOOL_KEY = 'test-tool-key'
|
||
|
||
|
||
@pytest.fixture
|
||
def tool_auth_headers(app):
|
||
"""以测试 integration key 生成 Bearer 鉴权头(与生产 Worker 的 Bearer 形态一致)。"""
|
||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
|
||
return {'Authorization': f'Bearer {TEST_TOOL_KEY}'}
|
||
|
||
|
||
@pytest.fixture
|
||
def terminal_configuration_test_run(app):
|
||
"""预置一个已终态的配置测试运行 + 批次,供 configuration-test 三端点走 OK envelope 路径。"""
|
||
from app import db
|
||
from app.models import (
|
||
FreightRpaOnhandConfigurationTestRun,
|
||
FreightRpaSource,
|
||
FreightRpaOnhandValidationBatch,
|
||
)
|
||
|
||
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||
batch = FreightRpaOnhandValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1)
|
||
db.session.add(batch)
|
||
db.session.flush()
|
||
run = FreightRpaOnhandConfigurationTestRun(
|
||
run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, source_id=source.id,
|
||
source_config_version=source.config_version,
|
||
rpa_profile_config_version=source.rpa_profile.config_version,
|
||
status='completed', stage='current_profile_verified', result_json={},
|
||
completed_at=datetime.utcnow(),
|
||
)
|
||
db.session.add(run)
|
||
db.session.commit()
|
||
return {'batch_id': batch.id, 'run_no': run.run_no}
|
||
|
||
|
||
def test_heartbeat_requires_auth(client, app):
|
||
"""heartbeat 走新路由且鉴权必备:无 Header 必须 401,绝不能匿名写心跳。"""
|
||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
|
||
assert client.post("/api/freight-rpa/heartbeat", json={}).status_code == 401
|
||
|
||
|
||
def test_legacy_rpa_routes_removed(client):
|
||
"""旧路由已死(无兼容层,脏回调显式 404):旧 URL 不得再被任何蓝图接住。"""
|
||
assert client.post("/api/shipping-notice" + "/rpa/heartbeat", json={}).status_code == 404
|
||
|
||
|
||
def test_onhand_ready_registered_sink_returns_tool_envelope(client, tool_auth_headers):
|
||
"""Task 9 注册 sink 后 onhand-ready 可达:空载荷走业务失败分支,envelope 与旧
|
||
/rpa/inventory-ready 的裸 tool_response dict 逐字一致(status/message/data 顶层键)。"""
|
||
resp = client.post("/api/freight-rpa/onhand-ready", json={}, headers=tool_auth_headers)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
# [断言意图] 旧端点 = jsonify(rpa_report_inventory(payload)),tool_response 顶层键固定为
|
||
# status/message/data;失败文案必须保留旧值「未找到任务编号」。
|
||
assert set(body) == {"status", "message", "data"}
|
||
assert body["status"] == "failed"
|
||
assert body["message"] == "未找到任务编号"
|
||
assert body["data"] == {}
|
||
|
||
|
||
def test_unauthenticated_sink_endpoint_is_401_not_404(client, app):
|
||
"""鉴权先于分发:未携带 key 打 sink 端点是 401(未授权),不能泄漏 404 分发语义。"""
|
||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
|
||
assert client.post("/api/freight-rpa/onhand-ready", json={}).status_code == 401
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Task 9 envelope 逐 kind 契约:以 git HEAD 旧端点实现为基准写死期望 shape。
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def test_onhand_batch_ready_envelope_matches_legacy(client, tool_auth_headers):
|
||
"""onhand-batch-ready(旧 /rpa/inventory-batch-ready = jsonify(rpa_report_inventory(...))):
|
||
裸业务 dict;schema 非法分支 data 内 transport_status/business_status/error_code 三键。"""
|
||
resp = client.post("/api/freight-rpa/onhand-batch-ready", json={}, headers=tool_auth_headers)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
assert set(body) == {"status", "message", "data"}
|
||
assert body["status"] == "failed"
|
||
assert body["message"] == "callback_schema_invalid"
|
||
assert body["data"] == {
|
||
"transport_status": "invalid",
|
||
"business_status": "rejected",
|
||
"error_code": "callback_schema_invalid",
|
||
}
|
||
|
||
|
||
def test_onhand_batch_claimed_envelope_matches_legacy(client, tool_auth_headers):
|
||
"""onhand-batch-claimed(旧 /rpa/inventory-batch-claimed):
|
||
envelope = {'success': True, 'data': claim_inventory_batch(payload)},禁止裸 dict。"""
|
||
resp = client.post("/api/freight-rpa/onhand-batch-claimed", json={}, headers=tool_auth_headers)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
# [断言意图] 旧端点包裹 {'success': True, 'data': ...};schema 非法时业务层返回三键拒绝体。
|
||
assert set(body) == {"success", "data"}
|
||
assert body["success"] is True
|
||
assert body["data"] == {
|
||
"transport_status": "invalid",
|
||
"business_status": "rejected",
|
||
"error_code": "callback_schema_invalid",
|
||
}
|
||
|
||
|
||
def test_onhand_batch_progress_envelope_matches_legacy(client, tool_auth_headers):
|
||
"""onhand-batch-progress(旧 /rpa/inventory-batch-progress):
|
||
裸业务 dict;schema 非法分支 data.progress_status='invalid'。"""
|
||
resp = client.post("/api/freight-rpa/onhand-batch-progress", json={}, headers=tool_auth_headers)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
assert set(body) == {"status", "message", "data"}
|
||
assert body["status"] == "failed"
|
||
assert body["message"] == "callback_schema_invalid"
|
||
assert body["data"] == {
|
||
"progress_status": "invalid",
|
||
"error_code": "callback_schema_invalid",
|
||
}
|
||
|
||
|
||
def test_onhand_configuration_test_start_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
|
||
"""onhand-configuration-test-start(旧 /rpa/inventory-configuration-test-batch-progress =
|
||
report_batch_test_progress):envelope = {'status':'ok','data':测试运行投影}。"""
|
||
resp = client.post(
|
||
"/api/freight-rpa/onhand-configuration-test-start",
|
||
json={
|
||
'validation_batch_id': terminal_configuration_test_run['batch_id'],
|
||
'validation_run_no': terminal_configuration_test_run['run_no'],
|
||
},
|
||
headers=tool_auth_headers,
|
||
)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
# [断言意图] 旧端点 = jsonify({'status':'ok','data': report_batch_test_progress(...)});
|
||
# 终态 run 早退分支返回 _payload(run)(含 id/run_no/status)。
|
||
assert set(body) == {"status", "data"}
|
||
assert body["status"] == "ok"
|
||
assert body["data"]["run_no"] == terminal_configuration_test_run['run_no']
|
||
assert body["data"]["status"] == "completed"
|
||
|
||
|
||
def test_onhand_configuration_test_analyze_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
|
||
"""onhand-configuration-test-analyze(旧 /rpa/inventory-configuration-test-ready =
|
||
report_test_export):envelope = {'status':'ok','data':测试运行投影}。"""
|
||
resp = client.post(
|
||
"/api/freight-rpa/onhand-configuration-test-analyze",
|
||
json={'run_no': terminal_configuration_test_run['run_no']},
|
||
headers=tool_auth_headers,
|
||
)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
assert set(body) == {"status", "data"}
|
||
assert body["status"] == "ok"
|
||
assert body["data"]["run_no"] == terminal_configuration_test_run['run_no']
|
||
|
||
|
||
def test_onhand_configuration_test_complete_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
|
||
"""onhand-configuration-test-complete(旧 /rpa/inventory-configuration-test-batch-ready =
|
||
report_batch_test_exports):envelope = {'status':'ok','data':批次投影+updated/ignored 计数}。"""
|
||
resp = client.post(
|
||
"/api/freight-rpa/onhand-configuration-test-complete",
|
||
json={'validation_batch_id': terminal_configuration_test_run['batch_id'], 'results': []},
|
||
headers=tool_auth_headers,
|
||
)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
assert set(body) == {"status", "data"}
|
||
assert body["status"] == "ok"
|
||
assert body["data"]["updated_count"] == 0
|
||
assert body["data"]["ignored_count"] == 0
|
||
assert body["data"]["batch_no"] == "CONFIG-BATCH-ENV-TEST"
|
||
|
||
|
||
def test_onhand_repair_envelope_matches_legacy(client, tool_auth_headers):
|
||
"""onhand-repair(旧 /rpa/inventory-repair = repair=True 后 jsonify(rpa_report_inventory(...))):
|
||
裸业务 dict,schema 非法分支与 batch-ready 同形。"""
|
||
resp = client.post("/api/freight-rpa/onhand-repair", json={}, headers=tool_auth_headers)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
assert set(body) == {"status", "message", "data"}
|
||
assert body["status"] == "failed"
|
||
assert body["data"] == {
|
||
"transport_status": "invalid",
|
||
"business_status": "rejected",
|
||
"error_code": "callback_schema_invalid",
|
||
}
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Task 10 inbound sink 注册后契约:三端点改 dispatch_sink 后 envelope 与拆分前直连
|
||
# 形态(jsonify({'success': True, 'data': 业务结果}))逐字一致,禁止裸 dict / 统一 envelope。
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def test_inbound_unit_progress_envelope_matches_legacy(client, tool_auth_headers):
|
||
"""inbound-unit-progress(旧直连 jsonify({'success':True,'data':mark_inbound_unit_processing(p)})):
|
||
schema 非法分支 data={'updated':False,'reason':'callback_schema_invalid'},证明 sink 已注册
|
||
(未注册会是 404 FREIGHT_RPA.SINK_NOT_REGISTERED)且 envelope 未漂移。"""
|
||
resp = client.post("/api/freight-rpa/inbound-unit-progress", json={}, headers=tool_auth_headers)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
assert set(body) == {"success", "data"}
|
||
assert body["success"] is True
|
||
assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"}
|
||
|
||
|
||
def test_inbound_batch_progress_envelope_matches_legacy(client, tool_auth_headers):
|
||
"""inbound-batch-progress(旧直连同款 envelope):schema 非法分支与 unit-progress 同形。"""
|
||
resp = client.post("/api/freight-rpa/inbound-batch-progress", json={}, headers=tool_auth_headers)
|
||
assert resp.status_code == 200
|
||
body = resp.get_json()
|
||
assert set(body) == {"success", "data"}
|
||
assert body["success"] is True
|
||
assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"}
|
||
|
||
|
||
def test_inbound_batch_ready_schema_invalid_reaches_business_validation(client, tool_auth_headers):
|
||
"""inbound-batch-ready sink 已注册:schema 非法穿透到业务校验(400 +
|
||
SHIPPING.INBOUND_CALLBACK_INVALID),而非未注册 404;错误 envelope 与拆分前同形
|
||
(旧端点在 jsonify 之前由 ingest 抛 ValidationError → 全局 AppError handler)。"""
|
||
resp = client.post("/api/freight-rpa/inbound-batch-ready", json={}, headers=tool_auth_headers)
|
||
assert resp.status_code == 400
|
||
body = resp.get_json()
|
||
assert body["success"] is False
|
||
assert body["error"]["code"] == "SHIPPING.INBOUND_CALLBACK_INVALID"
|
||
|
||
|
||
def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers):
|
||
"""inbound-batch-ready 未知 callback_id:404 + SHIPPING.INBOUND_UNIT_NOT_FOUND,
|
||
与拆分前 ingest 直连时的 NotFoundError 路径逐字一致。"""
|
||
resp = client.post(
|
||
"/api/freight-rpa/inbound-batch-ready",
|
||
json={"schema_version": "freight_rpa.inbound.v1", "callback_id": "no-such-callback"},
|
||
headers=tool_auth_headers,
|
||
)
|
||
assert resp.status_code == 404
|
||
body = resp.get_json()
|
||
assert body["error"]["code"] == "SHIPPING.INBOUND_UNIT_NOT_FOUND"
|
||
|
||
|
||
@pytest.mark.pure_unit
|
||
def test_dispatch_sink_unregistered_raises_app_error():
|
||
"""注册表单测:未注册 kind 抛 AppError(404, FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。"""
|
||
from app.core.errors import AppError
|
||
from app.services.freight_rpa.common.callback_sinks import dispatch_sink, register_sink
|
||
|
||
seen: dict[str, object] = {}
|
||
|
||
def _handler(**payload):
|
||
seen.update(payload)
|
||
return {'ok': True}
|
||
|
||
register_sink('unit-test-kind', _handler)
|
||
assert dispatch_sink('unit-test-kind', callback_id='cb-1') == {'ok': True}
|
||
assert seen == {'callback_id': 'cb-1'}
|
||
|
||
with pytest.raises(AppError) as excinfo:
|
||
dispatch_sink('never-registered-kind', callback_id='cb-2')
|
||
assert excinfo.value.code == 'FREIGHT_RPA.SINK_NOT_REGISTERED'
|
||
assert excinfo.value.http_status == 404
|
||
|
||
|
||
def test_admin_rpa_profiles_routes_migrated(app, client):
|
||
"""admin rpa-profiles 已迁 /api/admin/freight-rpa/*:管理员可达、旧 URL 404、普通用户 403。"""
|
||
from app import db
|
||
from app.models import User
|
||
|
||
app.config['AUTH_JWT_REQUIRED'] = False
|
||
with app.app_context():
|
||
db.session.add_all([
|
||
User(username='rpa-admin', email='rpa-admin@example.com', role='admin', status='active'),
|
||
User(username='rpa-user', email='rpa-user@example.com', role='user', status='active'),
|
||
])
|
||
db.session.commit()
|
||
|
||
admin_headers = {'X-Username': 'rpa-admin', 'X-Role': 'admin'}
|
||
user_headers = {'X-Username': 'rpa-user', 'X-Role': 'user'}
|
||
|
||
migrated = client.get('/api/admin/freight-rpa/rpa-profiles', headers=admin_headers)
|
||
assert migrated.status_code == 200
|
||
assert migrated.get_json()['success'] is True
|
||
|
||
# [断言意图] 普通用户必须被 require_admin 拦截(迁移未放松权限)。
|
||
assert client.get('/api/admin/freight-rpa/rpa-profiles', headers=user_headers).status_code == 403
|
||
|
||
# [断言意图] 旧 admin URL 无双路由:脏调用显式 404(前端已同窗口切换)。
|
||
assert client.get('/api/admin/shipping-notice/rpa-profiles', headers=admin_headers).status_code == 404
|