""" 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, ) def _enabled_source_code() -> str: """读取测试数据库的首个启用库存源,避免测试依赖已废弃 YAML 的固定编码。""" from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources sources = list_database_inventory_sources() assert sources, 'expected at least one enabled inventory source' return str(sources[0]['source_code']) @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} with app.app_context(): assert _enabled_source_code() 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(): source_code = _enabled_source_code() with pytest.raises(JobParamsValidationError, match='list of option values'): validate_task_params( 'shipping-inventory-rpa', {'source_codes': source_code}, check_options=False, ) def test_validate_task_params_checks_option_range(app): """check_options=True 时,multi_select 值不在选项范围内应报错。""" with app.app_context(): source_code = _enabled_source_code() 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': [source_code]}, check_options=True, ) assert result['source_codes'] == [source_code] 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 响应中。""" with app.app_context(): source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, job_params={'source_codes': [source_code]}, ) assert res.status_code == 201 body = res.get_json() assert body['job_params'] == {'source_codes': [source_code]} with app.app_context(): task = db.session.get(ScheduleTask, body['id']) assert task.job_params == {'source_codes': [source_code]} 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 的任务重置为默认值。""" with app.app_context(): source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, job_params={'source_codes': [source_code]}, ) 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 重置,避免旧参数残留。""" with app.app_context(): source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, job_params={'source_codes': [source_code]}, ) 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 时应清空旧参数。""" with app.app_context(): source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, job_params={'source_codes': [source_code]}, ) 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, app): """切换 platform_api_path 同时显式传 job_params 时,应保留请求体参数(经新 schema 校验)。""" with app.app_context(): source_code = _enabled_source_code() res = _create_platform_schedule( client, admin_jwt_headers, owner_id, job_params={'source_codes': [source_code]}, ) 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(): source_code = _enabled_source_code() task = ScheduleTask(job_params={'source_codes': [source_code]}) sources = _filter_sources(task) assert [item.get('source_code') for item in sources] == [source_code] # 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)