from __future__ import annotations import importlib.util import json from pathlib import Path import pytest SCRIPT_PATH = ( Path(__file__).resolve().parents[1] / "scripts" / "write_diagnosis_routing.py" ) SPEC = importlib.util.spec_from_file_location("write_diagnosis_routing", SCRIPT_PATH) MODULE = importlib.util.module_from_spec(SPEC) assert SPEC and SPEC.loader SPEC.loader.exec_module(MODULE) def _routing_payload() -> dict: return { "schema_version": "2.0", "status": "awaiting_user", "scope": { "cluster_id": "cluster-1", "time_range": { "start": "2026-08-25T04:00:00Z", "end": "2026-08-25T05:00:00Z", }, }, "candidates": [ { "route": "memory_or_oom_pressure", "label": "Memory / OOM", "routing_confidence": 0.8, "evidence_for": ["memory increased"], "evidence_against": [], } ], "recommended_route": "memory_or_oom_pressure", "selection": None, } def test_validate_routing_accepts_v2_standard_taxonomy() -> None: assert MODULE.validate_routing(_routing_payload())["schema_version"] == "2.0" def test_writer_taxonomy_matches_workspace_schema() -> None: schema_path = ( Path(__file__).resolve().parents[4] / "config" / "investibook" / "schemas" / "diagnosis-routing.schema.json" ) schema = json.loads(schema_path.read_text(encoding="utf-8")) assert set(schema["$defs"]["standardRoute"]["enum"]) == MODULE.STANDARD_ROUTES @pytest.mark.parametrize( ("field", "value"), [ ("schema_version", "1.0"), ("candidate_route", "tidb_memory_oom_or_panic"), ("recommended_route", "custom_memory_route"), ], ) def test_validate_routing_rejects_non_v2_or_invented_routes( field: str, value: str ) -> None: payload = _routing_payload() if field == "candidate_route": payload["candidates"][0]["route"] = value else: payload[field] = value with pytest.raises(ValueError): MODULE.validate_routing(payload) def test_validate_routing_requires_recommendation_to_be_a_candidate() -> None: payload = _routing_payload() payload["recommended_route"] = "sql_plan_or_query" with pytest.raises(ValueError, match="one of the candidate routes"): MODULE.validate_routing(payload) def test_validate_selected_routes_against_standard_taxonomy() -> None: payload = _routing_payload() payload["status"] = "selected" payload["selection"] = { "routes": ["memory_or_oom_pressure", "sql_plan_or_query"], "source": "feedback", } assert MODULE.validate_routing(payload)["selection"]["routes"] == [ "memory_or_oom_pressure", "sql_plan_or_query", ]