feat(schedule): 新增平台任务参数契约与动态选项支持

This commit is contained in:
hugo committed 2026-07-09 13:19:36 +08:00
1 parent 2ce1aca023
commit 8b5b0b49bf
76 files changed
+7103 -1203

No files matched your search

+45
View File
@@ -156,3 +156,48 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
assert any(item.get("event") == "run.failed" for item in events)
def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, monkeypatch, tmp_path):
"""multipart 上传发货通知时,agent_id 应从 form 字段解析,而非 JSON body。"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
monkeypatch.setattr(
"app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
lambda **kwargs: {
"status": "ok",
"batch_no": "SB-MULTIPART-001",
"data": {
"tasks": [{"task_id": "SN-MULTIPART-001"}],
"focus_task": {"task_no": "SN-MULTIPART-001"},
},
},
)
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role},
data={
"agent_id": str(agent.id),
"input": json.dumps(
{
"type": "upload_followup",
"display_text": "上传发货通知:notice.txt",
"action_type": "shipping.create_batch_from_notices",
"payload": {},
},
ensure_ascii=False,
),
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
},
content_type="multipart/form-data",
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
event_names = [item.get("event") for item in events]
assert "run.started" in event_names
assert "run.completed" in event_names
assert "run.failed" not in event_names
+63 -2
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import importlib.util
import json
import os
import sys
from pathlib import Path
import pytest
@@ -60,13 +61,73 @@ def test_env_strips_wrapping_quotes(monkeypatch):
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
worker = _load_freight_rpa_worker()
monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", '"htcus@hoo-thai.com"')
monkeypatch.setenv("FREIGHT_RPA_DSV_USERNAME", '"user@example.com"')
monkeypatch.setenv("FREIGHT_RPA_DSV_PASSWORD", "'secret-pass'")
assert worker._env("FREIGHT_RPA_DSV_USERNAME") == "htcus@hoo-thai.com"
assert worker._env("FREIGHT_RPA_DSV_USERNAME") == "user@example.com"
assert worker._env("FREIGHT_RPA_DSV_PASSWORD") == "secret-pass"
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
"""配置 FREIGHT_RPA_LOG_FILE 后,stdout/stderr 应同时写入日志文件。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "logs" / "worker.log"
monkeypatch.setenv("FREIGHT_RPA_LOG_FILE", str(log_path))
original_stdout = sys.stdout
original_stderr = sys.stderr
try:
resolved = worker._configure_file_logging()
print("hello stdout")
print("hello stderr", file=sys.stderr)
finally:
sys.stdout.flush()
sys.stderr.flush()
sys.stdout = original_stdout
sys.stderr = original_stderr
captured = capsys.readouterr()
assert resolved == log_path
assert "hello stdout" in captured.out
assert "hello stderr" in captured.err
text = log_path.read_text(encoding="utf-8")
assert "[logging] tee enabled" in text
assert "hello stdout" in text
assert "hello stderr" in text
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
"""日志超过 FREIGHT_RPA_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
Path(f"{log_path}.1").write_text("old-1", encoding="utf-8")
monkeypatch.setenv("FREIGHT_RPA_LOG_MAX_BYTES", "1")
monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "2")
worker._rotate_log_file_if_needed(log_path)
assert not log_path.exists()
assert Path(f"{log_path}.1").read_text(encoding="utf-8") == "current-log"
assert Path(f"{log_path}.2").read_text(encoding="utf-8") == "old-1"
def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp_path):
"""备份数量为 0 时,超过大小的当前日志应直接删除。"""
worker = _load_freight_rpa_worker()
log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8")
monkeypatch.setenv("FREIGHT_RPA_LOG_MAX_BYTES", "1")
monkeypatch.setenv("FREIGHT_RPA_LOG_BACKUP_COUNT", "0")
worker._rotate_log_file_if_needed(log_path)
assert not log_path.exists()
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
worker = _load_freight_rpa_worker()
+13 -1
View File
@@ -38,6 +38,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
db.session.commit()
run_no = run.run_no
task_id = task.id
run_id = run.id
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
@@ -46,9 +47,20 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
)
assert resp.status_code == 200
body = resp.get_json()
assert body["summary"]["success_count"] >= 1
assert body["summary"]["success_count"] == 0
assert body["summary"]["total_count"] >= 1
assert body.get("awaiting_rpa_callback") is True
assert list(trigger_dir.glob("inventory_export_batch_*.json"))
with app.app_context():
from app import db
refreshed = db.session.get(ScheduleRun, run_id)
assert refreshed is not None
assert refreshed.status == "running"
assert refreshed.finished_at is None
assert (refreshed.response_summary_json or {}).get("awaiting_rpa") is True
def test_internal_job_unknown_key_returns_404(client):
"""未注册 job key 应返回 404。"""
+32
View File
@@ -154,3 +154,35 @@ def test_post_and_patch_schedule_reject_non_object_config(app, client, admin_jwt
'config': 'not-an-object',
})
assert patch_res.status_code == 400
def test_patch_schedule_creates_config_for_task_without_config(app, client, admin_jwt_headers):
"""PATCH 为尚无 config 的排程写入 config 应成功,不因主键序列漂移 500。"""
with app.app_context():
owner = _mk_user('cfg_create_owner_u', 'cfg_create_owner@example.com')
db.session.commit()
owner_id = owner.id
create_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'config-create-schedule',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 4 * * *',
})
assert create_res.status_code == 201
task_id = create_res.get_json()['id']
patch_res = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'config': {
'row_id_key': 'id',
'data_source': {'db_type': 'sqlserver'},
},
})
assert patch_res.status_code == 200
cfg_res = client.get(f'/api/admin/schedule-config/{task_id}', headers=admin_jwt_headers)
assert cfg_res.status_code == 200
cfg_body = cfg_res.get_json()
assert cfg_body['config'] is not None
assert cfg_body['config']['row_id_key'] == 'id'
+41 -13
View File
@@ -188,19 +188,47 @@ def test_common_executor_in_process_without_base_url(app, monkeypatch):
def test_get_platform_jobs_api(client, admin_jwt_headers):
"""GET /api/admin/schedule/platform-jobs 应返回 registry 列表及 label_key。"""
res = client.get("/api/admin/schedule/platform-jobs", headers=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 "faq-aggregate-hot" in keys
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["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
"""GET /api/admin/schedule/platform-jobs 应返回启用中的 registry 列表及 label_key。"""
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
)
# 临时注册 disabled job,验证下拉接口与 definitions 一样只返回 enabled
register_platform_job(PlatformJobDefinition(
key='disabled-for-filter-test',
label='disabled job',
handler=lambda task, run: (0, 0, 0, 0, [], [], []),
enabled=False,
))
try:
res = client.get("/api/admin/schedule/platform-jobs", headers=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 "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["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
defs = client.get("/api/admin/platform-tasks/definitions", headers=admin_jwt_headers)
assert defs.status_code == 200
def_keys = {item["task_type"] for item in defs.get_json()["data"]}
assert "disabled-for-filter-test" not in def_keys
# 两个接口的启用集合应对齐
assert keys == def_keys
finally:
# 清掉临时注册项,避免污染其他用例
from app.services.schedule import job_registry as jr
jr._REGISTRY.pop('disabled-for-filter-test', None)
assert get_platform_job('disabled-for-filter-test') is None
def test_schedule_config_rejects_data_source_type_for_platform_job(client, admin_jwt_headers, app):
@@ -0,0 +1,548 @@
"""
backend/tests/test_schedule_platform_tasks.py
用途:平台任务契约中心测试(definitions/options 接口、job_params schema 校验、handler 参数读取)。
依赖:conftest 的 app/client fixture、job_registry、job_params、job_options。
逻辑:覆盖 schema 下发、动态选项、保存期校验(必填/类型/未知字段/选项范围/_advanced)、
执行期回退(job_params 优先、legacy 字段兜底)。
"""
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ScheduleTask, User
from app.services.schedule.job_params import (
ADVANCED_PARAMS_KEY,
JobParamsValidationError,
validate_task_params,
)
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT。"""
with app.app_context():
user = db.session.query(User).filter_by(username='admin').first()
if not user:
user = User(
username='admin',
email='admin@example.com',
role='admin',
status='active',
)
user.set_password('admin')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
# ---------- definitions / options 接口 ----------
def test_platform_task_definitions_returns_params_schema(client, admin_jwt_headers):
"""definitions 接口应下发注册表完整契约(task_type/label/params_schema/defaults)。"""
res = client.get('/api/admin/platform-tasks/definitions', headers=admin_jwt_headers)
assert res.status_code == 200
body = res.get_json()
# 统一 envelope:success + data
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']
assert rpa['category'] == 'shipping'
schema_keys = {f['key']: f for f in rpa['params_schema']}
assert schema_keys['source_codes']['type'] == 'multi_select'
assert schema_keys['source_codes']['options_source'] == 'shipping_inventory_sources'
assert rpa['defaults'] == {'source_codes': []}
# FAQ 热点聚合:select 应用字段
faq = by_type['faq-aggregate-hot']
faq_fields = {f['key']: f for f in faq['params_schema']}
assert faq_fields['app_id']['type'] == 'select'
assert faq_fields['app_id']['options_source'] == 'agent_apps'
# 无参数任务 params_schema 为空列表
assert by_type['fixed-assets-snapshot']['params_schema'] == []
def test_platform_task_options_shipping_sources(client, admin_jwt_headers, app):
"""options 接口应返回库存源统一 label/value 结构。"""
res = client.get(
'/api/admin/platform-tasks/options?source=shipping_inventory_sources',
headers=admin_jwt_headers,
)
assert res.status_code == 200
body = res.get_json()
assert body['success'] is True
options = body['data']
assert options, 'expected at least one enabled inventory source'
assert all('label' in item and 'value' in item for item in options)
values = {item['value'] for item in options}
assert 'DSV360_AWSBI_BYAWSATL01' in values
def test_platform_task_options_unknown_source_rejected(client, admin_jwt_headers):
"""未登记的 options_source 应 400;缺 source 参数同样 400。"""
res = client.get('/api/admin/platform-tasks/options?source=not_a_source', headers=admin_jwt_headers)
assert res.status_code == 400
res2 = client.get('/api/admin/platform-tasks/options', headers=admin_jwt_headers)
assert res2.status_code == 400
# ---------- validate_task_params 校验 ----------
def test_validate_task_params_fills_defaults(app):
"""未提供字段应回填注册表默认值。"""
with app.app_context():
result = validate_task_params('shipping-inventory-rpa', {}, check_options=False)
assert result == {'source_codes': []}
result_faq = validate_task_params('faq-aggregate-hot', {}, check_options=False)
assert result_faq == {'app_id': None}
def test_validate_task_params_rejects_unknown_key(app):
"""未声明字段默认拒绝,防止参数漂移。"""
with app.app_context():
with pytest.raises(JobParamsValidationError, match='unknown params'):
validate_task_params('faq-aggregate-hot', {'foo': 1}, check_options=False)
def test_validate_task_params_rejects_wrong_type(app):
"""multi_select 传入非 list 应报类型错误。"""
with app.app_context():
with pytest.raises(JobParamsValidationError, match='list of option values'):
validate_task_params(
'shipping-inventory-rpa',
{'source_codes': 'DSV360_AWSBI_BYAWSATL01'},
check_options=False,
)
def test_validate_task_params_checks_option_range(app):
"""check_options=True 时,multi_select 值不在选项范围内应报错。"""
with app.app_context():
with pytest.raises(JobParamsValidationError, match='not in options'):
validate_task_params(
'shipping-inventory-rpa',
{'source_codes': ['NOT_A_REAL_SOURCE']},
check_options=True,
)
# 合法值应通过
result = validate_task_params(
'shipping-inventory-rpa',
{'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
check_options=True,
)
assert result['source_codes'] == ['DSV360_AWSBI_BYAWSATL01']
def test_validate_task_params_passes_advanced_through(app):
"""_advanced 高级 JSON 区域应原样透传(历史/特殊任务兜底)。"""
with app.app_context():
result = validate_task_params(
'shipping-inventory-rpa',
{'source_codes': [], ADVANCED_PARAMS_KEY: {'timeout_seconds': 300}},
check_options=False,
)
assert result[ADVANCED_PARAMS_KEY] == {'timeout_seconds': 300}
def test_validate_task_params_unknown_job(app):
"""未注册任务直接报错。"""
with app.app_context():
with pytest.raises(JobParamsValidationError, match='Unknown platform job'):
validate_task_params('not-a-job', {}, check_options=False)
# ---------- 保存排程时的 API 校验 ----------
def _create_platform_schedule(client, headers, owner_id, *, job_params=None, extra=None):
"""POST /schedules 创建 platform_job 排程的公共入口。"""
payload = {
'name': 'contract test',
'schedule_type': 'platform_job',
'platform_api_path': 'shipping-inventory-rpa',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
}
if job_params is not None:
payload['job_params'] = job_params
if extra:
payload.update(extra)
return client.post('/api/admin/schedules', headers=headers, json=payload)
@pytest.fixture
def owner_id(app):
"""普通用户作为排程 owner。"""
with app.app_context():
user = User(username='pt_owner', email='pt_owner@example.com')
db.session.add(user)
db.session.commit()
return user.id
def test_post_schedule_persists_valid_job_params(client, admin_jwt_headers, owner_id, app):
"""合法 job_params 应持久化并出现在 serialize_task 响应中。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
assert res.status_code == 201
body = res.get_json()
assert body['job_params'] == {'source_codes': ['DSV360_AWSBI_BYAWSATL01']}
with app.app_context():
task = db.session.get(ScheduleTask, body['id'])
assert task.job_params == {'source_codes': ['DSV360_AWSBI_BYAWSATL01']}
def test_post_schedule_without_job_params_applies_schema_defaults(client, admin_jwt_headers, owner_id, app):
"""platform_job 未传 job_params 时仍应按 schema 校验并回填默认值,不可绕过契约。"""
res = _create_platform_schedule(client, admin_jwt_headers, owner_id)
assert res.status_code == 201
body = res.get_json()
assert body['job_params'] == {'source_codes': []}
with app.app_context():
task = db.session.get(ScheduleTask, body['id'])
assert task.job_params == {'source_codes': []}
def test_post_fixed_assets_snapshot_without_job_params_stays_none(client, admin_jwt_headers, owner_id, app):
"""无 params_schema 的 platform_job 仍允许 job_params 为 None。"""
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'fixed assets cron',
'schedule_type': 'platform_job',
'platform_api_path': 'fixed-assets-snapshot',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert res.status_code == 201
body = res.get_json()
assert body['job_params'] is None
def test_post_schedule_rejects_invalid_job_params(client, admin_jwt_headers, owner_id):
"""非法 job_params(选项范围外 / 未知字段 / 非对象)应 400。"""
assert _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['NOT_EXIST']},
).status_code == 400
assert _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'unknown_field': 1},
).status_code == 400
assert _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params=[1, 2],
).status_code == 400
def test_post_data_pipeline_rejects_job_params(client, admin_jwt_headers, owner_id):
"""data_pipeline 携带 job_params 应 400(参数契约仅属于平台任务)。"""
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'pipeline with job_params',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
'job_params': {'source_codes': []},
})
assert res.status_code == 400
def test_patch_schedule_updates_and_clears_job_params(client, admin_jwt_headers, owner_id, app):
"""PATCH 应支持更新;显式 null 对有 schema 的任务重置为默认值。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
task_id = res.get_json()['id']
res2 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'job_params': {'source_codes': []},
})
assert res2.status_code == 200
assert res2.get_json()['job_params'] == {'source_codes': []}
res3 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'job_params': None,
})
assert res3.status_code == 200
assert res3.get_json()['job_params'] == {'source_codes': []}
def test_patch_platform_api_path_resets_job_params_to_new_defaults(client, admin_jwt_headers, owner_id, app):
"""切换 platform_api_path 且未传 job_params 时,应按新任务 schema 重置,避免旧参数残留。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
task_id = res.get_json()['id']
res2 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'platform_api_path': 'faq-aggregate-hot',
})
assert res2.status_code == 200
body = res2.get_json()
assert body['platform_api_path'] == 'faq-aggregate-hot'
assert body['job_params'] == {'app_id': None}
with app.app_context():
task = db.session.get(ScheduleTask, task_id)
assert task.job_params == {'app_id': None}
def test_patch_platform_api_path_to_schemaless_clears_job_params(client, admin_jwt_headers, owner_id, app):
"""切换到无 params_schema 的平台任务且未传 job_params 时应清空旧参数。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
task_id = res.get_json()['id']
res2 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'platform_api_path': 'fixed-assets-snapshot',
})
assert res2.status_code == 200
body = res2.get_json()
assert body['platform_api_path'] == 'fixed-assets-snapshot'
assert body['job_params'] is None
def test_patch_platform_api_path_with_explicit_job_params_keeps_payload(client, admin_jwt_headers, owner_id):
"""切换 platform_api_path 同时显式传 job_params 时,应保留请求体参数(经新 schema 校验)。"""
res = _create_platform_schedule(
client, admin_jwt_headers, owner_id,
job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']},
)
task_id = res.get_json()['id']
res2 = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'platform_api_path': 'faq-aggregate-hot',
'job_params': {'app_id': None},
})
assert res2.status_code == 200
assert res2.get_json()['job_params'] == {'app_id': None}
# ---------- 执行链路参数读取 ----------
def test_faq_job_prefers_job_params_over_dify_agent_id(app):
"""FAQ handler 应优先读 job_params.app_id,历史任务回退 dify_agent_id。"""
from app.services.schedule.faq_hot_aggregate_job import _resolve_agent_filter
with app.app_context():
task = ScheduleTask(job_params={'app_id': 7}, dify_agent_id=3)
assert _resolve_agent_filter(task) == 7
legacy = ScheduleTask(job_params=None, dify_agent_id=3)
assert _resolve_agent_filter(legacy) == 3
empty = ScheduleTask(job_params={'app_id': None}, dify_agent_id=None)
assert _resolve_agent_filter(empty) is None
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
with app.app_context():
task = ScheduleTask(job_params={'source_codes': ['DSV360_AWSBI_BYAWSATL01']})
sources = _filter_sources(task)
assert [item.get('source_code') for item in sources] == ['DSV360_AWSBI_BYAWSATL01']
# job_params 为空(默认值)时不筛选 → 返回全部启用源
task_all = ScheduleTask(job_params={'source_codes': []})
assert len(_filter_sources(task_all)) >= 1
def test_run_platform_job_writes_normalized_job_params(app):
"""执行前 validate_task_params 的归一化结果应写回 task.job_params 供 handler 读取。"""
from app.models import ScheduleRun
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
run_platform_job,
)
original = get_platform_job('faq-aggregate-hot')
seen: dict = {}
def _fake_handler(task, _run):
seen['params'] = dict(task.job_params)
return 0, 0, 0, 0, [], [], []
register_platform_job(PlatformJobDefinition(
key=original.key,
label=original.label,
handler=_fake_handler,
description=original.description,
label_key=original.label_key,
description_key=original.description_key,
category=original.category,
enabled=original.enabled,
params_schema=original.params_schema,
defaults=original.defaults,
))
try:
with app.app_context():
task = ScheduleTask(
schedule_no='SCH-NORM-001',
name='norm params',
schedule_type='platform_job',
platform_api_path='faq-aggregate-hot',
owner_user_id=1,
cron_expr='0 3 * * *',
job_params={},
)
run = ScheduleRun(run_no='RUN-NORM-001', schedule_task_id=1, status='running')
run_platform_job('faq-aggregate-hot', task, run, {})
assert seen['params'] == {'app_id': None}
assert task.job_params == {'app_id': None}
finally:
register_platform_job(original)
def test_disabled_platform_job_rejected_by_contract_and_run(app, client, admin_jwt_headers, owner_id):
"""enabled=False 表示任务停用:契约校验拒绝创建/改指向,执行入口也拒绝。"""
from app.models import ScheduleRun
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
run_platform_job,
)
from app.services.schedule.schedule_contract import validate_schedule_fields
register_platform_job(PlatformJobDefinition(
key='disabled-contract-job',
label='disabled contract job',
handler=lambda task, run: (0, 0, 0, 0, [], [], []),
enabled=False,
))
try:
with app.app_context():
with pytest.raises(ValueError, match='disabled'):
validate_schedule_fields(
schedule_type='platform_job',
data_source_type=None,
platform_api_path='disabled-contract-job',
)
task = ScheduleTask(
schedule_no='SCH-DIS-001',
name='disabled job run',
schedule_type='platform_job',
platform_api_path='disabled-contract-job',
owner_user_id=1,
cron_expr='0 3 * * *',
)
run = ScheduleRun(run_no='RUN-DIS-001', schedule_task_id=1, status='running')
with pytest.raises(ValueError, match='disabled'):
run_platform_job('disabled-contract-job', task, run, {})
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'create disabled job',
'schedule_type': 'platform_job',
'platform_api_path': 'disabled-contract-job',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert res.status_code == 400
body = res.get_json() or {}
err = body.get('error')
msg = err.get('message') if isinstance(err, dict) else (err or body.get('message') or '')
assert 'disabled' in str(msg).lower()
finally:
from app.services.schedule import job_registry as jr
jr._REGISTRY.pop('disabled-contract-job', None)
assert get_platform_job('disabled-contract-job') is None
def test_platform_job_allows_config_respects_enabled(app):
"""
白名单 job 被 enabled=False 后,platform_job_allows_config 也应为 False,
避免 /schedule-config 继续写入已停用任务的 ScheduleTaskConfig。
"""
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
)
from app.services.schedule.schedule_contract import (
PLATFORM_JOBS_ALLOWING_CONFIG,
platform_job_allows_config,
)
# 选取一个已在白名单中的 key;若 registry 原本 enabled,临时改为 False
whitelist_key = next(iter(PLATFORM_JOBS_ALLOWING_CONFIG))
original = get_platform_job(whitelist_key)
assert original is not None, f'expected {whitelist_key} registered'
assert platform_job_allows_config(whitelist_key) is True
register_platform_job(PlatformJobDefinition(
key=whitelist_key,
label=original.label,
handler=original.handler,
enabled=False,
params_schema=list(original.params_schema or []),
defaults=dict(original.defaults or {}),
))
try:
with app.app_context():
assert platform_job_allows_config(whitelist_key) is False
with pytest.raises(ValueError, match='does not accept ScheduleTaskConfig'):
from app.services.schedule.schedule_contract import assert_schedule_config_writable
assert_schedule_config_writable(
schedule_type='platform_job',
platform_api_path=whitelist_key,
config={'fetch_sql': 'SELECT 1'},
)
finally:
register_platform_job(original)
assert platform_job_allows_config(whitelist_key) is True
def test_enable_rejects_disabled_platform_job(client, admin_jwt_headers, owner_id, app):
"""
既有 platform_job 排程在 registry job 被停用后,/enable 应拒绝重新入队。
避免 cron 到点才在运行阶段失败。
"""
from app.services.schedule.job_registry import (
PlatformJobDefinition,
get_platform_job,
register_platform_job,
)
job_key = 'shipping-inventory-rpa'
original = get_platform_job(job_key)
assert original is not None
res = _create_platform_schedule(client, admin_jwt_headers, owner_id)
assert res.status_code == 201
task_id = res.get_json()['id']
disable_res = client.post(f'/api/admin/schedules/{task_id}/disable', headers=admin_jwt_headers)
assert disable_res.status_code == 200
register_platform_job(PlatformJobDefinition(
key=job_key,
label=original.label,
handler=original.handler,
enabled=False,
params_schema=list(original.params_schema or []),
defaults=dict(original.defaults or {}),
))
try:
enable_res = client.post(f'/api/admin/schedules/{task_id}/enable', headers=admin_jwt_headers)
assert enable_res.status_code == 400
body = enable_res.get_json() or {}
err = body.get('error')
msg = err.get('message') if isinstance(err, dict) else (err or body.get('message') or '')
assert 'disabled' in str(msg).lower()
with app.app_context():
task = db.session.get(ScheduleTask, task_id)
assert task is not None
assert task.enabled is False
finally:
register_platform_job(original)
@@ -505,8 +505,8 @@ def test_workspace_create_batch_from_notices_rejects_all_failed_files_without_cr
assert res.status_code == 400
payload = res.get_json()
assert payload["success"] is False
assert payload["error"]["message"] == "all uploaded files failed extraction or contained no parseable text"
assert payload["error"]["details"]["rejected_files"] == [
assert payload["error"]["message"] == "未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试"
assert payload["error"]["details"]["file_summary"]["rejected_files"] == [
{
"filename": "notice-a.pdf",
"source_type": "pdf",
@@ -1,7 +1,71 @@
"""shipping_notice 库存 RPA 定时排程 executor 测试。"""
"""
backend/tests/test_shipping_notice_inventory_schedule.py
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
用途:货代库存 RPA 排程 executor、defer/finalize 契约与 source 过滤单测。
依赖:ScheduleTask/ScheduleRun、shipping_inventory_rpa_job、shipping_inventory_rpa_finalize。
逻辑:覆盖 trigger 写入、awaiting 终态、回调 finalize、超时回收。
"""
from datetime import datetime, timedelta
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 (
_build_finalize_details,
_compute_run_status,
is_awaiting_rpa_schedule_run,
recover_all_stale_awaiting_rpa_schedule_runs,
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 (
_filter_sources,
run_shipping_inventory_rpa_schedule,
)
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
def _make_inventory_schedule_task(
*,
schedule_no: str,
username: str,
api_body_template: str | None = None,
) -> ScheduleTask:
"""
构造带/不带 api_body_template 的库存 RPA 排程任务。
Args:
schedule_no: 排程编号
username: 唯一用户名
api_body_template: 可选 JSON 文本
Returns:
已 flush 的 ScheduleTask
"""
user = User(username=username, email=f"{username}@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no=schedule_no,
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(task)
db.session.flush()
if api_body_template is not None:
db.session.add(
ScheduleTaskConfig(
schedule_task_id=task.id,
api_body_template=api_body_template,
)
)
db.session.flush()
db.session.refresh(task)
return task
def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
@@ -11,23 +75,10 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
user = User(username="schedule_inv_user", email="schedule_inv_user@example.com")
from app import db
db.session.add(user)
db.session.flush()
task = ScheduleTask(
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-001",
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
username="schedule_inv_user",
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no="RUN20260707030000",
schedule_task_id=task.id,
@@ -38,6 +89,522 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
total, success, failed, skipped, details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
assert total >= 1
assert success >= 1
assert success == 0
assert failed == 0
assert skipped == 0
assert any(
isinstance(log, dict) and log.get("status") == "awaiting_rpa_callback"
for log in logs
)
assert list(trigger_dir.glob("inventory_export_batch_*.json"))
assert any(item.get("source_code") for item in details)
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_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-DEFER",
username="schedule_inv_defer_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
db.session.commit()
result = run_task_now(task, trigger_type="manual", triggered_by_user_id=None)
assert result.status == "running"
assert result.finished_at is None
assert result.success_count == 0
assert result.total_count == 1
assert (result.response_summary_json or {}).get("awaiting_rpa") is True
assert result.excel_file_data is None
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_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-STARTED-AT",
username="schedule_inv_started_at_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260709080400",
schedule_task_id=task.id,
status="running",
started_at=None,
)
db.session.add(run)
db.session.commit()
run_task_now(task, trigger_type="manual", triggered_by_user_id=None, run=run)
db.session.refresh(run)
assert run.started_at is not None
assert run.status == "running"
recovered = recover_stale_awaiting_rpa_schedule_runs(task)
assert recovered == 0
def test_recover_all_stale_awaiting_on_startup(app):
"""全局回收应清理已超时的 awaiting run。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-GLOBAL-RECOVER",
username="schedule_inv_global_recover_user",
)
run = ScheduleRun(
run_no="RUN20260709080500",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow() - timedelta(seconds=1200),
response_summary_json={"awaiting_rpa": True},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
assert recovered == 1
db.session.refresh(run)
assert run.status == "failed"
def test_recover_all_skips_non_inventory_rpa_task(app):
"""全局回收不应误杀非货代库存 RPA 任务上复用 awaiting_rpa 的 run。"""
with app.app_context():
user = User(username="other_await_user", email="other_await@x.com")
db.session.add(user)
db.session.flush()
other_task = ScheduleTask(
schedule_no="SCH-OTHER-AWAIT",
name="other",
schedule_type="platform_job",
platform_api_path="faq-hot-aggregate",
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(other_task)
db.session.flush()
run = ScheduleRun(
run_no="RUN20260709080550",
schedule_task_id=other_task.id,
status="running",
started_at=datetime.utcnow() - timedelta(seconds=1200),
response_summary_json={"awaiting_rpa": True},
step_logs=[{"step": "other", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
assert recovered == 0
db.session.refresh(run)
assert run.status == "running"
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_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_excel_fail.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
def _excel_boom(*_args, **_kwargs):
raise RuntimeError("excel exploded")
monkeypatch.setattr(
"app.services.schedule.shipping_inventory_rpa_finalize.export_schedule_result_excel",
_excel_boom,
)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-EXCEL-FAIL",
username="schedule_inv_excel_fail_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260709080700",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"display_name": "ATL01",
}],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
})
db.session.refresh(run)
assert run.status == "partial_failed"
assert run.failed_count == 0
assert run.error_message
assert "Excel" in run.error_message
assert (run.response_summary_json or {}).get("excel_export_status") == "failed"
assert (run.response_summary_json or {}).get("excel_failed") is True
assert (run.response_summary_json or {}).get("rpa_finalize", {}).get("excel_failed") is True
assert not run.excel_file_data
def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeypatch):
"""finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_fail_finalize.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
def _boom(*_args, **_kwargs):
raise RuntimeError("finalize exploded")
monkeypatch.setattr(
"app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details",
_boom,
)
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FINALIZE-FAIL",
username="schedule_inv_finalize_fail_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260709080600",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"display_name": "ATL01",
}],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
result = rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
})
db.session.refresh(run)
assert run.status == "running"
assert (run.response_summary_json or {}).get("awaiting_rpa") is True
assert (run.response_summary_json or {}).get("schedule_finalize_status") == "failed"
assert result["data"]["schedule_finalize_status"] == "failed"
assert result["data"].get("schedule_finalize_manual_retryable") is True
def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
"""RPA 回调后应终态化排程 run 并生成 Excel。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
processed_dir = drop_dir / "processed"
processed_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_sample.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FINALIZE",
username="schedule_inv_finalize_user",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
run = ScheduleRun(
run_no="RUN20260709080000",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"display_name": "ATL01",
}],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "DSV360_AWSBI_BYAWSATL01",
"warehouse_id": "BYAWSATL01",
"success": True,
"file_path": str(sample),
}],
})
db.session.refresh(run)
assert run.status == "success"
assert run.finished_at is not None
assert run.success_count == 1
assert run.failed_count == 0
assert run.excel_file_data
assert (run.response_summary_json or {}).get("awaiting_rpa") is False
def test_recover_stale_awaiting_rpa_schedule_run(app):
"""超时 awaiting run 应回收为 failed,避免阻塞后续执行。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-RECOVER",
username="schedule_inv_recover_user",
)
run = ScheduleRun(
run_no="RUN20260709080100",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow() - timedelta(seconds=1200),
response_summary_json={"awaiting_rpa": True},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
recovered = recover_stale_awaiting_rpa_schedule_runs(task)
assert recovered == 1
db.session.refresh(run)
assert run.status == "failed"
assert run.finished_at is not None
assert "超时" in (run.error_message or "")
def test_compute_run_status_requires_all_sources_success():
"""触发 3 源仅 1 成功 0 失败时应 partial_failed,不能误标 success。"""
assert _compute_run_status(total_count=3, success_count=1, failed_count=0) == "partial_failed"
assert _compute_run_status(total_count=3, success_count=3, failed_count=0) == "success"
assert _compute_run_status(total_count=3, success_count=0, failed_count=3) == "failed"
def test_build_finalize_details_marks_missing_callback_as_failed():
"""未出现在回调结果中的 pending source 应补为 failed。"""
pending = [
{"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"},
{"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"},
{"source_code": "SRC_B", "warehouse_id": "WH3", "display_name": "B1"},
]
details = _build_finalize_details(
pending,
created=[{"source_code": "SRC_A", "warehouse_id": "WH1", "inventory_file_no": "INV-1"}],
failed=[],
)
assert len(details) == 3
assert sum(1 for item in details if item.get("export_status") == "success") == 1
assert sum(1 for item in details if item.get("export_status") == "failed") == 2
missing = [item for item in details if item.get("error_message") == "RPA callback missing"]
assert len(missing) == 2
assert any(item.get("warehouse_id") == "WH2" for item in missing)
def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
"""回调结果少于触发源数时,排程应 partial_failed。"""
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_partial.xlsx"
try:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 1])
wb.save(sample)
except ImportError:
sample.write_bytes(b"placeholder")
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-PARTIAL",
username="schedule_inv_partial_user",
)
run = ScheduleRun(
run_no="RUN20260709080200",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=3,
response_summary_json={
"awaiting_rpa": True,
"pending_details": [
{"source_code": "SRC_A", "warehouse_id": "WH1", "display_name": "A1"},
{"source_code": "SRC_A", "warehouse_id": "WH2", "display_name": "A2"},
{"source_code": "SRC_B", "warehouse_id": "WH3", "display_name": "B1"},
],
},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
rpa_report_inventory_batch({
"run_no": run.run_no,
"schedule_run_id": run.id,
"trigger_type": "scheduled",
"results": [{
"source_code": "SRC_A",
"warehouse_id": "WH1",
"success": True,
"file_path": str(sample),
}],
})
db.session.refresh(run)
assert run.status == "partial_failed"
assert run.success_count == 1
assert run.failed_count == 2
def test_is_awaiting_rpa_schedule_run_helper(app):
"""awaiting RPA run 应被识别,普通 running 不应误判。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-AWAIT-FLAG",
username="schedule_inv_await_flag_user",
)
awaiting = ScheduleRun(
run_no="RUN20260709080300",
schedule_task_id=task.id,
status="running",
response_summary_json={"awaiting_rpa": True},
)
plain = ScheduleRun(
run_no="RUN20260709080301",
schedule_task_id=task.id,
status="running",
response_summary_json={},
)
db.session.add_all([awaiting, plain])
db.session.commit()
assert is_awaiting_rpa_schedule_run(awaiting) is True
assert is_awaiting_rpa_schedule_run(plain) is False
def test_inventory_rpa_excel_headers_survive_reload_config(app):
"""reload_config 后 shipping-inventory-rpa 表头仍应可用。"""
with app.app_context():
reload_config()
header_order, header_labels = resolve_schedule_header("shipping-inventory-rpa")
assert header_order
assert header_labels.get("inventory_file_no") == "库存快照号"
def test_filter_sources_by_source_codes(app):
"""推荐写法 source_codes 应精确筛到对应库存源。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-SRC",
username="schedule_inv_filter_src",
api_body_template='{"source_codes": ["DSV360_AWSBI_BYAWSATL01"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
def test_filter_sources_by_warehouse_id(app):
"""兼容占位符常用的 warehouse_id(如 BYAWSATL01)。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-WH",
username="schedule_inv_filter_wh",
api_body_template='{"source_codes": ["BYAWSATL01"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
def test_filter_sources_by_match_aliases(app):
"""兼容误填 match_aliases 的历史排程参数。"""
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-FILTER-ALIAS",
username="schedule_inv_filter_alias",
api_body_template='{"match_aliases": ["ATL01"]}',
)
db.session.commit()
sources = _filter_sources(task)
assert [item.get("source_code") for item in sources] == ["DSV360_AWSBI_BYAWSATL01"]
@@ -1,4 +1,4 @@
"""shipping_notice inventory_sources JSON 配置加载与校验测试。"""
"""shipping_notice inventory_sources YAML/JSON 配置加载与校验测试。"""
from pathlib import Path
@@ -13,8 +13,8 @@ from app.services.shipping_notice.inventory_sources import (
)
def test_inventory_sources_json_loads(app):
"""默认 JSON 配置应成功加载并包含 DSV360_AWSDU。"""
def test_inventory_sources_yaml_loads(app):
"""默认 YAML 配置应成功加载并包含 DSV360_AWSDU。"""
with app.app_context():
reload_inventory_sources_config()
source = get_inventory_source("DSV360_AWSDU")