"""排程 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 "freight-rpa-onhand" in keys assert "faq-aggregate-hot" in keys assert "fixed-assets-snapshot" in keys assert "accounting-voucher-po-print" in keys assert get_platform_job("freight-rpa-onhand") 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/freight-rpa-onhand') == 'freight-rpa-onhand' 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_is_not_a_runtime_alias(): """历史 data_source 整值不再由运行期拼接或别名表改写,交给 s17c。""" raw = { "schedule_type": "platform_app", "data_source_type": "shipping_inventory_rpa", "platform_api_path": "/123", } migrated = migrate_legacy_schedule_payload(raw) # 关键断言:运行期不再识别该历史键,避免用字符串拼接绕过 grep 门禁。 assert migrated["data_source_type"] == "shipping_inventory_rpa" assert migrated["platform_api_path"] == "/123" assert "shipping_inventory_rpa" not in str(migrate_legacy_schedule_payload.__code__.co_consts) 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="freight-rpa-onhand", 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。""" 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 "freight-rpa-onhand" 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["freight-rpa-onhand"]["label_key"] == "admin.schedule.form.platformJobFreightRpaOnhand" assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate" assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot" assert by_key["accounting-voucher-po-print"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherPoPrint" assert by_key["accounting-voucher-oa-sales-release"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherOaSalesRelease" 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): """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"