feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。 共享目录与 Worker 契约一次切换至 onhand/inbound/upload, 并补 outbound 骨架与 tt16 排程 job key 迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
bf3154033b
commit
ffc0d4a430
147 files changed
+4221
-2678
No files matched your search
@@ -0,0 +1,306 @@
|
||||
"""
|
||||
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 (
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryValidationBatch,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
batch = ShippingInventoryValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
run = ShippingInventoryConfigurationTestRun(
|
||||
run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, inventory_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_receipt_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.RECEIPT_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.RECEIPT_CALLBACK_INVALID"
|
||||
|
||||
|
||||
def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers):
|
||||
"""inbound-batch-ready 未知 callback_id:404 + SHIPPING.RECEIPT_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.RECEIPT_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
|
||||
@@ -94,11 +94,11 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_freight_upload_rpa_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat.assert_freight_upload_rpa_ready",
|
||||
lambda: None,
|
||||
)
|
||||
return
|
||||
@@ -111,10 +111,10 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
|
||||
from app.services.freight_rpa.common.worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
|
||||
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests
|
||||
|
||||
reset_rpa_worker_alert_state_for_tests()
|
||||
|
||||
@@ -475,10 +475,10 @@ def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
|
||||
|
||||
|
||||
def v2_inventory_batch_payload(payload: dict) -> dict:
|
||||
"""测试构造器:补齐冻结 shipping_inventory_rpa.v2 回调 envelope。"""
|
||||
"""测试构造器:补齐冻结 freight_rpa.onhand.v1 回调 envelope。"""
|
||||
body = dict(payload or {})
|
||||
run_no = str(body.get('batch_run_no') or body.get('run_no') or '').strip()
|
||||
body.setdefault('schema_version', 'shipping_inventory_rpa.v2')
|
||||
body.setdefault('schema_version', 'freight_rpa.onhand.v1')
|
||||
body.setdefault('callback_id', f'test-callback:{run_no or "unknown"}')
|
||||
body.setdefault('batch_run_no', run_no)
|
||||
return body
|
||||
@@ -498,7 +498,7 @@ def rpa_callback_payload(
|
||||
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
|
||||
source = get_database_inventory_source(source_code) or {}
|
||||
return {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": f"test-callback:{run_no}",
|
||||
"task_id": task.task_no,
|
||||
"status": status,
|
||||
|
||||
@@ -30,7 +30,7 @@ def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycl
|
||||
"""
|
||||
from app.services.in_transit_transfer import inbound_callback_bridge
|
||||
from app.services.schedule import queue_service
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat_alert
|
||||
from app.services.freight_rpa.common import worker_heartbeat_alert
|
||||
|
||||
calls: list[int] = []
|
||||
|
||||
@@ -42,7 +42,7 @@ def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycl
|
||||
return {"skipped": True, "reason": "test_stub"}
|
||||
|
||||
monkeypatch.setattr(inbound_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
|
||||
monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
|
||||
monkeypatch.setattr(worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
|
||||
monkeypatch.setattr(queue_service, "_worker_initialized", False)
|
||||
|
||||
assert prepare_schedule_queue() == 0
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""freight_rpa 包 import 边界适应度测试。
|
||||
|
||||
用途:锁死阶段 A 验收标准——freight_rpa 不寄生业务编排。
|
||||
依赖:app/services/freight_rpa 包、ast。
|
||||
逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败;
|
||||
白名单是 RPA 归档/凭据所需的两块业务工具(阶段 B 收敛为零)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa"
|
||||
|
||||
ALLOWED_SHIPPING_NOTICE = {
|
||||
"app.services.shipping_notice.audit_service",
|
||||
"app.services.shipping_notice.file_assets",
|
||||
}
|
||||
|
||||
|
||||
def _imported_modules(path: Path) -> set[str]:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
mods: set[str] = set()
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
mods.update(a.name for a in node.names)
|
||||
elif isinstance(node, ast.ImportFrom) and node.module:
|
||||
mods.add(node.module)
|
||||
return mods
|
||||
|
||||
|
||||
def test_freight_rpa_import_boundary():
|
||||
assert PKG.exists(), "freight_rpa 包不存在"
|
||||
violations: list[str] = []
|
||||
for py in PKG.rglob("*.py"):
|
||||
for mod in _imported_modules(py):
|
||||
if mod.startswith("app.services.shipping_notice") and mod not in ALLOWED_SHIPPING_NOTICE:
|
||||
violations.append(f"{py.name}: {mod}")
|
||||
assert not violations, "freight_rpa 违规 import:\n" + "\n".join(violations)
|
||||
+41
-41
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/tests/test_rpa_worker_heartbeat.py
|
||||
backend/tests/services/freight_rpa/test_worker_heartbeat.py
|
||||
|
||||
用途:货代库存/上传 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
|
||||
依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。
|
||||
依赖:freight_rpa.common.worker_heartbeat、shipping_notice_tools heartbeat 路由。
|
||||
逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配、货代上传就绪与 fail-fast 断言。
|
||||
"""
|
||||
|
||||
@@ -14,10 +14,10 @@ from typing import Any
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
FREIGHT_UPLOAD_CAPABILITY,
|
||||
INVENTORY_EXPORT_CAPABILITY,
|
||||
RECEIPT_EXPORT_CAPABILITY,
|
||||
ONHAND_EXPORT_CAPABILITY,
|
||||
INBOUND_EXPORT_CAPABILITY,
|
||||
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
@@ -53,7 +53,7 @@ def _heartbeat_payload(
|
||||
"worker_id": worker_id,
|
||||
"hostname": "WIN-RPA-HOST",
|
||||
"environment": environment or resolve_backend_rpa_environment(),
|
||||
"capabilities": capabilities or [INVENTORY_EXPORT_CAPABILITY],
|
||||
"capabilities": capabilities or [ONHAND_EXPORT_CAPABILITY],
|
||||
"status": "idle",
|
||||
"trigger_dir": trigger_dir,
|
||||
"drop_dir": str(trigger_dir).replace("triggers", "drop"),
|
||||
@@ -68,7 +68,7 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
@@ -133,7 +133,7 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
@@ -155,11 +155,11 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
|
||||
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_store_worker",
|
||||
lambda _worker: False,
|
||||
)
|
||||
|
||||
@@ -172,20 +172,20 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
|
||||
|
||||
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
||||
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
# 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch);
|
||||
# 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
@@ -205,8 +205,8 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path
|
||||
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
||||
"""收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。"""
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
@@ -217,7 +217,7 @@ def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path,
|
||||
trigger_dir = tmp_path / 'receipt_triggers'
|
||||
trigger_dir.mkdir()
|
||||
app.config['ENV_NAME'] = 'test'
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(trigger_dir)
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR'] = str(trigger_dir)
|
||||
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED'] = True
|
||||
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK'] = True
|
||||
app.config['FREIGHT_RPA_WORKER_MOCK'] = 'false'
|
||||
@@ -249,7 +249,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.time.time",
|
||||
"app.services.freight_rpa.common.worker_heartbeat.time.time",
|
||||
lambda: base_now + 120,
|
||||
)
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
@@ -258,7 +258,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
|
||||
|
||||
|
||||
def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
|
||||
"""POST /rpa/heartbeat 应写入心跳并返回 ok。"""
|
||||
"""POST /api/freight-rpa/heartbeat 应写入心跳并返回 ok(旧 shipping-notice 路由已删)。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
@@ -266,7 +266,7 @@ def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/rpa/heartbeat",
|
||||
"/api/freight-rpa/heartbeat",
|
||||
headers={"X-Integration-Key": "test-tool-key"},
|
||||
json=payload,
|
||||
)
|
||||
@@ -283,7 +283,7 @@ def test_rpa_heartbeat_api_rejects_missing_auth(client, app, tmp_path):
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post("/api/shipping-notice/rpa/heartbeat", json=payload)
|
||||
res = client.post("/api/freight-rpa/heartbeat", json=payload)
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
@@ -295,7 +295,7 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/rpa/heartbeat",
|
||||
"/api/freight-rpa/heartbeat",
|
||||
headers={"X-Integration-Key": "wrong-key"},
|
||||
json=payload,
|
||||
)
|
||||
@@ -306,9 +306,9 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
|
||||
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
@@ -326,7 +326,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
|
||||
schedule_no="SCH-HB-OFFLINE",
|
||||
name="货代库存每日导出",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
enabled=True,
|
||||
@@ -364,7 +364,7 @@ def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_pat
|
||||
raise ConnectionError("redis read failed")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
@@ -400,7 +400,7 @@ def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch)
|
||||
return bucket.get(key)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
@@ -417,13 +417,13 @@ def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch)
|
||||
|
||||
def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path):
|
||||
"""未显式配置 scope 时,可从 /mnt/hxops-rpa-* 挂载路径推导。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import shared_scope_id
|
||||
from app.services.freight_rpa.common.worker_heartbeat import shared_scope_id
|
||||
|
||||
trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
|
||||
trigger_dir.mkdir(parents=True)
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
assert shared_scope_id() == "hxops-rpa-test-data"
|
||||
@@ -457,7 +457,7 @@ def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app,
|
||||
_heartbeat_payload(
|
||||
trigger_dir=str(upload_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[INVENTORY_EXPORT_CAPABILITY],
|
||||
capabilities=[ONHAND_EXPORT_CAPABILITY],
|
||||
)
|
||||
)
|
||||
result = check_freight_upload_rpa_ready()
|
||||
@@ -474,7 +474,7 @@ def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
|
||||
_heartbeat_payload(
|
||||
trigger_dir=str(upload_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[INVENTORY_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
|
||||
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
|
||||
)
|
||||
)
|
||||
result = check_freight_upload_rpa_ready()
|
||||
@@ -483,7 +483,7 @@ def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
|
||||
|
||||
def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
|
||||
"""上传 fail-fast 须带 reasons,供建单前/触发时展示阻断原因。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
@@ -501,7 +501,7 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
|
||||
|
||||
def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
"""收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
check_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
serialize_rpa_worker_status,
|
||||
@@ -513,8 +513,8 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
inventory_trigger.mkdir(parents=True)
|
||||
_write_shared_sentinel(inventory_trigger, scope_id="hxops-rpa-test-data")
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(inventory_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(inventory_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
@@ -537,7 +537,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
worker_id="HOST-receipt",
|
||||
trigger_dir=str(receipt_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[RECEIPT_EXPORT_CAPABILITY],
|
||||
capabilities=[INBOUND_EXPORT_CAPABILITY],
|
||||
))
|
||||
without_sentinel = check_receipt_rpa_worker_ready()
|
||||
assert without_sentinel.ready is False
|
||||
@@ -547,8 +547,8 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
assert receipt_ready.ready is True
|
||||
assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"]
|
||||
|
||||
payload = serialize_rpa_worker_status(scope="receipt")
|
||||
assert payload["scope"] == "receipt"
|
||||
payload = serialize_rpa_worker_status(scope="inbound")
|
||||
assert payload["scope"] == "inbound"
|
||||
assert payload["ready"] is True
|
||||
assert payload["trigger_dir"] == str(receipt_trigger)
|
||||
assert [w["worker_id"] for w in payload["workers"]] == ["HOST-receipt"]
|
||||
@@ -556,7 +556,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
|
||||
def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path):
|
||||
"""未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
check_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
@@ -564,7 +564,7 @@ def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tm
|
||||
receipt_trigger = tmp_path / "receipt" / "triggers"
|
||||
receipt_trigger.mkdir(parents=True)
|
||||
app.config["ENV_NAME"] = "dev"
|
||||
app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = ""
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
@@ -577,7 +577,7 @@ def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tm
|
||||
worker_id="Hugo-30820",
|
||||
trigger_dir=str(receipt_trigger),
|
||||
shared_scope_id="",
|
||||
capabilities=[RECEIPT_EXPORT_CAPABILITY],
|
||||
capabilities=[INBOUND_EXPORT_CAPABILITY],
|
||||
))
|
||||
result = check_receipt_rpa_worker_ready()
|
||||
assert result.ready is True
|
||||
+23
-23
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/tests/test_rpa_worker_heartbeat_alert.py
|
||||
backend/tests/services/freight_rpa/test_worker_heartbeat_alert.py
|
||||
|
||||
用途:RPA Worker 心跳告警冷却、Redis/DB 不可用兜底与接收人回退单测。
|
||||
依赖:rpa_worker_heartbeat_alert、rpa_worker_heartbeat、models.AppSetting。
|
||||
依赖:freight_rpa.common.worker_heartbeat_alert、freight_rpa.common.worker_heartbeat、models.AppSetting。
|
||||
逻辑:验证 DB 权威读取、Redis 陈旧/空 DB 清理、并发 claim、企微失败可重试、恢复与 admin 回退。
|
||||
"""
|
||||
|
||||
@@ -17,7 +17,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import AppSetting, User
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import (
|
||||
_DB_ALERT_STATE_KEY,
|
||||
_STATUS_SENDING,
|
||||
_claim_alert_send_lock,
|
||||
@@ -32,7 +32,7 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
@@ -62,7 +62,7 @@ def test_alert_state_memory_fallback_when_redis_save_fails(app, monkeypatch):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
@@ -89,15 +89,15 @@ def test_storage_unavailable_alert_respects_memory_cooldown(app, tmp_path, monke
|
||||
raise ConnectionError("redis write failed")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
lambda **kwargs: send_calls.append(kwargs["title"]) or True,
|
||||
)
|
||||
|
||||
@@ -129,11 +129,11 @@ def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_capture_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
@@ -147,7 +147,7 @@ def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch):
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients
|
||||
|
||||
recipients = _alert_recipients()
|
||||
assert len(recipients) == 1
|
||||
@@ -170,7 +170,7 @@ def test_alert_state_persists_to_db_when_redis_unavailable(app, monkeypatch):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
@@ -191,7 +191,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
@@ -225,7 +225,7 @@ def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatc
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients
|
||||
|
||||
recipients = _alert_recipients()
|
||||
assert len(recipients) == 1
|
||||
@@ -242,11 +242,11 @@ def test_alert_wecom_send_failure_allows_retry_before_cooldown(app, tmp_path, mo
|
||||
return send_attempts["count"] >= 2
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_flaky_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
@@ -302,7 +302,7 @@ def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch)
|
||||
raise IntegrityError("INSERT", {}, Exception("duplicate key"))
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._claim_alert_send_lock_db",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._claim_alert_send_lock_db",
|
||||
_raise_integrity,
|
||||
)
|
||||
|
||||
@@ -342,11 +342,11 @@ def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_capture_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
@@ -359,7 +359,7 @@ def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
|
||||
)(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: type("BrokenRedis", (), {"get": lambda *_a, **_k: None, "set": lambda *_a, **_k: None, "delete": lambda *_a, **_k: None})(),
|
||||
)
|
||||
|
||||
@@ -404,7 +404,7 @@ def test_load_alert_state_prefers_db_over_stale_redis(app, monkeypatch):
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
@@ -448,7 +448,7 @@ def test_load_alert_state_overwrites_newer_stale_redis_from_db(app, monkeypatch)
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
@@ -488,7 +488,7 @@ def test_load_alert_state_clears_stale_redis_when_db_has_no_row(app, monkeypatch
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
@@ -62,7 +62,7 @@ def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
|
||||
]
|
||||
assert calls['units'][0]['credential_envelope']
|
||||
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert calls['payload']['schema_version'] == 'freight_rpa.inbound.v1'
|
||||
|
||||
|
||||
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
|
||||
@@ -139,27 +139,28 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
inventory_source_id=receipt_source.id).one()
|
||||
_bind_published_inbound_profile(config)
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到 inbound_export_batch_*.json
|
||||
# (批次 R 自 receipt_export_batch_* 改名,旧 glob 会把已写入的文件判成没写)。
|
||||
assert list(tmp_path.glob("inbound_export_batch_*.json")), "trigger file not written"
|
||||
|
||||
|
||||
def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""收料配置存在但未绑已发布 inbound 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
|
||||
)
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 inbound trigger 文件。
|
||||
assert outcome["ok"] is False
|
||||
assert outcome["error_code"] == "RPA_INBOUND_PROFILE_MISSING"
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
|
||||
assert list(tmp_path.glob("inbound_export_batch_*.json")) == []
|
||||
|
||||
|
||||
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
@@ -233,7 +234,7 @@ def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt
|
||||
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
|
||||
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
|
||||
assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert calls[0]['payload']['schema_version'] == 'freight_rpa.inbound.v1'
|
||||
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
|
||||
callback_ids = {u['callback_id'] for u in calls[0]['units']}
|
||||
assert len(callback_ids) == 2
|
||||
|
||||
@@ -229,10 +229,10 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
db.session.add(ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code,
|
||||
|
||||
@@ -46,7 +46,7 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p
|
||||
)
|
||||
schedule_task = ScheduleTask(
|
||||
schedule_no='SCH-INVENTORY-FAILED', name='Inventory Export', schedule_type='platform_job',
|
||||
owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='shipping-inventory-rpa',
|
||||
owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='freight-rpa-onhand',
|
||||
)
|
||||
db.session.add_all([file_record, schedule_task])
|
||||
db.session.flush()
|
||||
@@ -139,7 +139,7 @@ def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app
|
||||
|
||||
|
||||
def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_missing_steps(app, client):
|
||||
"""管理端普通保存不允许跳过测试直接启用,独立启用接口应返回业务缺失项。"""
|
||||
"""管理端普通保存不允许直接启用;独立启用接口只返回硬门槛缺失项,不含配置测试。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
@@ -166,7 +166,9 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
|
||||
assert created.status_code == 201
|
||||
source = parse_api_data(created.get_json())
|
||||
assert source['enabled'] is False
|
||||
assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
|
||||
# 关键断言:配置测试已退出启用门禁,缺失项只剩解析方案与发货模板。
|
||||
assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
assert 'configuration_test' not in {item['code'] for item in source['activation']['checks']}
|
||||
|
||||
activation = client.post(
|
||||
f"/api/admin/shipping-notice/sources/{source['id']}/activate",
|
||||
@@ -175,7 +177,7 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
|
||||
assert activation.status_code == 409
|
||||
error = parse_api_error(activation.get_json())
|
||||
assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
|
||||
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
|
||||
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
|
||||
|
||||
def test_latest_inventory_configuration_test_is_admin_only(app, client):
|
||||
|
||||
@@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
|
||||
|
||||
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
|
||||
"""batch 内 session 有效时不应重复 goto + login。"""
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
|
||||
assert spec and spec.loader
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -18,7 +18,7 @@ def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client,
|
||||
other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -47,8 +47,8 @@ def test_receipt_recipient_lists_only_own_archived_files(app, client):
|
||||
other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
@@ -82,8 +82,8 @@ def test_receipt_file_list_filters_before_applying_limit(app):
|
||||
other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
@@ -113,7 +113,7 @@ def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
|
||||
admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id])
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -123,7 +123,7 @@ def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
|
||||
db.session.add(report_file); db.session.commit()
|
||||
file_id = report_file.id
|
||||
calls = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.deliver_receipt_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0})
|
||||
monkeypatch.setattr('app.api.schedule.runs.deliver_inbound_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0})
|
||||
|
||||
response = client.post(f'/api/admin/receipt-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
@@ -140,7 +140,7 @@ def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, clien
|
||||
admin = User(username='receipt-retry-admin', email='receipt-retry-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RETRY', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -148,7 +148,7 @@ def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, clien
|
||||
db.session.add(failed); db.session.commit()
|
||||
failed_id = failed.id
|
||||
captured = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
|
||||
monkeypatch.setattr('app.api.schedule.runs.write_inbound_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
|
||||
|
||||
response = client.post(f'/api/admin/receipt-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
@@ -169,7 +169,7 @@ def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client):
|
||||
admin = User(username='receipt-units-admin', email='receipt-units-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
|
||||
@@ -11,7 +11,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
"""开始导出标记 processing;每笔完成后 batch-progress 抬升排程计数。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import (
|
||||
mark_receipt_unit_processing,
|
||||
report_receipt_batch_progress,
|
||||
)
|
||||
@@ -20,7 +20,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-LIVE', name='Receipt live progress', schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -40,7 +40,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
db.session.commit()
|
||||
|
||||
marked = mark_receipt_unit_processing({
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.callback_id,
|
||||
'status': 'processing',
|
||||
})
|
||||
@@ -49,7 +49,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
assert db.session.get(ShippingReceiptRpaUnitRun, unit.id).status == 'processing'
|
||||
|
||||
progressed = report_receipt_batch_progress({
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'schedule_run_id': run.id,
|
||||
'batch_run_no': run.run_no,
|
||||
'success_count': 1,
|
||||
@@ -73,7 +73,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-PROG', name='Receipt progress', schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -92,15 +92,15 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file',
|
||||
'app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file',
|
||||
lambda _path: b'receipt-bytes',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes',
|
||||
'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
payload = {
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.callback_id,
|
||||
'status': 'success',
|
||||
'file_path': 'Z:/receipt.xlsx',
|
||||
@@ -122,15 +122,15 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch)
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
first = ingest_receipt_callback(payload)
|
||||
second = ingest_receipt_callback(payload)
|
||||
assert first['file_id'] == second['file_id']
|
||||
@@ -145,7 +145,7 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB2', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -155,9 +155,9 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
|
||||
db.session.add(transfer_run); db.session.flush()
|
||||
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
|
||||
db.session.add(job); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
# [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id
|
||||
@@ -175,7 +175,7 @@ def test_ingest_failed_advance_is_durable(app):
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB3', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -185,7 +185,7 @@ def test_ingest_failed_advance_is_durable(app):
|
||||
db.session.add(transfer_run); db.session.flush()
|
||||
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
|
||||
db.session.add(job); db.session.commit()
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
assert result['status'] == 'failed'
|
||||
@@ -201,17 +201,17 @@ def test_ingest_failed_advance_is_durable(app):
|
||||
def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
|
||||
"""Callback cannot read arbitrary local xlsx files outside the receipt-only drop root."""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file
|
||||
from app.services.freight_rpa.inbound.report_archive import _read_inbound_callback_file
|
||||
|
||||
with app.app_context():
|
||||
allowed_root = tmp_path / 'receipt-drop'
|
||||
allowed_root.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_DROP_DIR'] = str(allowed_root)
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'not-a-real-xlsx')
|
||||
|
||||
with pytest.raises(ValidationError, match='receipt callback file'):
|
||||
_read_receipt_callback_file(str(outside))
|
||||
_read_inbound_callback_file(str(outside))
|
||||
|
||||
|
||||
def test_ingest_empty_persists_no_receipt_data(app):
|
||||
@@ -230,7 +230,7 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
schedule_no='SCH-RECEIPT-EMPTY',
|
||||
name='Receipt empty',
|
||||
schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa',
|
||||
platform_api_path='freight-rpa-inbound',
|
||||
owner_user_id=1,
|
||||
cron_expr='0 8 * * *',
|
||||
)
|
||||
@@ -253,7 +253,7 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
db.session.commit()
|
||||
|
||||
result = ingest_receipt_callback({
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.callback_id,
|
||||
'status': 'empty',
|
||||
'error_code': 'no_receipt_data',
|
||||
@@ -269,19 +269,21 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
|
||||
|
||||
def test_receipt_progress_routes_are_registered(app):
|
||||
"""回归锁:receipt-unit-progress / receipt-batch-progress 必须注册在 Tool 蓝图上。
|
||||
"""回归锁:inbound-unit-progress / inbound-batch-progress 必须注册在 freight-rpa 蓝图上。
|
||||
|
||||
2026-10-08 事故:重构分叉合并丢失两路由,Worker 上报全程 404、活动锚失效、
|
||||
在飞批次被超时对账误杀——本用例保证路由缺失在任何部署前即红。
|
||||
(批次 R:路由自旧 shipping-notice rpa 回调前缀迁至 /api/freight-rpa/inbound-*,
|
||||
处理函数不变,本回归锁同步改指新 URL。)
|
||||
"""
|
||||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = 'test-tool-key'
|
||||
client = app.test_client()
|
||||
headers = {'X-Integration-Key': 'test-tool-key'}
|
||||
for path, payload in (
|
||||
('/api/shipping-notice/rpa/receipt-unit-progress',
|
||||
{'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': 'no-such-callback'}),
|
||||
('/api/shipping-notice/rpa/receipt-batch-progress',
|
||||
{'schema_version': 'shipping_receipt_rpa.v1', 'schedule_run_id': 999999999}),
|
||||
('/api/freight-rpa/inbound-unit-progress',
|
||||
{'schema_version': 'freight_rpa.inbound.v1', 'callback_id': 'no-such-callback'}),
|
||||
('/api/freight-rpa/inbound-batch-progress',
|
||||
{'schema_version': 'freight_rpa.inbound.v1', 'schedule_run_id': 999999999}),
|
||||
):
|
||||
# [断言意图] 路由必须存在且鉴权通过(非 401/403/404);无匹配数据时服务层
|
||||
# 返回 200 + updated=False(注册性探针,不依赖任何夹具数据)。
|
||||
@@ -293,22 +295,22 @@ def test_receipt_progress_routes_are_registered(app):
|
||||
def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path):
|
||||
"""跨机路径契约:Worker 只上报文件名(或历史 Windows 绝对路径),后端按自身 drop 根定位。"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file
|
||||
from app.services.freight_rpa.inbound.report_archive import _read_inbound_callback_file
|
||||
|
||||
with app.app_context():
|
||||
drop_root = tmp_path / 'receipt-drop'
|
||||
drop_root.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(drop_root)
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_DROP_DIR'] = str(drop_root)
|
||||
target = drop_root / 'receipt_RUN_X_SITE_NA_2026.xlsx'
|
||||
target.write_bytes(b'receipt-bytes')
|
||||
|
||||
# [断言意图] 裸文件名(新 Worker 契约)与 Windows 本机绝对路径(历史载荷)都
|
||||
# 必须解析到后端 drop 根内同一文件;根外文件依旧拒绝(任意本机文件读取护栏不变)。
|
||||
assert _read_receipt_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes'
|
||||
assert _read_receipt_callback_file(
|
||||
assert _read_inbound_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes'
|
||||
assert _read_inbound_callback_file(
|
||||
r'C:\HxopsRpaTest\data\freight_rpa\receipt\drop\receipt_RUN_X_SITE_NA_2026.xlsx'
|
||||
) == b'receipt-bytes'
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'x')
|
||||
with pytest.raises(ValidationError, match='receipt callback file'):
|
||||
_read_receipt_callback_file(str(outside))
|
||||
_read_inbound_callback_file(str(outside))
|
||||
@@ -10,13 +10,13 @@ def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipient
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-recipient', email='recipient@example.com', role='user', status='active', wecom_userid='receipt-user')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -24,13 +24,13 @@ def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipient
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.upload_wecom_temp_media', lambda *_args: 'media-1')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.upload_wecom_temp_media', lambda *_args: 'media-1')
|
||||
calls: list[tuple] = []
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0})
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0})
|
||||
|
||||
assert deliver_receipt_file(report_file.id)['success_count'] == 1
|
||||
assert deliver_receipt_file(report_file.id)['success_count'] == 1
|
||||
assert deliver_inbound_file(report_file.id)['success_count'] == 1
|
||||
assert deliver_inbound_file(report_file.id)['success_count'] == 1
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@@ -41,13 +41,13 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-unbound-recipient', email='receipt-unbound@example.com', role='user', status='active')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY-FAIL', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -56,7 +56,7 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
|
||||
outcome = deliver_receipt_file(report_file.id)
|
||||
outcome = deliver_inbound_file(report_file.id)
|
||||
|
||||
assert outcome['failed_count'] == 1
|
||||
audit = ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_file_notification_attempted', aggregate_id=str(report_file.id)).one()
|
||||
@@ -73,7 +73,7 @@ def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True} if awaiting else None)
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -115,10 +115,10 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
|
||||
"""收料 run 终态后经通用排程出口一次性发 textcard+收料 ZIP;重复归集不重发。"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives')
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives')
|
||||
recipient = User(username='receipt-one-shot', email='one-shot@example.com', role='user', status='active', wecom_userid='one-shot-user')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
task, run, _report_file = _make_receipt_run_fixture(db, 'SCH-RECEIPT-ONESHOT', 'RUN-RECEIPT-ONESHOT', 'receipt-oneshot-callback')
|
||||
@@ -160,12 +160,12 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path):
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
|
||||
@@ -9,7 +9,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
"""一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
|
||||
|
||||
with app.app_context():
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
@@ -53,7 +53,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
])
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
job_params={'source_codes': [dbs.source_code, crane.source_code, empty_dbs.source_code]},
|
||||
)
|
||||
db.session.add(task); db.session.flush()
|
||||
@@ -62,7 +62,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger',
|
||||
'app.services.schedule.freight_inbound_rpa_job.write_inbound_export_batch_trigger',
|
||||
lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json',
|
||||
)
|
||||
total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run)
|
||||
@@ -71,7 +71,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
assert (total, success, failed, skipped, errors) == (3, 0, 0, 0, [])
|
||||
assert {item['source_code'] for item in details} == {dbs.source_code, crane.source_code, empty_dbs.source_code}
|
||||
assert all(item['warehouse_id'] is None for item in details)
|
||||
assert captured['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert captured['payload']['schema_version'] == 'freight_rpa.inbound.v1'
|
||||
assert len(captured['units']) == 3
|
||||
dbs_unit = next(item for item in captured['units'] if item['source_code'] == dbs.source_code)
|
||||
assert dbs_unit['rpa_profile_code'] == 'DBS_DUB_TEST'
|
||||
@@ -95,8 +95,8 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
@@ -110,7 +110,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
))
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-OFFLINE', name='Receipt offline', schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
job_params={'source_codes': [source.source_code]},
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -121,7 +121,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
|
||||
trigger_calls = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_receipt_rpa_job.assert_receipt_rpa_worker_ready',
|
||||
'app.services.schedule.freight_inbound_rpa_job.assert_receipt_rpa_worker_ready',
|
||||
lambda: (_ for _ in ()).throw(ServiceUnavailableError(
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
code='RPA.WORKER_OFFLINE',
|
||||
@@ -129,7 +129,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger',
|
||||
'app.services.schedule.freight_inbound_rpa_job.write_inbound_export_batch_trigger',
|
||||
lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json',
|
||||
)
|
||||
|
||||
@@ -173,12 +173,12 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
"""无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -197,13 +197,13 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
|
||||
def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
||||
"""Worker 只能观察到完整 JSON;临时写入文件不会匹配其 *.json 扫描。"""
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.freight_rpa.inbound.trigger_io import write_inbound_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
|
||||
path = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'c1'}], {})
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR'] = str(tmp_path)
|
||||
path = write_inbound_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'c1'}], {})
|
||||
assert path
|
||||
assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').exists()
|
||||
assert (tmp_path / 'inbound_export_batch_RUN-ATOMIC.json').exists()
|
||||
assert not list(tmp_path.glob('.*.tmp'))
|
||||
|
||||
|
||||
@@ -211,12 +211,12 @@ def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app):
|
||||
"""全量扫描(每轮 tick 路径)无需任务再次执行/进程重启即可收口超时收料 run。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -235,12 +235,12 @@ def test_receipt_recovery_respects_fresh_activity_of_long_batch(app):
|
||||
"""长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -274,10 +274,10 @@ def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
|
||||
"""按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。"""
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
# 单元1:排队 5 分钟从未被领取(created_at 为锚,queued 分支);单元2:领取后
|
||||
# 静默 5 分钟(started_at 为锚);单元3:30 秒前刚领取(健康在跑,不得误杀)。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""独立收料 Worker 静态契约。"""
|
||||
"""独立 inbound(原收料)Worker 静态契约。"""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
@@ -6,22 +6,23 @@ from pathlib import Path
|
||||
|
||||
|
||||
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
|
||||
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
assert 'shipping_receipt_rpa.v1' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-batch-ready' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-batch-progress' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-unit-progress' in text
|
||||
"""inbound Worker 只消费 freight_rpa.inbound.v1 trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR' in text
|
||||
assert 'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR' in text
|
||||
assert 'freight_rpa.inbound.v1' in text
|
||||
assert "from rpa_callbacks import" in text
|
||||
assert 'INBOUND_BATCH_READY' in text
|
||||
assert 'INBOUND_BATCH_PROGRESS' in text
|
||||
assert 'INBOUND_UNIT_PROGRESS' in text
|
||||
assert 'freight_rpa_worker' not in text
|
||||
assert 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
|
||||
assert 'FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR' not in text
|
||||
|
||||
|
||||
def test_receipt_dbs_export_does_not_require_warehouse_id():
|
||||
"""空条件允许走页面默认:Worker 不得因缺少 warehouse_id 直接失败。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_dbs_export.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_dbs_export.py'
|
||||
).read_text(encoding='utf-8')
|
||||
# 关键断言:历史必填门禁已移除;仅在 warehouse_id 有值时追加(兼容旧 trigger)。
|
||||
assert 'DBS receipt unit requires warehouse_id' not in text
|
||||
@@ -31,7 +32,7 @@ def test_receipt_dbs_export_does_not_require_warehouse_id():
|
||||
def test_receipt_dbs_export_maps_report_path_to_navigation():
|
||||
"""收料路径必须写入 navigation,避免共享导出驱动回退到库存报表名。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_dbs_export.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_dbs_export.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert "'navigation': report_path" in text
|
||||
assert "report_path = dict(unit.get('report_path_json') or {})" in text
|
||||
@@ -39,9 +40,9 @@ def test_receipt_dbs_export_maps_report_path_to_navigation():
|
||||
|
||||
def test_receipt_dbs_batch_reuses_inventory_session_prepare():
|
||||
"""DBS 收料批内必须复用库存 prepare_dsv_batch_export_step,禁止每源 new_page。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt'
|
||||
worker = (root / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
export = (root / 'receipt_dbs_export.py').read_text(encoding='utf-8')
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound'
|
||||
worker = (root / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
export = (root / 'inbound_dbs_export.py').read_text(encoding='utf-8')
|
||||
# 关键断言:与库存同构的批内会话准备;不得再写 first_in_profile / 按 index 新开空白页。
|
||||
assert 'prepare_dsv_batch_export_step' in worker
|
||||
assert 'skip_navigation' in worker and 'skip_navigation' in export
|
||||
@@ -51,12 +52,12 @@ def test_receipt_dbs_batch_reuses_inventory_session_prepare():
|
||||
|
||||
def test_receipt_worker_download_name_uses_source_not_callback():
|
||||
"""落盘名必须含 source_code,禁止用 callback_id 拼文件名(对齐库存 batch 命名)。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt'
|
||||
worker = (root / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound'
|
||||
worker = (root / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
# 关键断言:命名函数与 source/run 字段存在;不再用 safe_callback 拼 receipt_ 文件名。
|
||||
assert 'def _receipt_download_name(' in worker
|
||||
assert 'def _inbound_download_name(' in worker
|
||||
assert 'batch_run_no' in worker
|
||||
assert "f'receipt_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'" in worker
|
||||
assert "f'inbound_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'" in worker
|
||||
assert 'safe_callback' not in worker
|
||||
assert "receipt_{safe_callback}" not in worker
|
||||
|
||||
@@ -64,7 +65,7 @@ def test_receipt_worker_download_name_uses_source_not_callback():
|
||||
def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8')
|
||||
receipt_driver = (root / 'inbound' / 'inbound_crane_export.py').read_text(encoding='utf-8')
|
||||
crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8')
|
||||
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
|
||||
assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver
|
||||
@@ -73,7 +74,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
def test_receipt_crane_export_passes_download_dir_for_fallback():
|
||||
"""Crane 收料 source 必须带 __download_dir,否则共享 driver 目录兜底不会启用。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_crane_export.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_crane_export.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert "'__download_dir': str(unit.get('__download_dir') or '')" in text
|
||||
|
||||
@@ -81,7 +82,7 @@ def test_receipt_crane_export_passes_download_dir_for_fallback():
|
||||
def test_receipt_worker_save_download_uses_directory_fallback():
|
||||
"""收料落盘必须在 TargetClosed 时走 download_artifact_fallback(对齐库存)。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'download_artifact_fallback' in text
|
||||
assert 'def _persist_download_to_dest(' in text
|
||||
@@ -92,20 +93,20 @@ def test_receipt_worker_save_download_uses_directory_fallback():
|
||||
def test_receipt_worker_validates_excel_and_reports_empty():
|
||||
"""收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_receipt_data。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
|
||||
).read_text(encoding='utf-8')
|
||||
empty_mod = (
|
||||
Path(__file__).resolve().parents[2]
|
||||
/ 'scripts'
|
||||
/ 'freight_rpa'
|
||||
/ 'receipt'
|
||||
/ 'receipt_excel_empty.py'
|
||||
/ 'inbound'
|
||||
/ 'inbound_excel_empty.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'def _validate_receipt_excel(' in text
|
||||
assert 'from receipt_excel_empty import' in text
|
||||
assert 'class NoReceiptDataError' in empty_mod
|
||||
assert 'def _validate_inbound_excel(' in text
|
||||
assert 'from inbound_excel_empty import' in text
|
||||
assert 'class NoInboundDataError' in empty_mod
|
||||
assert 'no_receipt_data' in empty_mod
|
||||
assert 'is_receipt_excel_header_row' in empty_mod
|
||||
assert 'is_inbound_excel_header_row' in empty_mod
|
||||
assert "'error_code': 'no_receipt_data'" in text
|
||||
assert "_post_callback({" in text and "'status': 'empty'" in text
|
||||
assert '_EXPORT_UNIT_MAX_ATTEMPTS = 2' in text
|
||||
@@ -120,7 +121,7 @@ def test_receipt_ready_callback_outside_export_retry_like_inventory_progress():
|
||||
_post_unit_ready / batch-progress 放在导出循环外,并禁止 ready 失败再导。
|
||||
"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'def _post_unit_ready(' in text
|
||||
assert '重试只覆盖导出/落盘/校验' in text or 'ready 回调禁止进入本循环' in text
|
||||
@@ -133,18 +134,18 @@ def test_receipt_ready_callback_outside_export_retry_like_inventory_progress():
|
||||
|
||||
|
||||
def test_receipt_heartbeat_capability_is_receipt_export():
|
||||
"""收料 Worker 心跳能力必须声明 receipt_export,不得再写 inventory_export。"""
|
||||
"""inbound Worker 心跳能力必须声明 inbound_export,不得再写 onhand_export。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'common' / 'rpa_heartbeat.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'receipt_export' in text
|
||||
assert 'is_receipt' in text
|
||||
assert 'inbound_export' in text
|
||||
assert 'is_inbound' in text
|
||||
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
module_path = root / 'receipt' / 'receipt_crane_export.py'
|
||||
module_path = root / 'inbound' / 'inbound_crane_export.py'
|
||||
sys.path.insert(0, str(root))
|
||||
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
|
||||
assert spec and spec.loader
|
||||
@@ -161,7 +162,7 @@ def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
|
||||
def test_receipt_worker_uses_common_trigger_consumer():
|
||||
"""收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'claim_trigger' in text
|
||||
assert 'archive_trigger' in text
|
||||
assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块
|
||||
@@ -169,47 +170,47 @@ def test_receipt_worker_uses_common_trigger_consumer():
|
||||
|
||||
def test_receipt_worker_logs_full_lifecycle_and_banner():
|
||||
"""收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'configure_file_logging' in text
|
||||
assert 'maybe_rotate_open_log' in text
|
||||
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段
|
||||
assert '[receipt-unit] success' in text # 成功单元留痕(此前成功路径零输出)
|
||||
assert '[receipt-unit] failed' in text
|
||||
assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text
|
||||
assert '[inbound-unit] success' in text # 成功单元留痕(此前成功路径零输出)
|
||||
assert '[inbound-unit] failed' in text
|
||||
assert '[inbound-trigger] claimed' in text and '[inbound-trigger] archived' in text
|
||||
|
||||
|
||||
def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
|
||||
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'start_inbound_worker.ps1').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-inbound' in ps1
|
||||
|
||||
|
||||
def test_receipt_register_script_mirrors_inventory_with_distinct_identity():
|
||||
"""收料计划任务注册脚本与库存同构(AtLogOn+Interactive+headless),任务名独立可同机并存。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
receipt = (root / 'receipt' / 'register_receipt_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
inventory = (root / 'inventory' / 'register_inventory_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
receipt = (root / 'inbound' / 'register_inbound_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
inventory = (root / 'onhand' / 'register_onhand_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
# [断言意图] 任务名赋值行必须指向 Receipt;docstring 允许提及库存任务名(并排设计说明),功能段不得引用
|
||||
assert '$TestTask = "HXOPS Receipt RPA Worker TEST"' in receipt
|
||||
assert '$ProdTask = "HXOPS Receipt RPA Worker PROD"' in receipt
|
||||
assert 'HXOPS Inventory RPA Worker TEST' in inventory and 'HXOPS Receipt RPA Worker' not in inventory
|
||||
assert '$TestTask = "HXOPS Freight Inbound RPA Worker TEST"' in receipt
|
||||
assert '$ProdTask = "HXOPS Freight Inbound RPA Worker PROD"' in receipt
|
||||
assert 'HXOPS Freight Onhand RPA Worker TEST' in inventory and 'HXOPS Freight Inbound RPA Worker' not in inventory
|
||||
# [断言意图] 动作必须指向收料启动脚本,且不得把库存启动脚本带进收料注册
|
||||
assert 'start_receipt_worker.ps1' in receipt and 'start_inventory_worker.ps1' not in receipt
|
||||
assert 'start_inbound_worker.ps1' in receipt and 'start_onhand_worker.ps1' not in receipt
|
||||
# [断言意图] 形状约束与库存同款:AtLogOn + Interactive + headless + 隐藏控制台
|
||||
assert 'AtLogOn' in receipt and 'Interactive' in receipt and 'Headless' in receipt and 'WindowStyle Hidden' in receipt
|
||||
|
||||
|
||||
def test_receipt_worker_defaults_session_reuse_with_scoped_profiles():
|
||||
"""收料默认会话复用,且持久目录按 connector+profile 隔离(对齐库存)。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
# [断言意图] 默认开启复用;持久目录形如 connector__profile_session,禁止单一 receipt_session
|
||||
assert 'def _session_reuse_enabled()' in text
|
||||
assert "f'{connector}__{code}_session'" in text or 'f"{connector}__{code}_session"' in text
|
||||
assert "profile_root / 'receipt_session'" not in text
|
||||
assert 'receipt-batch-progress' in text
|
||||
assert 'receipt-unit-progress' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
|
||||
assert 'INBOUND_BATCH_PROGRESS' in text
|
||||
assert 'INBOUND_UNIT_PROGRESS' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'start_inbound_worker.ps1').read_text(encoding='utf-8')
|
||||
assert '[switch]$NoSessionReuse' in ps1
|
||||
assert "FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse" in ps1
|
||||
@@ -27,24 +27,24 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_ID", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
payload = module.build_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\inventory_drop",
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\onhand_triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\onhand_drop",
|
||||
)
|
||||
assert payload["shared_scope_id"] == "hxops-rpa-test-data"
|
||||
assert payload["trigger_dir"] == r"C:\HxopsRpaTest\data\inventory_triggers"
|
||||
assert payload["capabilities"] == ["inventory_export"]
|
||||
assert payload["trigger_dir"] == r"C:\HxopsRpaTest\data\onhand_triggers"
|
||||
assert payload["capabilities"] == ["onhand_export"]
|
||||
|
||||
|
||||
def test_build_heartbeat_payload_receipt_worker_declares_receipt_export(monkeypatch):
|
||||
"""收料 Worker(*-receipt 或 receipt trigger 路径)须声明 receipt_export。"""
|
||||
def test_build_heartbeat_payload_inbound_worker_declares_inbound_export(monkeypatch):
|
||||
"""inbound Worker(*-inbound 或 inbound trigger 路径)须声明 inbound_export。"""
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ID", "WIN-RPA-01-receipt")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ID", "WIN-RPA-01-inbound")
|
||||
payload = module.build_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\freight_rpa\receipt\triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\freight_rpa\receipt\drop",
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\freight_rpa\inbound\triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\freight_rpa\inbound\drop",
|
||||
)
|
||||
assert payload["capabilities"] == ["receipt_export"]
|
||||
assert payload["worker_id"].endswith("-receipt")
|
||||
assert payload["capabilities"] == ["inbound_export"]
|
||||
assert payload["worker_id"].endswith("-inbound")
|
||||
|
||||
|
||||
def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
@@ -52,13 +52,13 @@ def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.setenv(
|
||||
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
"FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR",
|
||||
r"C:\HxopsRpaTest\data\onhand_triggers",
|
||||
)
|
||||
assert module._resolve_shared_scope_id() == ""
|
||||
monkeypatch.setenv(
|
||||
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
r"C:\mount\hxops-rpa-test-data\inventory_triggers",
|
||||
"FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR",
|
||||
r"C:\mount\hxops-rpa-test-data\onhand_triggers",
|
||||
)
|
||||
assert module._resolve_shared_scope_id() == "hxops-rpa-test-data"
|
||||
|
||||
@@ -66,7 +66,7 @@ def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
|
||||
trigger_dir = tmp_path / "inventory_triggers"
|
||||
trigger_dir = tmp_path / "onhand_triggers"
|
||||
trigger_dir.mkdir()
|
||||
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01")
|
||||
|
||||
@@ -28,8 +28,8 @@ def _repo_root() -> Path:
|
||||
|
||||
|
||||
def _load_freight_rpa_worker():
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path)
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -40,12 +40,12 @@ def _load_freight_rpa_worker():
|
||||
def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
|
||||
"""构造库存导出 trigger 样本,避免测试依赖会被 worker 消费掉的仓库文件。"""
|
||||
return {
|
||||
"action": "inventory_export",
|
||||
"action": "onhand_export",
|
||||
"task_no": task_no,
|
||||
"requested_at": "2026-07-01T03:23:25.114522",
|
||||
"mode": "auto",
|
||||
"attempt": 3,
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": f"SRC-{task_no}:C1",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_run_no": f"SRC-{task_no}",
|
||||
@@ -87,15 +87,15 @@ def test_single_inventory_trigger_missing_source_run_is_rejected_before_rpa(monk
|
||||
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
monkeypatch.setattr(worker, "_download_onhand_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks == [
|
||||
(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
"/api/freight-rpa/onhand-ready",
|
||||
{
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": None,
|
||||
"task_no": "SN-IDENTITY-INVALID",
|
||||
"business_status": "rejected",
|
||||
@@ -122,9 +122,9 @@ def test_single_inventory_trigger_missing_callback_id_is_rejected(monkeypatch, t
|
||||
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
monkeypatch.setattr(worker, "_download_onhand_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks[0][1]["callback_id"] is None
|
||||
assert callbacks[0][1]["error_code"] == "trigger_identity_invalid"
|
||||
@@ -156,7 +156,7 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-001:batch:C1",
|
||||
"batch_run_no": "BATCH-001",
|
||||
"task_no": "SN-BATCH-IDENTITY",
|
||||
@@ -166,9 +166,9 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
|
||||
result = completed["results"][0]
|
||||
assert {key: result[key] for key in (
|
||||
"callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
|
||||
@@ -210,7 +210,7 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-CRANE-DYNAMIC:batch:C1",
|
||||
"batch_run_no": "BATCH-CRANE-DYNAMIC",
|
||||
"task_no": "SN-CRANE-DYNAMIC",
|
||||
@@ -220,9 +220,9 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
|
||||
assert completed["results"][0]["callback_id"] == "PSR-CRANE-DYNAMIC:C1"
|
||||
assert completed["results"][0]["expected_warehouse_id"] is None
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
@@ -239,7 +239,7 @@ def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch
|
||||
trigger_path = trigger_dir / "inventory_export_batch_invalid.json"
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-INVALID:batch:C1",
|
||||
"batch_run_no": "BATCH-INVALID",
|
||||
"task_no": "SN-BATCH-INVALID",
|
||||
@@ -259,7 +259,7 @@ def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks[0][1]["callback_id"] == "BATCH-INVALID:batch:C1"
|
||||
assert callbacks[0][1]["identity_errors"] == ["inventory_sources[0].expected_warehouse_id"]
|
||||
@@ -279,7 +279,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
# batch 级无 task_no,逐源无 task_no/source_run_no/lease_token/candidate_set_id/execution_id/gate_id。
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "RUN-SCHEDULED:batch:C1",
|
||||
"batch_run_no": "RUN-SCHEDULED",
|
||||
"run_no": "RUN-SCHEDULED",
|
||||
@@ -304,9 +304,9 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
|
||||
assert completed["schedule_run_id"] == 713
|
||||
assert completed["trigger_type"] == "scheduled"
|
||||
result = completed["results"][0]
|
||||
@@ -314,7 +314,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
assert result["warehouse_id"] == "AWSDU"
|
||||
assert result["status"] == "success"
|
||||
# 每完成一个站点应回传一次累计进度,供后端实时回写排程 run 笔数。
|
||||
progress = next(body for path, body in callbacks if path.endswith("/inventory-batch-progress"))
|
||||
progress = next(body for path, body in callbacks if path.endswith("/onhand-batch-progress"))
|
||||
assert progress["schedule_run_id"] == 713
|
||||
assert progress["batch_run_no"] == "RUN-SCHEDULED"
|
||||
assert progress["success_count"] == 1
|
||||
@@ -339,7 +339,7 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
|
||||
# trigger_type=configuration_test,无 task_no / gate_id / execution_id 等生产身份。
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no,
|
||||
@@ -363,14 +363,14 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert not any(body.get("error_code") == "trigger_identity_invalid" for _, body in callbacks)
|
||||
ready = next(body for path, body in callbacks if path.endswith("/inventory-configuration-test-ready"))
|
||||
ready = next(body for path, body in callbacks if path.endswith("/onhand-configuration-test-analyze"))
|
||||
assert ready["run_no"] == run_no
|
||||
assert ready["status"] == "success"
|
||||
assert ready.get("file_path")
|
||||
assert not any(path.endswith("/inventory-batch-ready") for path, _ in callbacks)
|
||||
assert not any(path.endswith("/onhand-batch-ready") for path, _ in callbacks)
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
assert not (failed_dir / trigger_path.name).exists()
|
||||
|
||||
@@ -398,7 +398,7 @@ def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-INTERRUPT:batch:C1",
|
||||
"batch_run_no": "BATCH-INTERRUPT",
|
||||
"task_no": "SN-CRANE-INTERRUPT",
|
||||
@@ -417,14 +417,14 @@ def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup
|
||||
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda *_args, **_kwargs: (_Playwright(), _Context(), object(), tmp_path / "profile"))
|
||||
monkeypatch.setattr(worker, "_ensure_crane_session", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(worker, "_export_crane_inventory_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
|
||||
monkeypatch.setattr(worker, "_export_crane_onhand_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
with pytest.raises(KeyboardInterrupt):
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert stopped == [True]
|
||||
assert [path for path, _body in callbacks] == ["/api/shipping-notice/rpa/inventory-batch-claimed"]
|
||||
assert [path for path, _body in callbacks] == ["/api/freight-rpa/onhand-batch-claimed"]
|
||||
assert trigger_path.is_file()
|
||||
assert not (processed_dir / trigger_path.name).exists()
|
||||
|
||||
@@ -443,10 +443,10 @@ def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
def test_worker_accepts_business_connector_without_site_id():
|
||||
"""数据库 Source 的 dbs/crane 业务类型不应要求已删除的 site_id 字段。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
worker._validate_inventory_source_for_rpa({
|
||||
worker._validate_onhand_source_for_rpa({
|
||||
"source_code": "DBS_DUB", "connector_type": "dbs", "warehouse_id": "DUB",
|
||||
})
|
||||
worker._validate_inventory_source_for_rpa({
|
||||
worker._validate_onhand_source_for_rpa({
|
||||
"source_code": "CRANE", "connector_type": "crane",
|
||||
})
|
||||
|
||||
@@ -788,7 +788,7 @@ def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypat
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
stats = cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
onhand_trigger_dir=inv_trigger,
|
||||
upload_trigger_dir=upload_trigger,
|
||||
drop_dir=drop,
|
||||
upload_queue_dir=queue,
|
||||
@@ -836,7 +836,7 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
onhand_trigger_dir=inv_trigger,
|
||||
browser_profile_dir=profiles,
|
||||
now_unix=now,
|
||||
)
|
||||
@@ -845,36 +845,36 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
|
||||
assert not orphan_run.exists()
|
||||
|
||||
|
||||
def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
|
||||
def test_cleanup_orphan_runtime_profiles_removes_inbound_prefix(tmp_path):
|
||||
"""
|
||||
崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。
|
||||
崩溃残留的 inbound_* 临时 Profile 超期必须被清理;_session 目录保留。
|
||||
|
||||
断言意图:收料 Worker 的一次性 Profile 以 receipt_ 前缀创建,异常中断后
|
||||
断言意图:inbound Worker 的一次性 Profile 以 inbound_ 前缀创建,异常中断后
|
||||
残留目录同样按孤儿 Profile 规则清理;会话复用目录按名豁免(与年龄无关);
|
||||
未超期的 receipt_* Profile 正在使用中,前缀匹配不得误删。
|
||||
未超期的 inbound_* Profile 正在使用中,前缀匹配不得误删。
|
||||
"""
|
||||
cleanup = _load_worker_disk_cleanup()
|
||||
root = tmp_path / "browser_profile"
|
||||
stale_receipt = root / "receipt_abcd1234"
|
||||
stale_receipt.mkdir(parents=True)
|
||||
(stale_receipt / "Cookies").write_text("drop", encoding="utf-8")
|
||||
young_receipt = root / "receipt_fresh5678"
|
||||
young_receipt.mkdir()
|
||||
stale_inbound = root / "inbound_abcd1234"
|
||||
stale_inbound.mkdir(parents=True)
|
||||
(stale_inbound / "Cookies").write_text("drop", encoding="utf-8")
|
||||
young_inbound = root / "inbound_fresh5678"
|
||||
young_inbound.mkdir()
|
||||
session_dir = root / "dsv_session"
|
||||
session_dir.mkdir()
|
||||
now = time.time()
|
||||
old = now - 10 * 24 * 3600
|
||||
os.utime(stale_receipt, (old, old))
|
||||
os.utime(young_receipt, (now - 3600, now - 3600))
|
||||
os.utime(stale_inbound, (old, old))
|
||||
os.utime(young_inbound, (now - 3600, now - 3600))
|
||||
os.utime(session_dir, (old, old))
|
||||
stats = cleanup.DiskCleanupStats()
|
||||
|
||||
# cutoff 对齐真实调用语义:run_worker_disk_cleanup 传入 now - 孤儿最大存活(默认 24h)
|
||||
cleanup.cleanup_orphan_runtime_profiles(root, cutoff_unix=now - 24 * 3600, stats=stats)
|
||||
|
||||
# 过期 receipt_* 目录树删除;未过期 receipt_* 与 _session 结尾目录即使过期也保留
|
||||
assert not stale_receipt.exists() and session_dir.exists()
|
||||
assert young_receipt.exists()
|
||||
# 过期 inbound_* 目录树删除;未过期 inbound_* 与 _session 结尾目录即使过期也保留
|
||||
assert not stale_inbound.exists() and session_dir.exists()
|
||||
assert young_inbound.exists()
|
||||
assert stats.deleted_dirs == 1
|
||||
|
||||
|
||||
@@ -995,17 +995,17 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
download_calls: list[dict] = []
|
||||
|
||||
def fake_download_inventory_with_browser(trigger: dict, target_drop_dir: Path) -> Path:
|
||||
def fake_download_onhand_with_browser(trigger: dict, target_drop_dir: Path) -> Path:
|
||||
download_calls.append(trigger)
|
||||
out_file = target_drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"
|
||||
out_file = target_drop_dir / "onhand_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"
|
||||
out_file.write_bytes(b"fake inventory content")
|
||||
return out_file
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser)
|
||||
monkeypatch.setattr(worker, "_download_onhand_with_browser", fake_download_onhand_with_browser)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert len(download_calls) == 1
|
||||
trigger = download_calls[0]
|
||||
@@ -1018,9 +1018,9 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_path == "/api/freight-rpa/onhand-ready"
|
||||
assert callback_payload == {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
@@ -1034,7 +1034,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
"expected_warehouse_id": "AWSDU",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
|
||||
"file_path": str(drop_dir / "onhand_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
|
||||
"file_sha256": hashlib.sha256(b"fake inventory content").hexdigest(),
|
||||
"rpa_mode": "browser",
|
||||
}
|
||||
@@ -1060,12 +1060,12 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_ONHAND", raising=False)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
exported_files = list(drop_dir.glob("inventory_SN-20260629-2EDADC77_*.xlsx"))
|
||||
exported_files = list(drop_dir.glob("onhand_SN-20260629-2EDADC77_*.xlsx"))
|
||||
assert len(exported_files) == 1
|
||||
exported = exported_files[0]
|
||||
wb = load_workbook(exported, data_only=True, read_only=True)
|
||||
@@ -1080,9 +1080,9 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
assert rows[2] == ("A002", 50)
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_path == "/api/freight-rpa/onhand-ready"
|
||||
assert callback_payload == {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
@@ -1122,14 +1122,14 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
|
||||
raise worker.NoInventoryDataError("DSV report has no inventory data")
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
|
||||
monkeypatch.setattr(worker, "_download_onhand_with_browser", raise_no_inventory)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_path == "/api/freight-rpa/onhand-ready"
|
||||
assert callback_payload["status"] == "skipped"
|
||||
assert callback_payload["success"] is False
|
||||
assert callback_payload["skipped"] is True
|
||||
@@ -1139,10 +1139,10 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
|
||||
assert not trigger_path.exists()
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped():
|
||||
def test_summarize_onhand_batch_results_all_skipped():
|
||||
"""全 skipped 时 batch 顶层 legacy success 应为 true,status 为 success。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
summary = worker._summarize_onhand_batch_results([
|
||||
{"source_code": "A", "status": "skipped", "success": False, "skipped": True},
|
||||
{"source_code": "B", "status": "skipped", "success": False, "skipped": True},
|
||||
])
|
||||
@@ -1153,10 +1153,10 @@ def test_summarize_inventory_batch_results_all_skipped():
|
||||
assert summary["failed_count"] == 0
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_partial_failed():
|
||||
def test_summarize_onhand_batch_results_partial_failed():
|
||||
"""存在 failed 但有 success/skipped 时 legacy success 仍为 true,status=partial_failed。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
summary = worker._summarize_onhand_batch_results([
|
||||
{"source_code": "A", "status": "success", "success": True},
|
||||
{"source_code": "B", "status": "failed", "success": False},
|
||||
])
|
||||
@@ -1167,10 +1167,10 @@ def test_summarize_inventory_batch_results_partial_failed():
|
||||
assert summary["failed_count"] == 1
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_empty():
|
||||
def test_summarize_onhand_batch_results_empty():
|
||||
"""空 results 应返回全 0 计数,避免 helper 复用时 KeyError。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([])
|
||||
summary = worker._summarize_onhand_batch_results([])
|
||||
assert summary == {
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
@@ -1547,7 +1547,7 @@ def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
|
||||
|
||||
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
|
||||
|
||||
assert callbacks == [("/api/shipping-notice/rpa/upload-complete", {
|
||||
assert callbacks == [("/api/freight-rpa/upload-complete", {
|
||||
"task_no": "SN-UPLOAD-FAIL", "attempt_id": 8, "callback_id": "rpa:8",
|
||||
"result": "failed", "success": False, "error_message": "success marker missing",
|
||||
})]
|
||||
@@ -1573,10 +1573,10 @@ def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path):
|
||||
assert callbacks[0][1]["error_message"] == "queue file missing: <empty>"
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_skipped_and_failed():
|
||||
def test_summarize_onhand_batch_results_skipped_and_failed():
|
||||
"""仅有 skipped+failed 时 legacy success 为 true(skipped 算已处理)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
summary = worker._summarize_onhand_batch_results([
|
||||
{"source_code": "A", "status": "skipped", "success": False, "skipped": True},
|
||||
{"source_code": "B", "status": "failed", "success": False},
|
||||
])
|
||||
@@ -1590,18 +1590,18 @@ def test_summarize_inventory_batch_results_skipped_and_failed():
|
||||
def test_summarize_inventory_batch_item_empty_dict_counts_as_failed():
|
||||
"""batch 归一化对空 dict 应算 failed,避免缺字段误计 success。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
assert worker._normalize_inventory_batch_item_status({}) == "failed"
|
||||
summary = worker._summarize_inventory_batch_results([{}])
|
||||
assert worker._normalize_onhand_batch_item_status({}) == "failed"
|
||||
summary = worker._summarize_onhand_batch_results([{}])
|
||||
assert summary["failed_count"] == 1
|
||||
assert summary["success_count"] == 0
|
||||
assert summary["success"] is False
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped_is_success():
|
||||
def test_summarize_onhand_batch_results_all_skipped_is_success():
|
||||
"""全 skipped 代表链路正常但无库存,不得误报为批量导出失败。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
summary = worker._summarize_onhand_batch_results(results)
|
||||
assert summary["status"] == "success"
|
||||
assert summary["has_success"] is False
|
||||
assert summary["status"] not in {"failed", "partial_failed"}
|
||||
@@ -2760,7 +2760,7 @@ def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg():
|
||||
assert filled == {"#ReportViewerMain_ctl08_ctl03_txtValue": "CADU-0000000100"}
|
||||
|
||||
|
||||
def test_validate_inventory_excel_accepts_real_report_shape(tmp_path):
|
||||
def test_validate_onhand_excel_accepts_real_report_shape(tmp_path):
|
||||
"""下载完成后必须能打开 Excel,并包含库存报表标题和关键表头。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
path = tmp_path / "inventory.xlsx"
|
||||
@@ -2775,17 +2775,17 @@ def test_validate_inventory_excel_accepts_real_report_shape(tmp_path):
|
||||
ws.append(["CADU-0000000100", "Well Trust Precision Technology", f"504-006043-{index:03d}", "Frame"])
|
||||
wb.save(path)
|
||||
|
||||
worker._validate_inventory_excel(path)
|
||||
worker._validate_onhand_excel(path)
|
||||
|
||||
|
||||
def test_validate_inventory_excel_rejects_invalid_download(tmp_path):
|
||||
def test_validate_onhand_excel_rejects_invalid_download(tmp_path):
|
||||
"""下载文件太小或不是有效 Excel 时不能回调 success。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
path = tmp_path / "inventory.xlsx"
|
||||
path.write_bytes(b"not a complete excel")
|
||||
|
||||
with pytest.raises(RuntimeError, match="too small|valid Excel"):
|
||||
worker._validate_inventory_excel(path)
|
||||
worker._validate_onhand_excel(path)
|
||||
|
||||
|
||||
def test_find_dsv_report_result_frame_prefers_grid_like_frame():
|
||||
@@ -2952,7 +2952,7 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
|
||||
str(tmp_path / "browser_profile"),
|
||||
)
|
||||
|
||||
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
|
||||
out_file = worker._download_onhand_with_browser(trigger, drop_dir)
|
||||
|
||||
assert out_file.is_file()
|
||||
assert out_file.parent == drop_dir
|
||||
|
||||
@@ -9,7 +9,7 @@ from unittest.mock import MagicMock
|
||||
|
||||
|
||||
def _load_worker():
|
||||
return _load_rpa_module("freight_rpa_worker")
|
||||
return _load_rpa_module("onhand_rpa_worker")
|
||||
|
||||
|
||||
def _load_dsv_report_export():
|
||||
@@ -21,8 +21,8 @@ def _load_dsv_auth_login_flow():
|
||||
|
||||
|
||||
_RPA_MODULE_PATHS = {
|
||||
"freight_rpa_worker": "inventory/inventory_rpa_worker.py",
|
||||
"inventory_rpa_worker": "inventory/inventory_rpa_worker.py",
|
||||
"freight_rpa_worker": "onhand/onhand_rpa_worker.py",
|
||||
"onhand_rpa_worker": "onhand/onhand_rpa_worker.py",
|
||||
"dsv_report_export": "connectors/dsv/dsv_report_export.py",
|
||||
"dsv_auth_login_flow": "connectors/dsv/dsv_auth_login_flow.py",
|
||||
"dsv_navigation": "connectors/dsv/dsv_navigation.py",
|
||||
@@ -205,18 +205,18 @@ def test_ensure_dsv_inventory_rows_skips_retry_when_rows_already_visible(monkeyp
|
||||
assert clicks == []
|
||||
|
||||
|
||||
def test_dsv_export_kind_receipt_from_flag_and_report_name():
|
||||
"""收料 source 须显式或按报表名识别为 receipt,不得默认库存。"""
|
||||
def test_dsv_export_kind_inbound_from_flag_and_report_name():
|
||||
"""inbound source 须显式或按报表名识别为 inbound,不得默认库存。"""
|
||||
worker = _load_dsv_report_export()
|
||||
assert worker._dsv_export_kind({"__export_kind__": "receipt"}) == "receipt"
|
||||
assert worker._dsv_export_kind({"navigation": {"report_name": "Receipt Detail"}}) == "receipt"
|
||||
assert worker._dsv_export_kind({"__export_kind__": "inbound"}) == "inbound"
|
||||
assert worker._dsv_export_kind({"navigation": {"report_name": "Receipt Detail"}}) == "inbound"
|
||||
assert worker._dsv_export_kind({"navigation": {"report_name": "On Hand Inventory by Location"}}) == "inventory"
|
||||
assert "on hand inventory by location" not in worker._dsv_body_markers_for_kind("receipt")
|
||||
assert "qty expected" in worker._dsv_body_markers_for_kind("receipt")
|
||||
assert "qty available" not in " ".join(worker._dsv_body_markers_for_kind("receipt"))
|
||||
assert "on hand inventory by location" not in worker._dsv_body_markers_for_kind("inbound")
|
||||
assert "qty expected" in worker._dsv_body_markers_for_kind("inbound")
|
||||
assert "qty available" not in " ".join(worker._dsv_body_markers_for_kind("inbound"))
|
||||
|
||||
|
||||
def test_wait_receipt_result_ready_accepts_export_toolbar(monkeypatch):
|
||||
def test_wait_inbound_result_ready_accepts_export_toolbar(monkeypatch):
|
||||
"""收料就绪:无库存正文时,Export 工具栏 + 非 loading 即应放行。"""
|
||||
worker = _load_dsv_report_export()
|
||||
state = {
|
||||
@@ -239,10 +239,10 @@ def test_wait_receipt_result_ready_accepts_export_toolbar(monkeypatch):
|
||||
)
|
||||
monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(worker, "_emit_debug_event", lambda *args, **kwargs: None)
|
||||
worker._wait_for_dsv_report_result_ready(_FakePage(), 2_000, kind="receipt")
|
||||
worker._wait_for_dsv_report_result_ready(_FakePage(), 2_000, kind="inbound")
|
||||
|
||||
|
||||
def test_ensure_dsv_receipt_rows_retries_then_export_fallback(monkeypatch):
|
||||
def test_ensure_dsv_inbound_rows_retries_then_export_fallback(monkeypatch):
|
||||
"""收料 DOM 无行时重试 View Report;仍无行不得抛空,继续导出。"""
|
||||
worker = _load_dsv_report_export()
|
||||
clicks: list[str] = []
|
||||
@@ -252,20 +252,20 @@ def test_ensure_dsv_receipt_rows_retries_then_export_fallback(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_wait_dsv_report_receipt_rows",
|
||||
"_wait_dsv_report_inbound_rows",
|
||||
lambda page_arg, timeout_ms: (waits.append(timeout_ms) or next(row_outcomes, False)),
|
||||
)
|
||||
monkeypatch.setattr(worker, "_click_dsv_view_report", lambda page_arg: clicks.append("view"))
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms, kind="inventory": None)
|
||||
|
||||
worker._ensure_dsv_receipt_rows_or_export_fallback(page=object(), report_name="Receipt Detail")
|
||||
worker._ensure_dsv_inbound_rows_or_export_fallback(page=object(), report_name="Receipt Detail")
|
||||
|
||||
assert clicks == ["view"]
|
||||
assert waits == [5_000, 5_000]
|
||||
|
||||
|
||||
def test_run_dsv_export_uses_receipt_row_probe(monkeypatch):
|
||||
"""__export_kind__=receipt 时须走收料行探针,不得调用库存行 ensure。"""
|
||||
def test_run_dsv_export_uses_inbound_row_probe(monkeypatch):
|
||||
"""__export_kind__=inbound 时须走 inbound 行探针,不得调用库存行 ensure。"""
|
||||
worker = _load_dsv_report_export()
|
||||
calls: list[str] = []
|
||||
monkeypatch.setattr(worker, "_fill_report_parameters", lambda page_arg, source: None)
|
||||
@@ -273,8 +273,8 @@ def test_run_dsv_export_uses_receipt_row_probe(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms, kind="inventory": calls.append(f"wait:{kind}"))
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_ensure_dsv_receipt_rows_or_export_fallback",
|
||||
lambda page_arg, report_name: calls.append("receipt-rows"),
|
||||
"_ensure_dsv_inbound_rows_or_export_fallback",
|
||||
lambda page_arg, report_name: calls.append("inbound-rows"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
@@ -303,13 +303,13 @@ def test_run_dsv_export_uses_receipt_row_probe(monkeypatch):
|
||||
|
||||
result = worker._run_dsv_inventory_export_from_form(
|
||||
_Page(),
|
||||
{"__export_kind__": "receipt", "navigation": {"report_name": "Receipt Detail"}},
|
||||
{"__export_kind__": "inbound", "navigation": {"report_name": "Receipt Detail"}},
|
||||
)
|
||||
assert result == "download"
|
||||
assert "wait:receipt" in calls
|
||||
assert "receipt-rows" in calls
|
||||
assert "wait:inbound" in calls
|
||||
assert "inbound-rows" in calls
|
||||
assert "inventory-rows" not in calls
|
||||
assert "export:receipt" in calls
|
||||
assert "export:inbound" in calls
|
||||
|
||||
|
||||
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
|
||||
@@ -324,7 +324,7 @@ def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
|
||||
export_mock = MagicMock(return_value="download")
|
||||
monkeypatch.setattr(worker.dsv_driver, "download_dsv360_inventory", export_mock)
|
||||
|
||||
result = worker._download_dsv360_inventory(page, {"task_no": "SN-1"}, source)
|
||||
result = worker._download_dsv360_onhand(page, {"task_no": "SN-1"}, source)
|
||||
|
||||
export_mock.assert_called_once_with(page, {"task_no": "SN-1"}, source)
|
||||
assert result == "download"
|
||||
|
||||
@@ -6,10 +6,10 @@ from app.models import ScheduleRun, ScheduleTask, User
|
||||
|
||||
|
||||
def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_path):
|
||||
"""POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
|
||||
"""POST /api/internal/jobs/freight-rpa-onhand 应写入 batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
from app import db
|
||||
@@ -21,7 +21,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
|
||||
schedule_no="SCH-IJ-001",
|
||||
name="货代库存每日导出",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
data_source_type=None,
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
@@ -41,7 +41,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
|
||||
run_id = run.id
|
||||
|
||||
resp = client.post(
|
||||
"/api/internal/jobs/shipping-inventory-rpa",
|
||||
"/api/internal/jobs/freight-rpa-onhand",
|
||||
data=json.dumps({"run_no": run_no, "schedule_task_id": task_id}),
|
||||
content_type="application/json",
|
||||
)
|
||||
@@ -95,7 +95,7 @@ def test_internal_job_rejects_mismatched_schedule_task_id(client, app):
|
||||
task_id = task.id
|
||||
|
||||
resp = client.post(
|
||||
"/api/internal/jobs/shipping-inventory-rpa",
|
||||
"/api/internal/jobs/freight-rpa-onhand",
|
||||
data=json.dumps({"schedule_task_id": task_id}),
|
||||
content_type="application/json",
|
||||
)
|
||||
@@ -114,7 +114,7 @@ def test_internal_job_rejects_foreign_run_no(client, app):
|
||||
schedule_no="SCH-IJ-A",
|
||||
name="shipping task",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
data_source_type=None,
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
@@ -143,7 +143,7 @@ def test_internal_job_rejects_foreign_run_no(client, app):
|
||||
run_no = run.run_no
|
||||
|
||||
resp = client.post(
|
||||
"/api/internal/jobs/shipping-inventory-rpa",
|
||||
"/api/internal/jobs/freight-rpa-onhand",
|
||||
data=json.dumps({"schedule_task_id": task_a_id, "run_no": run_no}),
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
@@ -128,7 +128,7 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -151,9 +151,9 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
|
||||
drop_dir.mkdir()
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -172,7 +172,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
|
||||
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
field_id = _published_order_field()
|
||||
@@ -208,7 +208,7 @@ def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
||||
"""没有受控解析定义时,空结果不能被用作站点可用性的替代证据。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -225,7 +225,7 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app,
|
||||
"""当前绑定方案的核心栏位仍在时,历史无关列缺失也必须直接成为验证证据。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -245,7 +245,7 @@ def test_verified_current_profile_does_not_auto_enable_ready_source(app, tmp_pat
|
||||
"""当前解析验证通过且硬门槛齐全时,测试回调仍不得自动启用;启停只走显式开关。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
@@ -268,7 +268,7 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm
|
||||
"""解析测试通过不绕过发货模板门禁,条件不完整的站点必须保持停用。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
@@ -289,7 +289,7 @@ def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path):
|
||||
"""固定仓查询成功但无库存时,只写入验证事实,不得自动启用站点。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
@@ -313,7 +313,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app,
|
||||
"""同连接站点一次投递,混合成功、空库存及失败后仍独立汇总为部分失败。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
) as write_trigger:
|
||||
first = _source('BATCH_SOURCE_A', 'BATCH_LOGIN_A')
|
||||
second = _source('BATCH_SOURCE_B', 'BATCH_LOGIN_B')
|
||||
@@ -355,7 +355,7 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
"""批次重试只新建失败站点运行,成功和空库存结果不会被重复导出。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('RETRY_SOURCE', 'RETRY_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -377,7 +377,7 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app,
|
||||
"""配置变更后的旧批次回调必须失效,未知运行号不能污染同批次状态。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('STALE_BATCH_SOURCE', 'STALE_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -405,7 +405,7 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
||||
"""页面刷新只能恢复仍在执行的批次,已结束批次不会反复占用进度面板。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('RESTORE_BATCH_SOURCE', 'RESTORE_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -427,7 +427,7 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path)
|
||||
"""Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('PROGRESS_BATCH_SOURCE', 'PROGRESS_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -460,7 +460,7 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
first = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -480,9 +480,9 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
|
||||
app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS'] = 1
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -509,9 +509,9 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
|
||||
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
||||
app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS'] = 10
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
first = _source('TIMEOUT_QUEUE_A', 'TIMEOUT_QUEUE_LOGIN')
|
||||
second = _source('TIMEOUT_QUEUE_B', 'TIMEOUT_QUEUE_LOGIN_B')
|
||||
@@ -537,7 +537,7 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
@@ -579,7 +579,7 @@ def test_rpa_profile_change_does_not_block_activation_hard_gates(app, tmp_path):
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
@@ -611,7 +611,7 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
@@ -645,7 +645,7 @@ def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
failed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
"""
|
||||
inventory RPA:Playwright Download.save_as 因浏览器关闭失败时,应按 downloads_path 目录兜底落盘。
|
||||
tests/test_inventory_rpa_download_save_fallback.py
|
||||
|
||||
用途:Playwright Download.save_as 因浏览器关闭失败时,onhand Worker 按下载目录兜底落盘。
|
||||
依赖:scripts/freight_rpa/onhand/onhand_rpa_worker.py 的 _save_download / _save_batch_download。
|
||||
逻辑:假 Download 抛出 TargetClosed;目录里已有的 xlsx 应被改成规范文件名。
|
||||
报表结构校验 _validate_onhand_excel 换成空操作,避免假字节触发门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +17,7 @@ from pathlib import Path
|
||||
|
||||
def _load_worker():
|
||||
module_path = (
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
)
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
@@ -21,7 +26,7 @@ def _load_worker():
|
||||
common_dir = str(module_path.parent.parent / "common")
|
||||
if common_dir not in sys.path:
|
||||
sys.path.insert(0, common_dir)
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_save_fallback_test", module_path)
|
||||
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_save_fallback_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
@@ -47,7 +52,8 @@ def test_save_batch_download_falls_back_when_browser_closed(monkeypatch):
|
||||
landed = drop_dir / "chromium_download.xlsx"
|
||||
landed.write_bytes(b"PK" + b"0" * 600)
|
||||
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
# [断言意图] 假 xlsx 只覆盖落盘兜底,跳过 onhand 报表结构校验。
|
||||
monkeypatch.setattr(worker, "_validate_onhand_excel", lambda _path: None)
|
||||
|
||||
out = worker._save_batch_download(
|
||||
_ClosedBrowserDownload(),
|
||||
@@ -72,7 +78,8 @@ def test_save_batch_download_reraises_when_fallback_missing(monkeypatch):
|
||||
drop_dir = Path(tmp) / "drop"
|
||||
drop_dir.mkdir()
|
||||
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
# [断言意图] 假 xlsx 只覆盖落盘兜底,跳过 onhand 报表结构校验。
|
||||
monkeypatch.setattr(worker, "_validate_onhand_excel", lambda _path: None)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_wait_for_new_download_file",
|
||||
@@ -102,7 +109,8 @@ def test_save_download_falls_back_when_browser_closed(monkeypatch):
|
||||
drop_dir.mkdir()
|
||||
landed = drop_dir / "raw.xlsx"
|
||||
landed.write_bytes(b"PK" + b"0" * 600)
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
# [断言意图] 假 xlsx 只覆盖落盘兜底,跳过 onhand 报表结构校验。
|
||||
monkeypatch.setattr(worker, "_validate_onhand_excel", lambda _path: None)
|
||||
|
||||
out = worker._save_download(
|
||||
_ClosedBrowserDownload(),
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""tt16c7d8e9f0a1b2 排程 job key 入站化迁移契约测试。
|
||||
|
||||
用途:锁定 tt16 迁移两侧契约——schedule_tasks.platform_api_path 三键更名
|
||||
(shipping-inventory-rpa→freight-rpa-onhand、freight-receipt-rpa→freight-rpa-inbound、
|
||||
freight-receipt-rpa-retention→freight-rpa-inbound-retention,随代码同窗口发布),
|
||||
并锁定迁移链挂接当前单 head(tt16a7b8c9d0e1f2,其上游为 tt15b6a7b8c9d0)。
|
||||
依赖:migrations/versions(_load 手法沿用 tests/services/in_transit_transfer/
|
||||
test_migration_inbound_rename.py 的 tt14 契约测试)、app_ctx(根 conftest
|
||||
app fixture 上下文别名)。
|
||||
逻辑:revision 链断言 + SQLite 真实 UPDATE upgrade/downgrade 往返
|
||||
(UPDATE 语句 SQLite/PG 通用,迁移语义以 PG 为准)。
|
||||
Fix round 1:桩表列名由计划骨架误写的 job_key 修正为真实列 platform_api_path
|
||||
(models/schedule.py:34,排程表无独立 job_key 列),并追加无关 key 对照行与
|
||||
往返前后命中计数断言,确保 UPDATE 真实生效且 WHERE 谓词不误伤其他 key。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
|
||||
|
||||
# 与 tt16._MAPPING 同源的三键对照(升级方向)。
|
||||
_MAPPING = {
|
||||
"shipping-inventory-rpa": "freight-rpa-onhand",
|
||||
"freight-receipt-rpa": "freight-rpa-inbound",
|
||||
"freight-receipt-rpa-retention": "freight-rpa-inbound-retention",
|
||||
}
|
||||
# 无关对照 key:全程不得被 UPDATE 触碰(验证 WHERE 谓词精确性)。
|
||||
_UNRELATED_KEY = "faq-aggregate-hot"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_ctx(app):
|
||||
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
|
||||
return app
|
||||
|
||||
|
||||
def _load(revision_prefix: str):
|
||||
for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")):
|
||||
spec = importlib.util.spec_from_file_location(path.stem, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
raise AssertionError(f"migration {revision_prefix} not found")
|
||||
|
||||
|
||||
def test_revision_chains_from_tt15():
|
||||
"""tt16 必须单头挂接:直接前驱为 tt16a7b8c9d0e1f2,链上溯两跳即 tt15b6a7b8c9d0。
|
||||
|
||||
[断言意图] 实施时 tt15 已被调拨域迁移 tt16a7b8c9d0e1f2 占用为前驱;
|
||||
本迁移若再直挂 tt15 会产生双 head,破坏 flask db upgrade,故锁两级链。
|
||||
"""
|
||||
migration = _load("tt16c7d8e9f0a1b2")
|
||||
assert migration.down_revision == "tt16a7b8c9d0e1f2"
|
||||
parent = _load(migration.down_revision)
|
||||
assert parent.down_revision == "tt15b6a7b8c9d0"
|
||||
|
||||
|
||||
def test_job_key_upgrade_downgrade(app_ctx):
|
||||
"""SQLite 往返:三旧行 upgrade 后全量换新 key,downgrade 精确还原旧行。
|
||||
|
||||
[断言意图] 桩表用真实列名 platform_api_path(迁移 SQL 在其上真实可执行);
|
||||
_MAPPING 三键在 upgrade 后不复存在、downgrade 后新键清零且旧行 id→key 对应
|
||||
关系逐行还原(双向 UPDATE 均为全表谓词替换);无关 key 对照行全程不变。
|
||||
"""
|
||||
engine = sa.create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
|
||||
# tt16 仅 UPDATE schedule_tasks.platform_api_path(真实列名,String(500)),
|
||||
# 无表结构变更:建最小桩表承接。
|
||||
sa.Table(
|
||||
"schedule_tasks", sa.MetaData(),
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("platform_api_path", sa.String(length=500)),
|
||||
).create(connection)
|
||||
|
||||
old_keys = list(_MAPPING)
|
||||
rows = [{"id": index + 1, "key": key} for index, key in enumerate(old_keys)]
|
||||
# id=4 为无关 key 对照行:升级/降级都不得被改写。
|
||||
rows.append({"id": len(rows) + 1, "key": _UNRELATED_KEY})
|
||||
connection.execute(
|
||||
sa.text("INSERT INTO schedule_tasks (id, platform_api_path) VALUES (:id, :key)"),
|
||||
rows,
|
||||
)
|
||||
|
||||
migration = _load("tt16c7d8e9f0a1b2")
|
||||
migration.op = operations
|
||||
|
||||
def _job_keys() -> dict[int, str]:
|
||||
result = connection.execute(
|
||||
sa.text("SELECT id, platform_api_path FROM schedule_tasks ORDER BY id")
|
||||
)
|
||||
return {row_id: key for row_id, key in result.fetchall()}
|
||||
|
||||
def _count_any_of(keys: list[str]) -> int:
|
||||
return connection.execute(sa.text(
|
||||
"SELECT COUNT(*) FROM schedule_tasks WHERE platform_api_path IN "
|
||||
"('" + "','".join(keys) + "')"
|
||||
)).scalar()
|
||||
|
||||
# [前置基线] 旧三键恰 3 行、新键 0 行、无关 key 恰 1 行。
|
||||
assert _count_any_of(old_keys) == 3
|
||||
assert _count_any_of(list(_MAPPING.values())) == 0
|
||||
assert _count_any_of([_UNRELATED_KEY]) == 1
|
||||
|
||||
# [STEP 1] upgrade:旧行逐行映射新键,旧键零残留,无关 key 不受影响。
|
||||
migration.upgrade()
|
||||
assert _job_keys() == {
|
||||
1: _MAPPING[old_keys[0]],
|
||||
2: _MAPPING[old_keys[1]],
|
||||
3: _MAPPING[old_keys[2]],
|
||||
4: _UNRELATED_KEY,
|
||||
}
|
||||
assert _count_any_of(old_keys) == 0
|
||||
assert _count_any_of(list(_MAPPING.values())) == 3
|
||||
assert _count_any_of([_UNRELATED_KEY]) == 1
|
||||
|
||||
# [STEP 2] downgrade:反向映射逐行还原旧键,新键零残留,无关 key 不受影响。
|
||||
migration.downgrade()
|
||||
assert _job_keys() == {row["id"]: row["key"] for row in rows}
|
||||
assert _count_any_of(old_keys) == 3
|
||||
assert _count_any_of(list(_MAPPING.values())) == 0
|
||||
assert _count_any_of([_UNRELATED_KEY]) == 1
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_receipt_excel_empty.py
|
||||
|
||||
用途:收料 Excel「有表头无明细」判空回归;钉死标题行不得当表头。
|
||||
依赖:openpyxl、scripts/freight_rpa/receipt/receipt_excel_empty。
|
||||
依赖:openpyxl、scripts/freight_rpa/inbound/inbound_excel_empty。
|
||||
逻辑:构造 DSV 标题+表头无数据簿;复制生产 drop 样例断言 empty。
|
||||
"""
|
||||
|
||||
@@ -16,14 +16,14 @@ import pytest
|
||||
from openpyxl import Workbook
|
||||
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
_RECEIPT_DIR = _REPO_ROOT / 'scripts' / 'freight_rpa' / 'receipt'
|
||||
if str(_RECEIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_RECEIPT_DIR))
|
||||
_INBOUND_DIR = _REPO_ROOT / 'scripts' / 'freight_rpa' / 'inbound'
|
||||
if str(_INBOUND_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_INBOUND_DIR))
|
||||
|
||||
from receipt_excel_empty import ( # noqa: E402
|
||||
NoReceiptDataError,
|
||||
enforce_receipt_excel_not_empty,
|
||||
receipt_excel_has_detail_rows,
|
||||
from inbound_excel_empty import ( # noqa: E402
|
||||
NoInboundDataError,
|
||||
enforce_inbound_excel_not_empty,
|
||||
inbound_excel_has_detail_rows,
|
||||
)
|
||||
|
||||
_DROP_SAMPLE = (
|
||||
@@ -72,9 +72,9 @@ def test_title_row_must_not_count_as_detail(tmp_path: Path):
|
||||
"""
|
||||
path = tmp_path / 'header_only.xlsx'
|
||||
_write_dsv_title_header_only(path)
|
||||
assert receipt_excel_has_detail_rows(path) is False
|
||||
with pytest.raises(NoReceiptDataError, match='no_receipt_data'):
|
||||
enforce_receipt_excel_not_empty(path)
|
||||
assert inbound_excel_has_detail_rows(path) is False
|
||||
with pytest.raises(NoInboundDataError, match='no_receipt_data'):
|
||||
enforce_inbound_excel_not_empty(path)
|
||||
|
||||
|
||||
def test_header_plus_data_row_is_not_empty(tmp_path: Path):
|
||||
@@ -88,8 +88,8 @@ def test_header_plus_data_row_is_not_empty(tmp_path: Path):
|
||||
assert sheet is not None
|
||||
sheet.append(['Well Trust', 'HOX1', '0001', 'O', 'KN', 'WB1', 'Inbound', 'Closed', '01/01/2026', '', '0010', 'CBIS', '', '', 'SKU-1'])
|
||||
workbook.save(path)
|
||||
assert receipt_excel_has_detail_rows(path) is True
|
||||
enforce_receipt_excel_not_empty(path)
|
||||
assert inbound_excel_has_detail_rows(path) is True
|
||||
enforce_inbound_excel_not_empty(path)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _DROP_SAMPLE.is_file(), reason='production drop sample not present')
|
||||
@@ -101,6 +101,6 @@ def test_production_header_only_sample_is_empty(tmp_path: Path):
|
||||
"""
|
||||
target = tmp_path / _DROP_SAMPLE.name
|
||||
shutil.copy2(_DROP_SAMPLE, target)
|
||||
assert receipt_excel_has_detail_rows(target) is False
|
||||
with pytest.raises(NoReceiptDataError, match='no_receipt_data'):
|
||||
enforce_receipt_excel_not_empty(target)
|
||||
assert inbound_excel_has_detail_rows(target) is False
|
||||
with pytest.raises(NoInboundDataError, match='no_receipt_data'):
|
||||
enforce_inbound_excel_not_empty(target)
|
||||
@@ -63,17 +63,17 @@ def test_archive_rejects_bad_outcome_and_unclaimed_path(tmp_path):
|
||||
|
||||
|
||||
def test_inventory_worker_scans_with_claim(tmp_path):
|
||||
"""库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。"""
|
||||
root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory"
|
||||
text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8")
|
||||
"""onhand Worker 扫描必须先领取(processing/),不得原地消费根目录文件。"""
|
||||
root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "onhand"
|
||||
text = (root / "onhand_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "claim_trigger" in text
|
||||
# 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent
|
||||
assert text.count('trigger_path.parent / "failed"') == 0
|
||||
|
||||
|
||||
def test_receipt_worker_runs_periodic_disk_cleanup():
|
||||
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
|
||||
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
|
||||
"""inbound Worker 必须周期执行保留清理(对齐 onhand),孤儿 inbound_* Profile 必须纳入清理。"""
|
||||
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inbound" / "inbound_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
|
||||
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
|
||||
assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
|
||||
assert '"inbound_"' in cleanup or "'inbound_'" in cleanup
|
||||
@@ -35,11 +35,11 @@ def admin_jwt_headers(app):
|
||||
def test_platform_jobs_registered():
|
||||
"""内置 platform job 应已注册。"""
|
||||
keys = {job.key for job in list_platform_jobs()}
|
||||
assert "shipping-inventory-rpa" in keys
|
||||
assert "freight-rpa-onhand" in keys
|
||||
assert "faq-aggregate-hot" in keys
|
||||
assert "fixed-assets-snapshot" in keys
|
||||
assert "accounting-voucher-po-print" in keys
|
||||
assert get_platform_job("shipping-inventory-rpa") is not None
|
||||
assert get_platform_job("freight-rpa-onhand") is not None
|
||||
|
||||
|
||||
def test_unknown_platform_job_raises():
|
||||
@@ -62,7 +62,7 @@ def test_resolve_schedule_executor_dispatch():
|
||||
def test_normalize_job_key_extracts_last_segment_from_full_path():
|
||||
"""历史数据存完整内部路径或 URL 时,应提取最后一段作为 job key。"""
|
||||
assert normalize_job_key('/api/internal/jobs/faq-aggregate-hot') == 'faq-aggregate-hot'
|
||||
assert normalize_job_key('http://hxops.local/api/internal/jobs/shipping-inventory-rpa') == 'shipping-inventory-rpa'
|
||||
assert normalize_job_key('http://hxops.local/api/internal/jobs/freight-rpa-onhand') == 'freight-rpa-onhand'
|
||||
assert normalize_job_key('/api/internal/jobs/fixed_assets_snapshot?token=x') == 'fixed-assets-snapshot'
|
||||
assert normalize_job_key('faq_aggregate_hot') == 'faq-aggregate-hot'
|
||||
assert normalize_job_key(None) == ''
|
||||
@@ -97,7 +97,7 @@ def test_migrate_legacy_shipping_inventory_rpa():
|
||||
"platform_api_path": "/123",
|
||||
})
|
||||
assert migrated["schedule_type"] == "platform_job"
|
||||
assert migrated["platform_api_path"] == "shipping-inventory-rpa"
|
||||
assert migrated["platform_api_path"] == "freight-rpa-onhand"
|
||||
assert migrated["data_source_type"] is None
|
||||
|
||||
|
||||
@@ -135,7 +135,7 @@ def test_run_platform_job_unknown_key(app):
|
||||
schedule_no="SCH-REG-001",
|
||||
name="test",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
)
|
||||
@@ -208,14 +208,14 @@ def test_get_platform_jobs_api(client, admin_jwt_headers):
|
||||
assert res.status_code == 200
|
||||
body = res.get_json()
|
||||
keys = {item["key"] for item in body}
|
||||
assert "shipping-inventory-rpa" in keys
|
||||
assert "freight-rpa-onhand" in keys
|
||||
assert "faq-aggregate-hot" in keys
|
||||
assert "disabled-for-filter-test" not in keys
|
||||
assert all(item.get("enabled") is True for item in body)
|
||||
assert all("label" in item for item in body)
|
||||
# 内置 job 应返回稳定 i18n key,供前端 $t(label_key) 渲染
|
||||
by_key = {item["key"]: item for item in body}
|
||||
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
|
||||
assert by_key["freight-rpa-onhand"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
|
||||
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
|
||||
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
|
||||
assert by_key["accounting-voucher-po-print"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherPoPrint"
|
||||
|
||||
@@ -61,7 +61,7 @@ def test_platform_task_definitions_returns_params_schema(client, admin_jwt_heade
|
||||
assert body['success'] is True
|
||||
by_type = {item['task_type']: item for item in body['data']}
|
||||
# 货代库存 RPA:multi_select 库存源字段
|
||||
rpa = by_type['shipping-inventory-rpa']
|
||||
rpa = by_type['freight-rpa-onhand']
|
||||
assert rpa['category'] == 'shipping'
|
||||
schema_keys = {f['key']: f for f in rpa['params_schema']}
|
||||
assert schema_keys['source_codes']['type'] == 'multi_select'
|
||||
@@ -106,7 +106,7 @@ def test_platform_task_options_unknown_source_rejected(client, admin_jwt_headers
|
||||
def test_validate_task_params_fills_defaults(app):
|
||||
"""未提供字段应回填注册表默认值。"""
|
||||
with app.app_context():
|
||||
result = validate_task_params('shipping-inventory-rpa', {}, check_options=False)
|
||||
result = validate_task_params('freight-rpa-onhand', {}, check_options=False)
|
||||
assert result == {'source_codes': []}
|
||||
result_faq = validate_task_params('faq-aggregate-hot', {}, check_options=False)
|
||||
assert result_faq == {'app_id': None}
|
||||
@@ -125,7 +125,7 @@ def test_validate_task_params_rejects_wrong_type(app):
|
||||
source_code = _enabled_source_code()
|
||||
with pytest.raises(JobParamsValidationError, match='list of option values'):
|
||||
validate_task_params(
|
||||
'shipping-inventory-rpa',
|
||||
'freight-rpa-onhand',
|
||||
{'source_codes': source_code},
|
||||
check_options=False,
|
||||
)
|
||||
@@ -137,13 +137,13 @@ def test_validate_task_params_checks_option_range(app):
|
||||
source_code = _enabled_source_code()
|
||||
with pytest.raises(JobParamsValidationError, match='not in options'):
|
||||
validate_task_params(
|
||||
'shipping-inventory-rpa',
|
||||
'freight-rpa-onhand',
|
||||
{'source_codes': ['NOT_A_REAL_SOURCE']},
|
||||
check_options=True,
|
||||
)
|
||||
# 合法值应通过
|
||||
result = validate_task_params(
|
||||
'shipping-inventory-rpa',
|
||||
'freight-rpa-onhand',
|
||||
{'source_codes': [source_code]},
|
||||
check_options=True,
|
||||
)
|
||||
@@ -154,7 +154,7 @@ def test_validate_task_params_passes_advanced_through(app):
|
||||
"""_advanced 高级 JSON 区域应原样透传(历史/特殊任务兜底)。"""
|
||||
with app.app_context():
|
||||
result = validate_task_params(
|
||||
'shipping-inventory-rpa',
|
||||
'freight-rpa-onhand',
|
||||
{'source_codes': [], ADVANCED_PARAMS_KEY: {'timeout_seconds': 300}},
|
||||
check_options=False,
|
||||
)
|
||||
@@ -175,7 +175,7 @@ def _create_platform_schedule(client, headers, owner_id, *, job_params=None, ext
|
||||
payload = {
|
||||
'name': 'contract test',
|
||||
'schedule_type': 'platform_job',
|
||||
'platform_api_path': 'shipping-inventory-rpa',
|
||||
'platform_api_path': 'freight-rpa-onhand',
|
||||
'owner_user_id': owner_id,
|
||||
'cron_expr': '0 3 * * *',
|
||||
}
|
||||
@@ -365,7 +365,7 @@ def test_faq_job_prefers_job_params_over_dify_agent_id(app):
|
||||
|
||||
def test_shipping_rpa_filter_prefers_job_params(app):
|
||||
"""货代 RPA 应优先按 job_params.source_codes 筛选库存源。"""
|
||||
from app.services.schedule.shipping_inventory_rpa_job import _filter_sources
|
||||
from app.services.schedule.freight_onhand_rpa_job import _filter_sources
|
||||
|
||||
with app.app_context():
|
||||
source_code = _enabled_source_code()
|
||||
@@ -536,7 +536,7 @@ def test_enable_rejects_disabled_platform_job(client, admin_jwt_headers, owner_i
|
||||
register_platform_job,
|
||||
)
|
||||
|
||||
job_key = 'shipping-inventory-rpa'
|
||||
job_key = 'freight-rpa-onhand'
|
||||
original = get_platform_job(job_key)
|
||||
assert original is not None
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
tests/test_shipping_inventory_configuration.py
|
||||
|
||||
用途:验证库存源主数据、外部系统映射约束和 RPA 凭据加密的阶段一契约。
|
||||
依赖:Flask app/db、库存配置模型、credential_crypto、inventory_source_repository。
|
||||
依赖:Flask app/db、库存配置模型、freight_rpa.common.credential_crypto、inventory_source_repository。
|
||||
逻辑:阶段二前锁定最小数据安全与关系约束,避免错误配置进入路由或 RPA 执行链路。
|
||||
"""
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.models import (
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask, ShippingRpaProfile,
|
||||
)
|
||||
from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.inventory_external_mapping import resolve_external_warehouse
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_notice_inventory_rpa_archive.py
|
||||
|
||||
用途:库存 RPA 原始库存 ZIP 归档、summary 可见性与 admin API 路由单测。
|
||||
依赖:shipping_inventory_rpa_archive、api/schedule/runs、query_service、shipping_inventory_rpa_finalize。
|
||||
依赖:freight_onhand_rpa_archive、api/schedule/runs、query_service、freight_onhand_rpa_finalize。
|
||||
逻辑:finalize 预生成 ZIP;列表只读 summary;下载 send_file 归档路径。
|
||||
"""
|
||||
|
||||
@@ -26,7 +26,7 @@ from app.services.schedule.scheduler_service import (
|
||||
_build_schedule_run_wecom_description,
|
||||
_build_schedule_run_wecom_jump_params,
|
||||
)
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import (
|
||||
from app.services.schedule.freight_onhand_rpa_archive import (
|
||||
inventory_raw_zip_available_from_summary,
|
||||
inventory_raw_zip_download_name,
|
||||
inventory_rpa_attachment_stem,
|
||||
@@ -130,7 +130,7 @@ def test_serialize_run_reads_inventory_raw_zip_available_from_summary(app):
|
||||
def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path):
|
||||
"""finalize 预生成应落盘 ZIP 并返回 summary 字段。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
@@ -176,7 +176,7 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p
|
||||
def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
|
||||
"""无可读快照时不生成 ZIP。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
with app.app_context():
|
||||
run = _make_inventory_run_with_created(
|
||||
@@ -193,7 +193,7 @@ def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_fi
|
||||
def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path):
|
||||
"""created 有记录但磁盘文件缺失时不应生成 ZIP。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
with app.app_context():
|
||||
run = _make_inventory_run_with_created(
|
||||
@@ -219,7 +219,7 @@ def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp
|
||||
def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path):
|
||||
"""下载解析应返回归档路径与建议文件名。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
@@ -262,7 +262,7 @@ def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
|
||||
def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path):
|
||||
"""summary 指向归档目录外的真实文件时必须 404。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
outside_zip = tmp_path / "outside.zip"
|
||||
outside_zip.write_bytes(b"fake-zip")
|
||||
@@ -286,7 +286,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path
|
||||
"""summary 指向非 .zip 后缀文件时必须 404。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
archive_dir.mkdir(parents=True)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
fake_file = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt"
|
||||
fake_file.write_bytes(b"not-a-zip")
|
||||
@@ -414,7 +414,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
|
||||
app.config["WECOM_NOTIFY_ENABLED"] = True
|
||||
app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com"
|
||||
app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(tmp_path / "archives")
|
||||
|
||||
user = User(
|
||||
username="wecom_jump_user",
|
||||
@@ -482,7 +482,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
|
||||
):
|
||||
"""admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
|
||||
@@ -191,7 +191,9 @@ def test_auto_inventory_missing_snapshot_triggers_rpa(monkeypatch):
|
||||
trigger = {'status': 'running', 'task_id': task.task_no, 'rpa': {'attempts': 1}}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
|
||||
lambda _task, *, mode, allow_auto_retry=True: trigger,
|
||||
# source_codes:inventory_workflow.ensure_inventory 自 70dd0051b 起透传 scoped 源列表,
|
||||
# 测试桩需同步接受(修复既有签名漂移,与本任务平移无关)。
|
||||
lambda _task, *, mode, allow_auto_retry=True, source_codes=None: trigger,
|
||||
)
|
||||
|
||||
result = inventory_workflow.ensure_inventory({
|
||||
@@ -225,7 +227,9 @@ def test_auto_inventory_uses_per_source_attempt_identity_contract(app, monkeypat
|
||||
monkeypatch.setattr(workflow, 'task_rpa_inventory_source', lambda _task: {'source_code': 'DSV360_AWSDU'})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
|
||||
lambda actual_task, *, mode, allow_auto_retry=True: calls.append((actual_task, mode)) or prepared,
|
||||
# source_codes:ensure_inventory_via_rpa 会透传 scoped 源列表,
|
||||
# 测试桩需同步接受(修复既有签名漂移,与本任务平移无关)。
|
||||
lambda actual_task, *, mode, allow_auto_retry=True, source_codes=None: calls.append((actual_task, mode)) or prepared,
|
||||
)
|
||||
monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_args, **_kwargs: None)
|
||||
@@ -641,7 +645,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_mixed.xlsx"
|
||||
@@ -683,7 +687,7 @@ def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "inventory-mapping-confirmed.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -769,7 +773,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "batch_task_success.xlsx"
|
||||
@@ -854,7 +858,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(
|
||||
@@ -981,7 +985,7 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "crane-multi-warehouse.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("CRANE-WH").getvalue())
|
||||
|
||||
@@ -1054,7 +1058,7 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "crane-unresolved-link.xlsx"
|
||||
sample.write_bytes(
|
||||
inventory_xlsx_with_warehouse(
|
||||
@@ -1301,7 +1305,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "orphan_task.xlsx"
|
||||
with open(sample, "wb") as handle:
|
||||
@@ -1394,13 +1398,13 @@ def test_per_source_timeout_archives_unclaimed_trigger_into_failed(app, tmp_path
|
||||
|
||||
def test_inventory_trigger_writes_without_online_worker(app, tmp_path, monkeypatch):
|
||||
"""投递库存 trigger 只依赖共享目录可写,Worker 可在稍后启动并领取。"""
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
trigger_dir = tmp_path / 'inventory_triggers'
|
||||
app.config['FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir)
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR'] = str(trigger_dir)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready',
|
||||
'app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready',
|
||||
lambda: (_ for _ in ()).throw(AssertionError('trigger write must not require worker heartbeat')),
|
||||
)
|
||||
|
||||
@@ -1515,7 +1519,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "reuse_ingest_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1587,7 +1591,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
run_no = "RUN-REUSE-MISMATCH"
|
||||
|
||||
@@ -1642,7 +1646,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample_a = drop_dir / "task_a.xlsx"
|
||||
sample_b = drop_dir / "task_b.xlsx"
|
||||
sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1714,7 +1718,7 @@ def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path,
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "failed_before_confirm.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
callback_calls: list[dict] = []
|
||||
@@ -1775,7 +1779,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "shared.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
run_no = "RUN-SHARED-LINK"
|
||||
@@ -1851,7 +1855,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "post_commit.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1894,7 +1898,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "promote_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1982,13 +1986,13 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
|
||||
def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch):
|
||||
"""callback 归档失败时应写入持久化 cleanup job。"""
|
||||
from app import db
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import callback_cleanup_queue_dir
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import callback_cleanup_queue_dir
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "move_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -2021,13 +2025,13 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m
|
||||
"""move 与 quarantine 均失败时,仍应以原路径入队且 API 返回 ok。"""
|
||||
import json
|
||||
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import callback_cleanup_queue_dir
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import callback_cleanup_queue_dir
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "quarantine_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -2146,7 +2150,7 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
|
||||
|
||||
def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_path):
|
||||
"""cleanup 队列应由启动恢复独立消费,不依赖下一次 callback。"""
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import (
|
||||
callback_cleanup_queue_dir,
|
||||
enqueue_callback_file_move,
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
@@ -2156,7 +2160,7 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat
|
||||
processed_dir = tmp_path / "processed"
|
||||
drop_dir.mkdir()
|
||||
processed_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir)
|
||||
|
||||
quarantine = drop_dir / ".hxops_quarantine"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_notice_inventory_schedule.py
|
||||
|
||||
用途:货代库存 RPA 排程 executor、defer/finalize 契约与 source 过滤单测。
|
||||
依赖:ScheduleTask/ScheduleRun、shipping_inventory_rpa_job、shipping_inventory_rpa_finalize。
|
||||
依赖:ScheduleTask/ScheduleRun、freight_onhand_rpa_job、freight_onhand_rpa_finalize。
|
||||
逻辑:覆盖 trigger 写入、awaiting 终态、回调 finalize、超时回收。
|
||||
"""
|
||||
|
||||
@@ -14,7 +14,7 @@ import pytest
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig, User
|
||||
from app.services.schedule.scheduler_service import run_task_now
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import (
|
||||
_build_finalize_details,
|
||||
_compute_run_status,
|
||||
is_awaiting_rpa_schedule_run,
|
||||
@@ -22,7 +22,7 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
)
|
||||
from app.services.schedule import reload_config, resolve_schedule_header
|
||||
from app.services.schedule.shipping_inventory_rpa_job import (
|
||||
from app.services.schedule.freight_onhand_rpa_job import (
|
||||
_filter_sources,
|
||||
run_shipping_inventory_rpa_schedule,
|
||||
)
|
||||
@@ -79,7 +79,7 @@ def _make_inventory_schedule_task(
|
||||
schedule_no=schedule_no,
|
||||
name="货代库存每日导出",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
data_source_type=None,
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
@@ -103,7 +103,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
|
||||
"""排程 executor 应写入 inventory_export_batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -135,7 +135,7 @@ def test_run_task_now_defers_inventory_rpa_until_callback(app, tmp_path):
|
||||
"""run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -157,7 +157,7 @@ def test_deferred_run_sets_started_at_when_missing(app, tmp_path):
|
||||
"""复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -244,7 +244,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
|
||||
"""全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_excel_fail.xlsx"
|
||||
@@ -254,7 +254,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
|
||||
raise RuntimeError("excel exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.shipping_inventory_rpa_finalize.export_schedule_result_excel",
|
||||
"app.services.schedule.freight_onhand_rpa_finalize.export_schedule_result_excel",
|
||||
_excel_boom,
|
||||
)
|
||||
|
||||
@@ -309,7 +309,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
|
||||
"""finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_fail_finalize.xlsx"
|
||||
@@ -319,7 +319,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
|
||||
raise RuntimeError("finalize exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details",
|
||||
"app.services.schedule.freight_onhand_rpa_finalize._build_finalize_details",
|
||||
_boom,
|
||||
)
|
||||
|
||||
@@ -373,7 +373,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
|
||||
drop_dir.mkdir()
|
||||
processed_dir = drop_dir / "processed"
|
||||
processed_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_sample.xlsx"
|
||||
@@ -516,7 +516,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
|
||||
"""回调结果少于触发源数时,排程应 partial_failed。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_partial.xlsx"
|
||||
@@ -653,10 +653,10 @@ def test_is_awaiting_rpa_schedule_run_helper(app):
|
||||
|
||||
|
||||
def test_inventory_rpa_excel_headers_survive_reload_config(app):
|
||||
"""reload_config 后 shipping-inventory-rpa 表头仍应可用。"""
|
||||
"""reload_config 后 freight-rpa-onhand 表头仍应可用。"""
|
||||
with app.app_context():
|
||||
reload_config()
|
||||
header_order, header_labels = resolve_schedule_header("shipping-inventory-rpa")
|
||||
header_order, header_labels = resolve_schedule_header("freight-rpa-onhand")
|
||||
assert header_order
|
||||
assert header_labels.get("inventory_file_no") == "库存快照号"
|
||||
|
||||
@@ -753,7 +753,7 @@ def test_scheduled_batch_progress_updates_run_counts(app):
|
||||
db.session.commit()
|
||||
|
||||
result = report_inventory_batch_progress({
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "RUN-PROGRESS:batch:C1",
|
||||
"batch_run_no": "RUN-PROGRESS",
|
||||
"run_no": "RUN-PROGRESS",
|
||||
@@ -795,7 +795,7 @@ def test_scheduled_batch_progress_rejects_mismatched_run_no(app):
|
||||
db.session.commit()
|
||||
|
||||
result = report_inventory_batch_progress({
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "RUN-PROGRESS-WRONG:batch:C1",
|
||||
"batch_run_no": "RUN-PROGRESS-WRONG",
|
||||
"schedule_run_id": run.id,
|
||||
@@ -834,7 +834,7 @@ def test_scheduled_batch_progress_noop_after_finalized(app):
|
||||
db.session.commit()
|
||||
|
||||
result = report_inventory_batch_progress({
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "RUN-PROGRESS-FINAL:batch:C1",
|
||||
"batch_run_no": "RUN-PROGRESS-FINAL",
|
||||
"schedule_run_id": run.id,
|
||||
@@ -853,7 +853,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "missing_warehouse.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
@@ -883,7 +883,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "retry_snapshot.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
@@ -892,7 +892,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
raise RuntimeError("finalize exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details",
|
||||
"app.services.schedule.freight_onhand_rpa_finalize._build_finalize_details",
|
||||
_boom,
|
||||
)
|
||||
|
||||
@@ -942,11 +942,11 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, monkeypatch):
|
||||
"""finalize 首次失败、重试成功后应归档 callback 原文件。"""
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.schedule import shipping_inventory_rpa_finalize as finalize_mod
|
||||
from app.services.schedule import freight_onhand_rpa_finalize as finalize_mod
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "retry_move.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
|
||||
@@ -2,19 +2,19 @@
|
||||
backend/tests/test_shipping_notice_rpa_trigger_for_task.py
|
||||
|
||||
用途:验证按需库存导出仅生成 v2 batch trigger,并携带完整冻结身份。
|
||||
依赖:shipping_notice.rpa、pytest app/tmp_path 夹具。
|
||||
依赖:shipping_notice.onhand_trigger_batch、pytest app/tmp_path 夹具。
|
||||
逻辑:构造 connector_type 库存连接器载荷,检查 trigger 文件分支与关键字段。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_trigger_for_task
|
||||
|
||||
|
||||
def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
|
||||
"""batch 开启时单票按需应写 inventory_export_batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
|
||||
@@ -41,7 +41,8 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
|
||||
trigger_files = list(trigger_dir.glob("inventory_export_batch_*.json"))
|
||||
assert trigger_files
|
||||
payload = __import__("json").loads(trigger_files[0].read_text(encoding="utf-8"))
|
||||
assert payload["action"] == "inventory_export_batch"
|
||||
assert payload["action"] == "onhand_export_batch"
|
||||
assert payload["schema_version"] == "freight_rpa.onhand.v1"
|
||||
item = payload["inventory_sources"][0]
|
||||
assert item["task_no"] == "SN-ON-DEMAND-1"
|
||||
assert item["source_code"] == "DSV360_AWSDU"
|
||||
@@ -55,7 +56,7 @@ def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
|
||||
|
||||
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
|
||||
@@ -68,10 +69,10 @@ def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
|
||||
def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_path):
|
||||
"""平台 trigger 仅保留业务 connector,且明确给 worker 兼容的 driver 与登录入口。"""
|
||||
import json
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
with app.app_context():
|
||||
path = write_inventory_export_batch_trigger("RUN-DBS", [{
|
||||
"source_code": "UNKNOWN_FOR_TEST", "connector_type": "dbs", "rpa_profile_code": "DBS_TEST",
|
||||
@@ -89,10 +90,10 @@ def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_p
|
||||
def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path):
|
||||
"""新 batch Trigger 必须显式写入顶层和逐源 callback_id,Worker 不得推导。"""
|
||||
import json
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
|
||||
source = {
|
||||
"source_code": "DBS",
|
||||
|
||||
@@ -459,10 +459,10 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
headers = _tool_headers(app)
|
||||
trigger = tmp_path / "inventory_triggers"
|
||||
trigger.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS"] = 1
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
lambda: None,
|
||||
)
|
||||
|
||||
|
||||
@@ -412,7 +412,7 @@ def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
|
||||
source_code='DBS',
|
||||
run_no=attempt.source_run_no,
|
||||
callback_payload={
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'schema_version': 'freight_rpa.onhand.v1',
|
||||
'callback_id': 'PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X:C2',
|
||||
'task_no': task.task_no,
|
||||
'source_code': 'DBS',
|
||||
@@ -461,7 +461,7 @@ def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app,
|
||||
)
|
||||
|
||||
response = inventory_rpa_workflow.rpa_report_inventory({
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'schema_version': 'freight_rpa.onhand.v1',
|
||||
'callback_id': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X:C1',
|
||||
'task_no': task.task_no,
|
||||
'task_id': task.task_no,
|
||||
@@ -504,7 +504,7 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
|
||||
)
|
||||
|
||||
inventory_rpa_workflow.rpa_report_inventory({
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'schema_version': 'freight_rpa.onhand.v1',
|
||||
'callback_id': 'PSR-SN-2026-001-DBS-A1-X:C1',
|
||||
'task_no': task.task_no,
|
||||
'task_id': task.task_no,
|
||||
@@ -546,7 +546,7 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
|
||||
|
||||
# HTTP 入口只负责受控收件和入队;身份围栏属于 Worker 正式处理体。
|
||||
response = inventory_rpa_workflow.process_rpa_report_inventory_batch({
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'schema_version': 'freight_rpa.onhand.v1',
|
||||
'callback_id': 'batch-callback-identity',
|
||||
'batch_run_no': 'BATCH-CALLBACK-IDENTITY',
|
||||
'results': [{
|
||||
@@ -574,7 +574,7 @@ def test_batch_callback_inherits_authenticated_top_level_schema_version():
|
||||
|
||||
merged = _merge_batch_callback_item(
|
||||
{
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'schema_version': 'freight_rpa.onhand.v1',
|
||||
'run_no': 'BATCH-1',
|
||||
'task_no': 'SN-1',
|
||||
},
|
||||
@@ -584,7 +584,7 @@ def test_batch_callback_inherits_authenticated_top_level_schema_version():
|
||||
},
|
||||
)
|
||||
|
||||
assert merged['schema_version'] == 'shipping_inventory_rpa.v2'
|
||||
assert merged['schema_version'] == 'freight_rpa.onhand.v1'
|
||||
assert merged['run_no'] == 'BATCH-1'
|
||||
assert merged['task_no'] == 'SN-1'
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/tests/test_shipping_receipt_rpa_archive.py
|
||||
backend/tests/test_freight_inbound_rpa_archive.py
|
||||
|
||||
用途:收料 RPA 原始收料 ZIP 归档、summary 可见性与 admin API 路由单测。
|
||||
依赖:shipping_receipt_rpa_archive、api/schedule/runs、freight_receipt_rpa_finalize。
|
||||
依赖:freight_inbound_rpa_archive、api/schedule/runs、freight_inbound_rpa_finalize。
|
||||
逻辑:finalize 预生成 ZIP;下载 send_file 归档路径;包内条目为序号_source_code。
|
||||
"""
|
||||
|
||||
@@ -26,7 +26,7 @@ from app.models import (
|
||||
ShippingReceiptRpaUnitRun,
|
||||
User,
|
||||
)
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import (
|
||||
from app.services.schedule.freight_inbound_rpa_archive import (
|
||||
get_receipt_archive_dir,
|
||||
persist_receipt_rpa_raw_zip_archive,
|
||||
receipt_raw_zip_available_from_summary,
|
||||
@@ -80,7 +80,7 @@ def _make_receipt_run_with_file(
|
||||
schedule_no=schedule_no,
|
||||
name=f'Receipt archive {schedule_no}',
|
||||
schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa',
|
||||
platform_api_path='freight-rpa-inbound',
|
||||
owner_user_id=owner.id,
|
||||
cron_expr='0 8 * * *',
|
||||
schedule_timezone='Asia/Shanghai',
|
||||
@@ -142,11 +142,11 @@ def test_get_receipt_archive_dir_falls_back_when_config_none(app, tmp_path, monk
|
||||
|
||||
monkeypatch.setattr(
|
||||
Config,
|
||||
'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR',
|
||||
'FREIGHT_RPA_INBOUND_ARCHIVE_DIR',
|
||||
str(tmp_path / 'receipt_archives_fallback'),
|
||||
)
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = None
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = None
|
||||
archive_dir = Path(get_receipt_archive_dir())
|
||||
assert archive_dir.is_dir()
|
||||
assert archive_dir == (tmp_path / 'receipt_archives_fallback').resolve()
|
||||
@@ -155,7 +155,7 @@ def test_get_receipt_archive_dir_falls_back_when_config_none(app, tmp_path, monk
|
||||
def test_config_exposes_freight_rpa_receipt_archive_dir(app):
|
||||
"""Flask Config 必须声明收料归档目录,否则 env 不会进 app.config。"""
|
||||
with app.app_context():
|
||||
value = app.config.get('FREIGHT_RPA_RECEIPT_ARCHIVE_DIR')
|
||||
value = app.config.get('FREIGHT_RPA_INBOUND_ARCHIVE_DIR')
|
||||
assert value is not None
|
||||
assert str(value).strip() != ''
|
||||
|
||||
@@ -172,7 +172,7 @@ def test_serialize_run_reads_receipt_raw_zip_available_from_summary(app):
|
||||
schedule_no='ARCH-RCP-SER',
|
||||
name='Receipt archive serialize',
|
||||
schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa',
|
||||
platform_api_path='freight-rpa-inbound',
|
||||
owner_user_id=user.id,
|
||||
cron_expr='0 8 * * *',
|
||||
)
|
||||
@@ -204,9 +204,9 @@ def test_build_zip_entry_name_prefers_source_code():
|
||||
def test_persist_receipt_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path, monkeypatch):
|
||||
"""finalize 预生成应落盘 ZIP(含 manifest)并返回 summary 字段。"""
|
||||
archive_dir = tmp_path / 'receipt_archives'
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(archive_dir)
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(archive_dir)
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.shipping_receipt_rpa_archive.file_asset_storage.get_bytes',
|
||||
'app.services.schedule.freight_inbound_rpa_archive.file_asset_storage.get_bytes',
|
||||
lambda _key: b'fake-receipt-xlsx',
|
||||
)
|
||||
|
||||
@@ -239,7 +239,7 @@ def test_persist_receipt_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_pat
|
||||
|
||||
def test_resolve_receipt_raw_zip_download_rejects_missing_summary(app, tmp_path):
|
||||
"""summary 未标记可用时应 404。"""
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt_archives')
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt_archives')
|
||||
with app.app_context():
|
||||
run, _ = _make_receipt_run_with_file(
|
||||
schedule_no='SCH-RCP-ARCH-MISS',
|
||||
@@ -268,9 +268,9 @@ def test_receipt_attachment_stem_uses_local_timezone(app):
|
||||
def test_admin_can_download_receipt_raw_zip(app, client, admin_jwt_headers, tmp_path, monkeypatch):
|
||||
"""管理端 receipt-raw-zip 应返回 ZIP 与展示名。"""
|
||||
archive_dir = tmp_path / 'receipt_archives'
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(archive_dir)
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(archive_dir)
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.shipping_receipt_rpa_archive.file_asset_storage.get_bytes',
|
||||
'app.services.schedule.freight_inbound_rpa_archive.file_asset_storage.get_bytes',
|
||||
lambda _key: b'fake-receipt-xlsx',
|
||||
)
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ def test_inventory_callback_id_is_checked_before_attempt_identity(app):
|
||||
使失败回调(error_code)能通过身份校验并回写 callback_id。
|
||||
"""
|
||||
return {
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'schema_version': 'freight_rpa.onhand.v1',
|
||||
'callback_id': 'cb-unique',
|
||||
'task_no': task.task_no,
|
||||
'source_code': source_code,
|
||||
|
||||
Reference in new issue
Block a user