feat(schedule): 优化排程任务配置与进度契约处理逻辑

This commit is contained in:
hugo committed 2026-07-08 16:09:28 +08:00
1 parent d54f51ddc3
commit 99453aa52a
65 files changed
+2837 -487

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ def test_agent_lifecycle(client, admin_headers):
assert len(agents) == 1
assert agents[0]['name'] == "Test Agent"
assert agents[0]['description'] == "Initial Description"
assert 'dify_api_key' not in agents[0]
assert agents[0]['dify_api_key'] == "key-123"
assert agents[0]['dify_api_key_masked']
# 3. Update Agent
+1 -1
View File
@@ -89,7 +89,7 @@ def test_agent_crud(client):
agents = parse_api_data(res.get_json())
assert len(agents) == 1
assert agents[0]['name'] == 'Test Agent'
assert 'dify_api_key' not in agents[0]
assert agents[0]['dify_api_key'] == 'sk-test-key'
# Update
res = client.put(f'/api/admin/agents/{agent_id}', json={
@@ -133,6 +133,19 @@ def test_validate_omitted_handler_config_preserves_existing(app):
assert normalized['handler_config']['intent_routes'] == ['text2sql']
def test_validate_shipping_notice_clears_bound_schedule_task_id():
normalized = validate_agent_payload({
'name': 'Shipping Bot',
'agent_code': 'shipping_notice',
'runtime_provider': 'hybrid',
'conversation_mode': 'task_chat',
'dify_app_id': 'app-ship',
'bound_schedule_task_id': 42,
'capabilities': {'task_progress': True},
})
assert normalized['bound_schedule_task_id'] is None
def test_strip_migrated_extra_registry_keys_preserves_training(app):
with app.app_context():
agent = Agent(
@@ -23,12 +23,26 @@ def test_build_agent_registry_schema_includes_platform_enums():
def test_build_agent_registry_schema_agent_types_include_validation_rules():
"""agent_types 每条应含 required_fields 与 forced_capabilities。"""
"""agent_types 每条应含 required_fields、default_capabilities、forced_capabilities 与 progress_contract。"""
schema = build_agent_registry_schema()
by_code = {item['agent_code']: item for item in schema['agent_types']}
assert by_code['file_check']['required_fields'] == ['bound_schedule_task_id']
assert by_code['file_check']['forced_capabilities']['task_progress'] is True
assert by_code['generic']['required_fields'] == []
file_check_contract = by_code['file_check']['progress_contract']
assert file_check_contract['data_source']['type'] == 'schedule_run'
assert file_check_contract['binding']['requires_schedule_task'] is True
shipping = by_code['shipping_notice']
assert shipping['default_capabilities']['file_upload'] is True
assert shipping['default_capabilities']['task_progress'] is True
assert shipping['forced_capabilities'] == {
'file_upload': True,
'task_progress': True,
'human_confirm': True,
}
assert shipping['progress_contract']['presentation']['layout'] == 'workspace'
assert shipping['progress_contract']['binding']['requires_schedule_task'] is False
assert 'erp_kb' not in shipping['forced_capabilities']
def test_build_agent_registry_schema_handler_config_schemas():
@@ -12,7 +12,9 @@ from app.core.errors import ValidationError
from app.services.agent_registry.catalog_loader import (
clear_catalog_cache,
coerce_manifest_boolean,
get_agent_type_default_capabilities,
get_default_capabilities,
normalize_progress_contract,
)
@@ -46,6 +48,53 @@ def test_get_default_capabilities_uses_manifest_boolean_coercion(monkeypatch):
assert caps['task_progress'] is False
def test_get_agent_type_default_capabilities_merges_platform_and_type_defaults():
"""agent_types.default_capabilities 应覆盖 platform 同名字段。"""
clear_catalog_cache()
caps = get_agent_type_default_capabilities('shipping_notice')
assert caps['streaming'] is True
assert caps['file_upload'] is True
assert caps['task_progress'] is True
assert caps['erp_kb'] is False
def test_normalize_progress_contract_file_check_shape():
contract = normalize_progress_contract({
'enabled': True,
'data_source': {'type': 'schedule_run'},
'update': {'transport': 'polling', 'interval_seconds': 2},
'binding': {'type': 'chat_log_run', 'requires_schedule_task': True},
'presentation': {'layout': 'card', 'visualization': 'counter'},
})
assert contract is not None
assert contract['data_source']['type'] == 'schedule_run'
assert contract['binding']['requires_schedule_task'] is True
def test_normalize_progress_contract_sse_requires_event():
"""transport=sse 但缺 event 时应 fail-fast,避免运行时静默不发进度。"""
with pytest.raises(ValidationError, match='update.event'):
normalize_progress_contract({
'enabled': True,
'data_source': {'type': 'domain_state', 'domain': 'shipping_notice'},
'update': {'transport': 'sse'},
'binding': {'type': 'conversation_context'},
'presentation': {'layout': 'workspace', 'visualization': 'stepper'},
})
def test_normalize_progress_contract_schedule_run_requires_schedule_task_binding():
"""schedule_run 数据源必须声明 binding.requires_schedule_task=true。"""
with pytest.raises(ValidationError, match='requires_schedule_task'):
normalize_progress_contract({
'enabled': True,
'data_source': {'type': 'schedule_run'},
'update': {'transport': 'polling'},
'binding': {'type': 'chat_log_run', 'requires_schedule_task': False},
'presentation': {'layout': 'card', 'visualization': 'counter'},
})
def test_get_tool_run_progress_defaults_coerces_boolean_string(monkeypatch):
from app.services.agent_registry import catalog_loader
from app.services.agent_registry.catalog_loader import get_tool_run_progress_defaults
@@ -16,6 +16,7 @@ from app.services.agent_registry.catalog import AGENT_TYPE_CATALOG, clear_catalo
from app.services.agent_registry.catalog_loader import list_agent_type_codes
from app.services.agent_registry.catalog_validation import (
apply_catalog_capabilities,
catalog_progress_requires_schedule_task,
normalize_handler_config,
validate_required_fields,
)
@@ -110,6 +111,11 @@ def test_normalize_handler_config_rejects_invalid_boolean_string():
normalize_handler_config('file_check', {'lock_input_when_running': 'maybe'})
def test_catalog_progress_requires_schedule_task_follows_contract():
assert catalog_progress_requires_schedule_task('file_check') is True
assert catalog_progress_requires_schedule_task('shipping_notice') is False
def test_normalize_handler_config_empty_schema_rejects_any_field():
"""空 handler_config_schema 表示不允许任何 handler_config 字段。"""
with pytest.raises(ValidationError, match='不允许配置 handler_config'):
+48 -1
View File
@@ -13,6 +13,8 @@ from app.services.agent_registry.resolver import (
agent_declares_task_progress,
agent_has_erp_kb,
agent_has_intent_route,
agent_has_progress,
agent_progress_requires_schedule_task,
is_file_check_runtime_ready,
normalize_capabilities,
resolve_agent_code,
@@ -20,6 +22,7 @@ from app.services.agent_registry.resolver import (
resolve_conversation_mode,
resolve_handler_key,
resolve_intent_routes,
resolve_progress_contract,
resolve_runtime_provider,
)
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
@@ -184,7 +187,7 @@ def test_agent_declares_task_progress_reads_registry_columns():
def test_is_file_check_runtime_ready_requires_bound_task_id():
"""完整 file_check 入口须 capabilities.task_progress 与 bound_schedule_task_id。"""
"""完整 file_check 入口须 progress_contract 要求排程且 bound_schedule_task_id 已配置。"""
ready = _agent(
agent_code='file_check',
capabilities={'task_progress': True},
@@ -196,3 +199,47 @@ def test_is_file_check_runtime_ready_requires_bound_task_id():
)
assert is_file_check_runtime_ready(ready) is True
assert is_file_check_runtime_ready(misconfigured) is False
def test_resolve_progress_contract_reads_catalog_for_file_check():
agent = _agent(agent_code='file_check', capabilities={'task_progress': True})
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['data_source']['type'] == 'schedule_run'
assert contract['presentation']['visualization'] == 'counter'
def test_resolve_progress_contract_reads_catalog_for_shipping_notice():
agent = _agent(agent_code='shipping_notice', capabilities={'task_progress': True})
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['data_source']['type'] == 'domain_state'
assert contract['update']['event'] == 'shipping_ui_state'
def test_agent_has_progress_merges_catalog_forced_capabilities():
"""capabilities 列缺失时,Catalog forced_capabilities.task_progress 也应放行 contract。"""
assert agent_has_progress(_agent(agent_code='file_check')) is True
assert agent_has_progress(_agent(agent_code='file_check', capabilities={'task_progress': True})) is True
assert agent_has_progress(_agent(agent_code='generic')) is False
def test_resolve_progress_contract_shipping_notice_without_capabilities_column():
"""存量 shipping_notice 行 capabilities.task_progress 缺失/false 时仍应返回 contract。"""
missing = _agent(agent_code='shipping_notice', capabilities=None)
stale_false = _agent(agent_code='shipping_notice', capabilities={'task_progress': False})
for agent in (missing, stale_false):
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['update']['event'] == 'shipping_ui_state'
def test_agent_progress_requires_schedule_task_only_for_file_check():
assert agent_progress_requires_schedule_task(_agent(
agent_code='file_check',
capabilities={'task_progress': True},
)) is True
assert agent_progress_requires_schedule_task(_agent(
agent_code='shipping_notice',
capabilities={'task_progress': True},
)) is False
@@ -6,7 +6,12 @@ tests/test_agent_registry_serialization.py
from types import SimpleNamespace
from app.services.agent_registry.serialization import mask_dify_api_key, serialize_agent_for_admin
from app.services.agent_registry.serialization import (
build_tool_run_progress_view,
mask_dify_api_key,
serialize_agent_for_admin,
serialize_registry_fields,
)
def test_mask_dify_api_key():
@@ -15,7 +20,7 @@ def test_mask_dify_api_key():
assert mask_dify_api_key('sk-abcdefghijklmnop') == 'sk-a****mnop'
def test_serialize_agent_for_admin_does_not_expose_plain_api_key():
def test_serialize_agent_for_admin_includes_api_key_for_admin_edit():
agent = SimpleNamespace(
id=1,
name='Bot',
@@ -44,5 +49,38 @@ def test_serialize_agent_for_admin_does_not_expose_plain_api_key():
handler_config=None,
)
payload = serialize_agent_for_admin(agent)
assert 'dify_api_key' not in payload
assert payload['dify_api_key'] == agent.dify_api_key
assert payload['dify_api_key_masked'] == mask_dify_api_key(agent.dify_api_key)
def test_serialize_registry_fields_includes_progress_contract():
file_check = SimpleNamespace(
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
capabilities={'task_progress': True},
bound_schedule_task_id=42,
handler_config={'poll_interval_seconds': 2, 'lock_input_when_running': True},
dify_app_type='chatflow',
iframe_url=None,
category=None,
sub_category=None,
sort_order=0,
welcome_message=None,
suggested_questions_style='plain',
suggested_questions=[],
file_upload_policy=None,
)
payload = serialize_registry_fields(file_check)
assert payload['progress_contract']['data_source']['type'] == 'schedule_run'
assert payload['tool_run_progress']['schedule_task_id'] == 42
def test_build_tool_run_progress_view_skips_domain_state_contract():
shipping = SimpleNamespace(
agent_code='shipping_notice',
capabilities={'task_progress': True},
bound_schedule_task_id=99,
handler_config=None,
)
assert build_tool_run_progress_view(shipping) is None
+8 -6
View File
@@ -49,11 +49,12 @@ def _mk_check_task(owner_id: int, *, enabled=True):
task = ScheduleTask(
schedule_no='CHK-ROHS-001',
name='RoHS 自动检核',
schedule_type='platform_app',
schedule_type='data_pipeline',
data_source_type='database',
owner_user_id=owner_id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/1',
platform_api_path=None,
enabled=enabled,
)
db.session.add(task)
@@ -65,11 +66,12 @@ def _mk_other_check_task(owner_id: int):
task = ScheduleTask(
schedule_no='CHK-GENERAL-001',
name='通用检核',
schedule_type='platform_app',
schedule_type='data_pipeline',
data_source_type='database',
owner_user_id=owner_id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/general-check',
platform_api_path=None,
enabled=True,
)
db.session.add(task)
@@ -512,7 +514,7 @@ def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
second_task = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核备用',
schedule_type='platform_app',
schedule_type='data_pipeline',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
@@ -609,7 +611,7 @@ def test_workspace_file_check_active_run_filters_by_task_id(app, client):
task_b = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核 B',
schedule_type='platform_app',
schedule_type='data_pipeline',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
@@ -0,0 +1,138 @@
"""internal_jobs API registry 集成测试。"""
import json
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。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
from app import db
user = User(username="internal_job_user", email="internal_job_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-IJ-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,
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no="RUN20260708030000",
schedule_task_id=task.id,
status="running",
)
db.session.add(run)
db.session.commit()
run_no = run.run_no
task_id = task.id
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"run_no": run_no, "schedule_task_id": task_id}),
content_type="application/json",
)
assert resp.status_code == 200
body = resp.get_json()
assert body["summary"]["success_count"] >= 1
assert list(trigger_dir.glob("inventory_export_batch_*.json"))
def test_internal_job_unknown_key_returns_404(client):
"""未注册 job key 应返回 404。"""
resp = client.post(
"/api/internal/jobs/not-registered-job",
data=json.dumps({}),
content_type="application/json",
)
assert resp.status_code == 404
def test_internal_job_rejects_mismatched_schedule_task_id(client, app):
"""schedule_task_id 与 URL job key 不匹配应 400。"""
with app.app_context():
from app import db
user = User(username="ij_mismatch_user", email="ij_mismatch_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-IJ-MISMATCH",
name="固资快照",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(task)
db.session.commit()
task_id = task.id
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"schedule_task_id": task_id}),
content_type="application/json",
)
assert resp.status_code == 400
def test_internal_job_rejects_foreign_run_no(client, app):
"""run_no 属于其他任务时应 400。"""
with app.app_context():
from app import db
user = User(username="ij_run_user", email="ij_run_user@example.com")
db.session.add(user)
db.session.flush()
task_a = ScheduleTask(
schedule_no="SCH-IJ-A",
name="shipping task",
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,
)
task_b = ScheduleTask(
schedule_no="SCH-IJ-B",
name="faq task",
schedule_type="platform_job",
platform_api_path="faq-aggregate-hot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 4 * * *",
enabled=True,
)
db.session.add_all([task_a, task_b])
db.session.flush()
run = ScheduleRun(
run_no="RUN-FOREIGN-001",
schedule_task_id=task_b.id,
status="running",
)
db.session.add(run)
db.session.commit()
task_a_id = task_a.id
run_no = run.run_no
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"schedule_task_id": task_a_id, "run_no": run_no}),
content_type="application/json",
)
assert resp.status_code == 400
+79 -10
View File
@@ -1,12 +1,30 @@
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import Agent, ScheduleRun, ScheduleTask, User
def _mk_admin():
admin = User(username='admin', email='admin@example.com', role='admin', status='active')
admin.set_password('x')
db.session.add(admin)
return admin
@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',
}
def _mk_user(name: str, email: str):
@@ -16,9 +34,8 @@ def _mk_user(name: str, email: str):
return user
def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
def test_schedule_crud_and_workspace_visibility(app, client, admin_jwt_headers):
with app.app_context():
_mk_admin()
owner = _mk_user('owner_u', 'owner@example.com')
notify = _mk_user('notify_u', 'notify@example.com')
other = _mk_user('other_u', 'other@example.com')
@@ -31,9 +48,10 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
other_id = other.id
agent_id = agent.id
create_res = client.post('/api/admin/schedules', headers=admin_headers, json={
create_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'rohs-schedule',
'schedule_type': 'dify_app',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 */30 * * *',
'wait_seconds': 5,
@@ -46,7 +64,7 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
task = create_res.get_json()
task_id = task['id']
list_res = client.get('/api/admin/schedules', headers=admin_headers)
list_res = client.get('/api/admin/schedules', headers=admin_jwt_headers)
assert list_res.status_code == 200
assert any(x['id'] == task_id for x in list_res.get_json())
@@ -85,3 +103,54 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
denied = client.get(f'/api/workspace/schedule-runs/{run_id}', headers=other_headers)
assert denied.status_code == 403
def test_post_schedule_defaults_data_source_type_to_database(app, client, admin_jwt_headers):
"""兼容旧客户端:data_pipeline 不传 data_source_type 时应默认 database 而非 400。"""
with app.app_context():
owner = _mk_user('legacy_owner_u', 'legacy_owner@example.com')
db.session.commit()
owner_id = owner.id
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'legacy-minimal-schedule',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert res.status_code == 201
body = res.get_json()
assert body['schedule_type'] == 'data_pipeline'
assert body['data_source_type'] == 'database'
def test_post_and_patch_schedule_reject_non_object_config(app, client, admin_jwt_headers):
"""POST/PATCH config 传非 JSON 对象(数组/字符串)应 400,而非 500。"""
with app.app_context():
owner = _mk_user('cfg_type_owner_u', 'cfg_type_owner@example.com')
db.session.commit()
owner_id = owner.id
post_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'bad-config-schedule',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
'config': ['not-an-object'],
})
assert post_res.status_code == 400
create_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'good-schedule',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
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': 'not-an-object',
})
assert patch_res.status_code == 400
+289
View File
@@ -0,0 +1,289 @@
"""排程 Job Registry 与 executor 分发测试。"""
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 import _run_common_executor, _run_generic_check_job, resolve_schedule_executor
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs, run_platform_job
from app.services.schedule.schedule_contract import migrate_legacy_schedule_payload, normalize_job_key
@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',
}
def test_platform_jobs_registered():
"""内置 platform job 应已注册。"""
keys = {job.key for job in list_platform_jobs()}
assert "shipping-inventory-rpa" in keys
assert "faq-aggregate-hot" in keys
assert "fixed-assets-snapshot" in keys
assert get_platform_job("shipping-inventory-rpa") is not None
def test_unknown_platform_job_raises():
"""未注册 key 应无法 resolve。"""
assert get_platform_job("not-a-real-job") is None
def test_resolve_schedule_executor_dispatch():
"""schedule_type 决定 executor 分发。"""
pipeline_task = ScheduleTask(schedule_type="data_pipeline", data_source_type="database")
platform_task = ScheduleTask(schedule_type="platform_job", platform_api_path="faq-aggregate-hot")
assert resolve_schedule_executor(pipeline_task) is _run_generic_check_job
assert resolve_schedule_executor(platform_task) is _run_common_executor
with pytest.raises(RuntimeError, match="Unsupported schedule_type"):
resolve_schedule_executor(ScheduleTask(schedule_type="legacy_type"))
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('/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) == ''
def test_normalize_platform_api_path_delegates_to_job_key():
"""执行层归一化应与契约层 normalize_job_key 一致;完整 URL 原样透传。"""
from app.services.schedule import normalize_platform_api_path
assert normalize_platform_api_path('/api/internal/jobs/faq-aggregate-hot') == 'faq-aggregate-hot'
assert normalize_platform_api_path('faq_aggregate_hot') == 'faq-aggregate-hot'
assert normalize_platform_api_path('http://external.host/hook') == 'http://external.host/hook'
assert normalize_platform_api_path(None) == ''
def test_migrate_legacy_full_path_platform_api_path():
"""旧 platform_app + 完整路径 platform_api_path 应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"platform_api_path": "/api/internal/jobs/fixed-assets-snapshot",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "fixed-assets-snapshot"
assert migrated["data_source_type"] is None
def test_migrate_legacy_shipping_inventory_rpa():
"""旧 shipping_inventory_rpa 语义应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"data_source_type": "shipping_inventory_rpa",
"platform_api_path": "/123",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "shipping-inventory-rpa"
assert migrated["data_source_type"] is None
def test_migrate_legacy_faq_hot_aggregate():
"""旧 faq_hot_aggregate 语义应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"data_source_type": "faq_hot_aggregate",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "faq-aggregate-hot"
assert migrated["data_source_type"] is None
def test_migrate_legacy_database_pipeline():
"""旧 platform_app + database 应迁移为 data_pipeline。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"data_source_type": "database",
"platform_api_path": "/42",
})
assert migrated["schedule_type"] == "data_pipeline"
assert migrated["platform_api_path"] is None
assert migrated["data_source_type"] == "database"
def test_run_platform_job_unknown_key(app):
"""run_platform_job 对未知 key 应抛 KeyError。"""
with app.app_context():
user = User(username="registry_user", email="registry_user@example.com")
from app import db
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-REG-001",
name="test",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
from app.models import ScheduleRun
run = ScheduleRun(run_no="RUN-REG-001", schedule_task_id=1, status="running")
with pytest.raises(KeyError):
run_platform_job("unknown-job-key", task, run, {})
def test_common_executor_in_process_without_base_url(app, monkeypatch):
"""已注册 job key 在无 INTERNAL_API_BASE_URL 时应进程内执行,不走 HTTP。"""
with app.app_context():
from app import db
from app.models import ScheduleRun
app.config["INTERNAL_API_BASE_URL"] = ""
user = User(username="inproc_exec_user", email="inproc_exec_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-INPROC-001",
name="in-process job",
schedule_type="platform_job",
platform_api_path="faq-aggregate-hot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(run_no="RUN-INPROC-001", schedule_task_id=task.id, status="running")
db.session.add(run)
db.session.commit()
called: dict[str, str] = {}
def _fake_run_platform_job(key, t, r, payload=None):
called["key"] = key
return 1, 1, 0, 0, [{"ok": True}], [], [{"step": "in_process", "status": "success"}]
monkeypatch.setattr(
"app.services.schedule.job_registry.run_platform_job",
_fake_run_platform_job,
)
total, success, failed, skipped, details, errors, logs = _run_common_executor(task, run)
assert called["key"] == "faq-aggregate-hot"
assert total == 1 and success == 1
assert any(log.get("step") == "in_process" for log in logs)
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"
def test_schedule_config_rejects_data_source_type_for_platform_job(client, admin_jwt_headers, app):
"""platform_job 经 schedule-config PUT 改 data_source_type 应被拒绝。"""
with app.app_context():
from app import db
user = User(username="cfg_platform_user", email="cfg_platform_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-CFG-001",
name="platform cfg guard",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.commit()
task_id = task.id
res = client.put(
f"/api/admin/schedule-config/{task_id}",
headers=admin_jwt_headers,
json={"data_source_type": "database"},
)
assert res.status_code == 400
def test_post_platform_job_rejects_illegal_config(client, admin_jwt_headers, app):
"""创建 platform_job 携带非白名单 config 应 400。"""
with app.app_context():
user = User(username="post_cfg_user", email="post_cfg_user@example.com")
db.session.add(user)
db.session.commit()
owner_id = user.id
res = client.post(
"/api/admin/schedules",
headers=admin_jwt_headers,
json={
"name": "faq with config",
"schedule_type": "platform_job",
"platform_api_path": "faq-aggregate-hot",
"owner_user_id": owner_id,
"cron_expr": "0 3 * * *",
"config": {"api_body_template": "{}"},
},
)
assert res.status_code == 400
def test_patch_platform_job_rejects_illegal_config_without_partial_update(client, admin_jwt_headers, app):
"""PATCH 携带非法 config 应 400,且任务主字段不被半更新。"""
with app.app_context():
user = User(username="patch_cfg_user", email="patch_cfg_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-PATCH-CFG-001",
name="before patch",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.commit()
task_id = task.id
res = client.patch(
f"/api/admin/schedules/{task_id}",
headers=admin_jwt_headers,
json={
"name": "after patch",
"config": {"api_body_template": "{}"},
},
)
assert res.status_code == 400
with app.app_context():
refreshed = db.session.get(ScheduleTask, task_id)
assert refreshed.name == "before patch"
@@ -19,9 +19,11 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
task = ScheduleTask(
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 * * *",
data_source_type="shipping_inventory_rpa",
enabled=True,
)
db.session.add(task)