Files
syops/backend/tests/test_freight_receipt_rpa_schedule.py
hugo 911afa0f73 feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
2026-10-19 18:45:16 +08:00

339 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""独立收料 RPA 排程的单元口径和 trigger 契约测试。"""
from __future__ import annotations
from datetime import datetime, timedelta
def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, monkeypatch):
"""一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaProfile
from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule
with app.app_context():
dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
crane_profile = FreightRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'})
# s18 起站点行不再承载解析绑定/报表路径/查询条件;入站排程只读 FreightRpaInboundReportConfig。
crane = FreightRpaSource(
source_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', rpa_profile=crane_profile,
excel_template=dbs.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', enabled=True,
)
empty_dbs = FreightRpaSource(
source_code='DSV360_EMPTY_QP', display_name='Empty QP', connector_type='dbs', rpa_profile=dbs.rpa_profile,
excel_template=dbs.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', enabled=True,
)
db.session.add_all([
crane, empty_dbs,
FreightRpaInboundReportConfig(
source_id=dbs.id,
report_path_json={
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
},
query_parameters_json=[
{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False},
],
),
])
db.session.flush()
db.session.add_all([
FreightRpaInboundReportConfig(
source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[],
),
FreightRpaInboundReportConfig(
source_id=empty_dbs.id,
report_path_json={
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
},
query_parameters_json=[],
),
])
task = ScheduleTask(
schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job',
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()
run = ScheduleRun(run_no='RUN-RECEIPT-1', schedule_task_id=task.id, status='running')
db.session.add(run); db.session.commit()
captured = {}
monkeypatch.setattr(
'app.services.schedule.freight_rpa_inbound_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_rpa_inbound_schedule(task, run)
# 关键断言:三源三单元;多值 Warehouse 不拆;空 query_parameters 仍产出。
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'] == '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'
assert dbs_unit['login_url'] == 'https://test.invalid/dbs'
assert dbs_unit['credential_envelope'] == {
'username_ciphertext': None,
'password_ciphertext': None,
}
assert dbs_unit['report_path_json']['report_name'] == 'Receipt Detail'
assert dbs_unit['warehouse_id'] is None
# 关键断言:Warehouse 条件原样保留在单元快照,由 Worker 按参数填写或走页面默认。
assert dbs_unit['query_parameters_json'] == [
{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False},
]
empty_unit = next(item for item in captured['units'] if item['source_code'] == empty_dbs.source_code)
assert empty_unit['query_parameters_json'] == []
def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypatch):
"""收料 Worker 离线时排程立即 failed,不写 trigger、不落 unit。"""
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule
from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
db.session.add(FreightRpaInboundReportConfig(
source_id=source.id,
report_path_json={
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
},
query_parameters_json=[],
))
task = ScheduleTask(
schedule_no='SCH-RECEIPT-OFFLINE', name='Receipt offline', schedule_type='platform_job',
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)
db.session.flush()
run = ScheduleRun(run_no='RUN-RECEIPT-OFFLINE', schedule_task_id=task.id, status='running')
db.session.add(run)
db.session.commit()
trigger_calls = []
monkeypatch.setattr(
'app.services.schedule.freight_rpa_inbound_job.assert_inbound_rpa_worker_ready',
lambda: (_ for _ in ()).throw(ServiceUnavailableError(
RPA_WORKER_OFFLINE_MESSAGE,
code='RPA.WORKER_OFFLINE',
details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'inbound worker offline'},
)),
)
monkeypatch.setattr(
'app.services.schedule.freight_rpa_inbound_job.write_inbound_export_batch_trigger',
lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json',
)
total, success, failed, skipped, details, errors, logs = run_freight_rpa_inbound_schedule(task, run)
# [断言意图] fail-fast:计 failed、不入库 unit、不写 trigger、不进入 awaiting。
assert (total, success, failed, skipped) == (1, 0, 1, 0)
assert details == []
assert errors == ['inbound worker offline']
assert trigger_calls == []
assert FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0
failed_log = next(log for log in logs if isinstance(log, dict) and log.get('status') == 'failed')
assert failed_log['detail'].get('reasons') == ['no_worker_heartbeat']
assert not any(
isinstance(log, dict) and log.get('status') == 'awaiting_inbound_rpa_callback'
for log in logs
)
def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
"""动态排程选项只暴露库存站点已启用且已配置收料的站点。"""
from app import db
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
from app.services.schedule.job_options import list_job_options
with app.app_context():
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
db.session.add(FreightRpaInboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'},
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['A'], 'required': False, 'select_all': False}],
))
db.session.commit()
options = list_job_options('freight_rpa_inbound_sources')
assert any(item['value'] == source.source_code for item in options)
def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
"""无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_stale_inbound_rpa_schedule_runs
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = FreightRpaSource.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-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_inbound_rpa': True})
db.session.add(run); db.session.flush()
unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={})
db.session.add(unit); db.session.commit()
assert recover_stale_inbound_rpa_schedule_runs(task) == 1
db.session.refresh(run); db.session.refresh(unit)
assert run.status == 'failed'
assert unit.status == 'failed'
assert unit.error_code == 'RPA.INBOUND_CALLBACK_TIMEOUT'
assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0
assert ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1
def test_receipt_trigger_is_published_atomically(app, tmp_path):
"""Worker 只能观察到完整 JSON;临时写入文件不会匹配其 *.json 扫描。"""
from app.services.freight_rpa.inbound.trigger_io import write_inbound_export_batch_trigger
with app.app_context():
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 / 'inbound_export_batch_RUN-ATOMIC.json').exists()
assert not list(tmp_path.glob('.*.tmp'))
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, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_inbound_rpa_schedule_runs
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = FreightRpaSource.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-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_inbound_rpa': True})
db.session.add(run); db.session.flush()
db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={}))
db.session.commit()
# [断言意图] 全量扫描不依赖 task 入参、进程重启或同排程再次执行(点B 修复口径);
# 超时窗(60s)过后扫描即收口为 failed 并写 recovered_reason。
assert recover_all_stale_inbound_rpa_schedule_runs() == 1
db.session.refresh(run)
assert run.status == 'failed'
assert run.response_summary_json.get('recovered_reason') == 'inbound_rpa_callback_timeout'
def test_inbound_recovery_respects_fresh_activity_of_long_batch(app):
"""长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_inbound_rpa_schedule_runs
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = FreightRpaSource.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-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_inbound_rpa': True})
db.session.add(run); db.session.flush()
# 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚)
db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30)))
db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45)))
db.session.commit()
# [断言意图] run.started_at(30min 前) 已远超 60s 窗,但最后活动仅 30~45s——
# 笔间静默口径下健康长批次必须不被回收(旧口径按 started_at 会误杀)。
assert recover_all_stale_inbound_rpa_schedule_runs() == 0
db.session.refresh(run)
assert run.status == 'running'
def test_inbound_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
"""哨兵回归:收料超时对账必须挂在每轮领取维护区,不得回流启动一次性分支。"""
import inspect
from app.services.schedule import queue_service
source = inspect.getsource(queue_service)
marker_init = source.index("_worker_initialized = True")
# [断言意图] 调用点必须位于一次性分支竖旗之后(每轮维护区);
# 回流旧写法(inbound_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。
assert source.index("inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()") > marker_init
assert "inbound_recovered = recover_all_stale_inbound_rpa_schedule_runs()" not in source
def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
"""按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。"""
from app import db
from app.models import ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
# 单元1:排队 5 分钟从未被领取(created_at 为锚,queued 分支);单元2:领取后
# 静默 5 分钟(started_at 为锚);单元3:30 秒前刚领取(健康在跑,不得误杀)。
stale_queued = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-queued', status='queued', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(minutes=5),
)
stale_processing = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-processing', status='processing', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(minutes=6),
started_at=datetime.utcnow() - timedelta(minutes=5),
)
fresh_processing = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source.source_code, connector_type='dbs',
callback_id='inbound-orphan-fresh', status='processing', config_snapshot_json={},
created_at=datetime.utcnow() - timedelta(seconds=45),
started_at=datetime.utcnow() - timedelta(seconds=30),
)
db.session.add_all([stale_queued, stale_processing, fresh_processing])
db.session.commit()
# [断言意图] 调拨工作台按需触发单元 schedule_run_id=NULL,不在 run 级扫描
# (recover_all_stale_inbound_rpa_schedule_runs 按 run 遍历)范围内;网页异常
# 关闭后回调永不到达,必须由本扫描终态化(2026-10-16 事故回归),健康单元原样;
# 与 run 级回收同口径:只标失败、写审计,绝不自动创建重试单元。
assert recover_all_stale_orphan_inbound_units() == 2
db.session.refresh(stale_queued)
db.session.refresh(stale_processing)
db.session.refresh(fresh_processing)
assert stale_queued.status == 'failed'
assert stale_queued.error_code == 'RPA.INBOUND_CALLBACK_TIMEOUT'
assert stale_queued.finished_at is not None
assert stale_processing.status == 'failed'
assert fresh_processing.status == 'processing'
assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=stale_queued.id).count() == 0
# [断言意图] 审计须含失败结果与 before/after 快照——与 run 级回收同语义由测试锁定。
timeout_event = ShippingAuditEvent.query.filter_by(
event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(stale_queued.id),
).one()
assert timeout_event.result == 'failure'
assert (timeout_event.after_snapshot_json or {}).get('status') == 'failed'
def test_orphan_inbound_recovery_is_wired_into_per_tick_maintenance():
"""哨兵回归:孤儿单元回收必须挂在每轮领取维护区(与 run 级扫描同区同轮)。"""
import inspect
from app.services.schedule import queue_service
source = inspect.getsource(queue_service)
# [断言意图] 调用点必须与 run 级收料扫描同在每轮维护区且在其后;
# 缺席或回流启动一次性分支都会复现「长驻进程期间来源永久 fetching」事故。
marker_run_scan = source.index("inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()")
assert source.index("recover_all_stale_orphan_inbound_units()") > marker_run_scan