"""独立收料 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, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule with app.app_context(): dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() crane_profile = ShippingRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'}) crane = ShippingInventorySource( source_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', rpa_profile=crane_profile, parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True, ) empty_dbs = ShippingInventorySource( source_code='DSV360_EMPTY_QP', display_name='Empty QP', connector_type='dbs', rpa_profile=dbs.rpa_profile, parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template, warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', report_path_json={}, query_parameters_json=[], enabled=True, ) db.session.add_all([ crane, empty_dbs, ShippingReceiptReportConfig( inventory_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([ ShippingReceiptReportConfig( inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[], ), ShippingReceiptReportConfig( inventory_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-receipt-rpa', 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_receipt_rpa_job.write_receipt_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) # 关键断言:三源三单元;多值 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'] == 'shipping_receipt_rpa.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, 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 with app.app_context(): source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() db.session.add(ShippingReceiptReportConfig( inventory_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-receipt-rpa', 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_receipt_rpa_job.assert_receipt_rpa_worker_ready', lambda: (_ for _ in ()).throw(ServiceUnavailableError( RPA_WORKER_OFFLINE_MESSAGE, code='RPA.WORKER_OFFLINE', details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'receipt worker offline'}, )), ) monkeypatch.setattr( 'app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger', lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json', ) total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run) # [断言意图] fail-fast:计 failed、不入库 unit、不写 trigger、不进入 awaiting。 assert (total, success, failed, skipped) == (1, 0, 1, 0) assert details == [] assert errors == ['receipt worker offline'] assert trigger_calls == [] assert ShippingReceiptRpaUnitRun.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_receipt_rpa' for log in logs ) def test_receipt_schedule_options_only_return_enabled_configured_sources(app): """动态排程选项只暴露库存站点已启用且已配置收料的站点。""" from app import db from app.models import ShippingInventorySource, ShippingReceiptReportConfig from app.services.schedule.job_options import list_job_options with app.app_context(): source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() db.session.add(ShippingReceiptReportConfig( inventory_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('shipping_receipt_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, ShippingInventorySource, ShippingReceiptRpaUnitRun from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs with app.app_context(): app.config['FREIGHT_RPA_RECEIPT_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 * * *') 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() unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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_receipt_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.RECEIPT_CALLBACK_TIMEOUT' assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0 assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_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.shipping_notice.receipt_rpa import write_receipt_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'}], {}) assert path assert (tmp_path / 'receipt_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, ShippingInventorySource, ShippingReceiptRpaUnitRun from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs with app.app_context(): app.config['FREIGHT_RPA_RECEIPT_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 * * *') 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() db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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_receipt_rpa_schedule_runs() == 1 db.session.refresh(run) assert run.status == 'failed' assert run.response_summary_json.get('recovered_reason') == 'receipt_rpa_callback_timeout' 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 with app.app_context(): app.config['FREIGHT_RPA_RECEIPT_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 * * *') 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() # 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚) db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_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_receipt_rpa_schedule_runs() == 0 db.session.refresh(run) assert run.status == 'running' def test_receipt_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") # [断言意图] 调用点必须位于一次性分支竖旗之后(每轮维护区); # 回流旧写法(receipt_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。 assert source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") > marker_init assert "receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()" not in source