Source: live external MCP run against ss-prod Sales Dashboard (docs/2026-09-07-sales-prod-mcp-run.md) proved the initial-bootstrap chain externally unreachable: register_draft_pack requires a principal-owned AgentRun but no MCP operation created one after the chat decommission; the vertical E2E masked the gap with a raw-ORM prerequisite seed. T029i: MCP create_agent_run/get_agent_run (mcp_server/tools_agent_run.py) over Services.AgentRuns.Service.Create — REST-parity EXECUTE/READ permissions, human-only, server-pinned UIContext, idempotency-key replay; catalog 2.1.0->2.2.0; MCPX-FR-027 external-reachability invariant pinned; initial-scenario E2E converted to the fully external chain (zero non-MCP seeding); strict-xfail pin flipped as designed, unmarked and hardened (E2E-EXT-001 CLOSED). T029k: ScenarioGraph.CapabilityAuthority — truthful capability facts derived from the authoritative DashboardQueryModel (mutation-context capabilities never derived), derived-wins merge over caller declarations, single choke point wired into MCP inspect_scenario / inspect_dashboard_context and REST api_compile_scenario; CAP-001 classification-fix test on the sales-shape fixture (B02-B04/T01-T03 automated, C04-C06 unsupported, unsafe-mutation cases legitimately human). T029l: disposition vocabulary clarity — RU/EN labels name the persisted outcome (confirm->passed), confirm restyled bg-destructive->bg-primary, decide_checkpoint description carries the immutable outcome table; lifecycle mapping and API vocabulary unchanged (DISP-001 CLOSED). Decision memory: ADR-0024 (IMPLEMENTED, 4 rejected alternatives incl. no-AgentRun boundary and implicit auto-create) + README registry; 050 MCPX-FR-027/028/029 + release-gate rows + Clarifications session 2026-09-07; 038/044/045 field-run amendments -> IMPLEMENTED; WORKSTATE checkpoints (plan round + execution round). Pre-existing HEAD regressions surfaced by the first full-suite rerun since 4d5ef6be/58c5ae39 and fixed: (1) stale SC-007 resource pin — canonical identifier is the post-redirect /mcp/ (code + twin pin aligned since the batches; test_mcp_client_flow_http pin updated with rationale); (2) app-lifespan tests re-entered the run-once StreamableHTTPSessionManager module singleton — autouse fresh-transport-app fixture (production lifespan runs once per process; singleton stays correct there). Gates: full backend suite 11357 passed / 243 skipped / 1 xpassed / 0 failed (first green full run since the batches); MCP+catalog slice 70 passed; capability slice 67 passed; frontend vitest 3507 passed (206 files), lint 0 errors (364 baseline warnings), build OK; ruff/compileall clean; anchors balanced; scoped git diff --check clean. INV_7 watch: tools_scenario.py 508 LOC and routes scenario.py 442 LOC flagged for the next decomposition pass (new code lives in new modules 155/236 LOC). OPEN: T029m / E2E-EXT-002 — live-stand replay of the sales scenario through the full external chain. Not included (foreign uncommitted workstream): translate/migration integration tests, _job_routes.py, .kilo/agent-manager.json, specs-036-050-20260907-111314.md.
344 lines
18 KiB
Python
344 lines
18 KiB
Python
# #region Test.Api.ScenarioRoutes [C:3] [TYPE Module] [SEMANTICS testing,api,scenario,routes]
|
|
# @BRIEF Deep route tests for Api.DashboardTesting.Scenario graph endpoints — compile/validate/
|
|
# resolve success + error envelopes, with services mocked at the module boundary.
|
|
# @RELATION BINDS_TO -> [Api.DashboardTesting.Scenario]
|
|
# @TEST_CONTRACT: ScenarioCompileRequest -> {scenario, validation} | 422 VALIDATION_ERROR
|
|
# @TEST_CONTRACT: DashboardTestScenario -> ValidationResult | 422
|
|
# @TEST_CONTRACT: ScenarioResolveRequest + scenario -> new revision | 409 STALE_REVISION | 422
|
|
# @TEST_EDGE: missing_field -> FastAPI 422 (required fields, extra=forbid, nested body)
|
|
# @TEST_EDGE: invalid_type -> 422 (change dict missing kind -> 500 pinned edge)
|
|
# @TEST_EDGE: external_fail -> service ValueError/KeyError envelopes
|
|
# @TEST_EDGE: rbac_denied -> 401 unauthenticated; 403 without WRITE/READ permission
|
|
# @TEST_EDGE: stale_base -> 409 STALE_REVISION
|
|
# @TEST_FIXTURE: scenario_valid.json -> tests/fixtures/dashboard_scenarios/scenario_valid.json
|
|
# #endregion Test.Api.ScenarioRoutes
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from src.api.routes.dashboard_testing.scenario import router
|
|
from src.core.database import get_db
|
|
|
|
from .conftest import (
|
|
SCENARIO_ROUTES_HASH,
|
|
scenario_routes_client,
|
|
scenario_routes_no_perm_user,
|
|
scenario_routes_scenario_json,
|
|
)
|
|
|
|
_QUERY_MODEL_SALES = Path(__file__).resolve().parents[1] / "fixtures" / "dashboard_scenarios" / "query_model_sales.json"
|
|
|
|
|
|
def _validation_result(*, valid: bool = True, error: str | None = None) -> SimpleNamespace:
|
|
errors = [SimpleNamespace(model_dump=lambda: {"code": error})] if error else []
|
|
return SimpleNamespace(
|
|
valid=valid,
|
|
errors=errors,
|
|
warnings=[],
|
|
blockers=[],
|
|
coverage=[],
|
|
topological_order=[],
|
|
graph_hash=SCENARIO_ROUTES_HASH,
|
|
)
|
|
|
|
|
|
def _compile_body(**overrides: object) -> dict:
|
|
body = {
|
|
"agent_run_id": "run-1",
|
|
"objective": {"goal": "Verify filters", "selected_case_ids": ["B01"]},
|
|
"query_model": {"filters": [{"column": "date"}]},
|
|
"checklist_catalog_version": 1,
|
|
"baseline_version": "latest",
|
|
"capabilities": {"browser": True},
|
|
"parameters": {"test_date": "2026-08-01"},
|
|
"has_dataset_fields": True,
|
|
"environment_id": "env-1",
|
|
"dashboard_id": 42,
|
|
"dashboard_name": "dash-42",
|
|
}
|
|
body.update(overrides)
|
|
return body
|
|
|
|
|
|
class TestCompileEndpoint:
|
|
"""POST /api/dashboard-testing/scenarios/compile — Api.DashboardTesting.Scenario.Compile."""
|
|
|
|
PATH = "/api/dashboard-testing/scenarios/compile"
|
|
|
|
# #region Std.Semantics.TestCompileSuccess [C:2] [TYPE Function]
|
|
# @BRIEF Happy path: request fields flow into CompileScenarioRequest, graph + validation returned.
|
|
def test_success_maps_request_fields(self) -> None:
|
|
compiled = SimpleNamespace(scenario=SimpleNamespace(model_dump=lambda: {"scenario_id": "scn-1", "steps": []}))
|
|
with patch("src.api.routes.dashboard_testing.scenario.compile_scenario", return_value=compiled) as m_compile, \
|
|
patch("src.api.routes.dashboard_testing.scenario.validate_scenario", return_value=_validation_result()) as m_validate:
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=_compile_body())
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["scenario"] == {"scenario_id": "scn-1", "steps": []}
|
|
assert data["validation"]["valid"] is True
|
|
assert data["validation"]["graph_hash"] == SCENARIO_ROUTES_HASH
|
|
req = m_compile.call_args.args[0]
|
|
assert req.agent_run_id == "run-1"
|
|
assert req.objective == {"goal": "Verify filters", "selected_case_ids": ["B01"]}
|
|
assert req.checklist_catalog_version == 1
|
|
assert req.has_dataset_fields is True
|
|
assert req.dashboard_id == 42
|
|
assert req.parameters == {"test_date": "2026-08-01"}
|
|
m_validate.assert_called_once_with(compiled.scenario)
|
|
# #endregion Std.Semantics.TestCompileSuccess
|
|
|
|
# #region Std.Semantics.TestCompileCapabilityAuthority [C:2] [TYPE Function]
|
|
# @BRIEF T029k REST parity (MCPX-FR-028): an authoritative-shape query_model derives capability facts
|
|
# that win over conflicting caller declarations, and the response carries the additive
|
|
# capability_authority section — identical semantics to the MCP inspect_scenario tool.
|
|
def test_capability_authority_derived_wins(self) -> None:
|
|
compiled = SimpleNamespace(scenario=SimpleNamespace(model_dump=lambda: {"scenario_id": "scn-cap", "steps": []}))
|
|
body = _compile_body(
|
|
query_model=json.loads(_QUERY_MODEL_SALES.read_text(encoding="utf-8")),
|
|
capabilities={"browser": True, "native_filters": True, "text_filter": False, "xlsx_export": True},
|
|
has_dataset_fields=False,
|
|
)
|
|
with patch("src.api.routes.dashboard_testing.scenario.compile_scenario", return_value=compiled) as m_compile, \
|
|
patch("src.api.routes.dashboard_testing.scenario.validate_scenario", return_value=_validation_result()):
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=body)
|
|
assert resp.status_code == 200
|
|
req = m_compile.call_args.args[0]
|
|
assert req.capabilities["text_filter"] is True # derived truth beats declared false
|
|
assert req.capabilities["xlsx_export"] is False # fabricated true overridden
|
|
assert req.has_dataset_fields is True # accessible dataset with columns
|
|
section = resp.json()["capability_authority"]
|
|
assert section["status"] == "derived"
|
|
assert section["overrides"] == ["text_filter", "xlsx_export"]
|
|
assert section["has_dataset_fields"] is True
|
|
# #endregion Std.Semantics.TestCompileCapabilityAuthority
|
|
|
|
# #region Std.Semantics.TestCompileValueError [C:2] [TYPE Function]
|
|
# @BRIEF Compiler failure -> 422 VALIDATION_ERROR envelope.
|
|
def test_compile_service_value_error_422(self) -> None:
|
|
with patch("src.api.routes.dashboard_testing.scenario.compile_scenario", side_effect=ValueError("bad baseline")):
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=_compile_body())
|
|
assert resp.status_code == 422
|
|
assert resp.json()["detail"]["code"] == "VALIDATION_ERROR"
|
|
assert "bad baseline" in resp.json()["detail"]["detail"]
|
|
# #endregion Std.Semantics.TestCompileValueError
|
|
|
|
# #region Std.Semantics.TestCompileKeyError [C:2] [TYPE Function]
|
|
# @BRIEF KeyError from compiler is also wrapped as 422 (not a 500).
|
|
def test_compile_service_key_error_422(self) -> None:
|
|
with patch("src.api.routes.dashboard_testing.scenario.compile_scenario", side_effect=KeyError("objective")):
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=_compile_body())
|
|
assert resp.status_code == 422
|
|
assert resp.json()["detail"]["code"] == "VALIDATION_ERROR"
|
|
# #endregion Std.Semantics.TestCompileKeyError
|
|
|
|
# #region Std.Semantics.TestCompileValidatorFailure [C:2] [TYPE Function]
|
|
# @BRIEF Validator failure after a successful compile -> 422.
|
|
def test_compile_validation_service_422(self) -> None:
|
|
compiled = SimpleNamespace(scenario=SimpleNamespace(model_dump=lambda: {}))
|
|
with patch("src.api.routes.dashboard_testing.scenario.compile_scenario", return_value=compiled), \
|
|
patch("src.api.routes.dashboard_testing.scenario.validate_scenario", side_effect=ValueError("malformed graph")):
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=_compile_body())
|
|
assert resp.status_code == 422
|
|
assert resp.json()["detail"]["code"] == "VALIDATION_ERROR"
|
|
# #endregion Std.Semantics.TestCompileValidatorFailure
|
|
|
|
# #region Std.Semantics.TestCompileMissingField [C:2] [TYPE Function]
|
|
# @BRIEF Required-field omission -> FastAPI body-validation 422 with list detail.
|
|
def test_missing_required_fields_422(self) -> None:
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json={"agent_run_id": "run-1"}) # objective missing
|
|
assert resp.status_code == 422
|
|
assert isinstance(resp.json()["detail"], list)
|
|
# #endregion Std.Semantics.TestCompileMissingField
|
|
|
|
# #region Std.Semantics.TestCompileExtraForbid [C:2] [TYPE Function]
|
|
# @BRIEF extra=forbid rejects smuggled executable-code fields.
|
|
def test_extra_forbidden_field_422(self) -> None:
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=_compile_body(executable_code="import os"))
|
|
assert resp.status_code == 422
|
|
assert isinstance(resp.json()["detail"], list)
|
|
# #endregion Std.Semantics.TestCompileExtraForbid
|
|
|
|
# #region Std.Semantics.TestCompileRbacDenied [C:2] [TYPE Function]
|
|
# @BRIEF Authenticated user without WRITE permission -> 403.
|
|
def test_write_permission_denied_403(self) -> None:
|
|
client, _ = scenario_routes_client(user=scenario_routes_no_perm_user())
|
|
resp = client.post(self.PATH, json=_compile_body())
|
|
assert resp.status_code == 403
|
|
# #endregion Std.Semantics.TestCompileRbacDenied
|
|
|
|
# #region Std.Semantics.TestCompileUnauthenticated [C:2] [TYPE Function]
|
|
# @BRIEF No token -> 401 from the OAuth2 scheme before the route body runs.
|
|
def test_unauthenticated_401(self) -> None:
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
app.dependency_overrides[get_db] = lambda: MagicMock()
|
|
resp = TestClient(app).post(self.PATH, json={})
|
|
assert resp.status_code == 401
|
|
# #endregion Std.Semantics.TestCompileUnauthenticated
|
|
|
|
|
|
class TestValidateEndpoint:
|
|
"""POST /api/dashboard-testing/scenarios/validate — Api.DashboardTesting.Scenario.Validate."""
|
|
|
|
PATH = "/api/dashboard-testing/scenarios/validate"
|
|
|
|
# #region Std.Semantics.TestValidateSuccess [C:2] [TYPE Function]
|
|
# @BRIEF Happy path: all finding lists and graph metadata serialized.
|
|
def test_success_returns_findings(self) -> None:
|
|
result = SimpleNamespace(
|
|
valid=True,
|
|
errors=[SimpleNamespace(model_dump=lambda: {"code": "E1", "severity": "error"})],
|
|
warnings=[SimpleNamespace(model_dump=lambda: {"code": "W1"})],
|
|
blockers=[],
|
|
coverage=[{"case_id": "B01"}],
|
|
topological_order=["s1"],
|
|
graph_hash=SCENARIO_ROUTES_HASH,
|
|
)
|
|
with patch("src.api.routes.dashboard_testing.scenario.validate_scenario", return_value=result):
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=scenario_routes_scenario_json())
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["valid"] is True
|
|
assert data["errors"] == [{"code": "E1", "severity": "error"}]
|
|
assert data["warnings"] == [{"code": "W1"}]
|
|
assert data["blockers"] == []
|
|
assert data["coverage"] == [{"case_id": "B01"}]
|
|
assert data["topological_order"] == ["s1"]
|
|
assert data["graph_hash"] == SCENARIO_ROUTES_HASH
|
|
# #endregion Std.Semantics.TestValidateSuccess
|
|
|
|
# #region Std.Semantics.TestValidateValueError [C:2] [TYPE Function]
|
|
# @BRIEF Malformed graph raises ValueError -> 422 VALIDATION_ERROR.
|
|
def test_value_error_422(self) -> None:
|
|
with patch("src.api.routes.dashboard_testing.scenario.validate_scenario", side_effect=ValueError("cycle detected")):
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=scenario_routes_scenario_json())
|
|
assert resp.status_code == 422
|
|
assert resp.json()["detail"]["code"] == "VALIDATION_ERROR"
|
|
# #endregion Std.Semantics.TestValidateValueError
|
|
|
|
# #region Std.Semantics.TestValidateMalformedBody [C:2] [TYPE Function]
|
|
# @BRIEF Graph body missing required fields -> FastAPI 422.
|
|
def test_malformed_graph_body_422(self) -> None:
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json={"scenario_id": "x"})
|
|
assert resp.status_code == 422
|
|
assert isinstance(resp.json()["detail"], list)
|
|
# #endregion Std.Semantics.TestValidateMalformedBody
|
|
|
|
# #region Std.Semantics.TestValidateRbacDenied [C:2] [TYPE Function]
|
|
# @BRIEF Authenticated user without READ permission -> 403.
|
|
def test_read_permission_denied_403(self) -> None:
|
|
client, _ = scenario_routes_client(user=scenario_routes_no_perm_user())
|
|
resp = client.post(self.PATH, json=scenario_routes_scenario_json())
|
|
assert resp.status_code == 403
|
|
# #endregion Std.Semantics.TestValidateRbacDenied
|
|
|
|
|
|
class TestResolveEndpoint:
|
|
"""POST /api/dashboard-testing/scenarios/{id}/resolve — Api.DashboardTesting.Scenario.Resolve."""
|
|
|
|
PATH = "/api/dashboard-testing/scenarios/fi-0080_verify/resolve"
|
|
|
|
# #region Std.Semantics.TestResolveBody [C:1] [TYPE Function]
|
|
# @BRIEF Nested body: {"req": ..., "scenario": ...} (two body models, embedded by param name).
|
|
def _body(self, changes: list[dict] | None = None) -> dict:
|
|
return {
|
|
"req": {
|
|
"base_revision_hash": SCENARIO_ROUTES_HASH,
|
|
"changes": changes if changes is not None else [
|
|
{"kind": "parameter", "target": "test_date", "value": "2026-08-01", "reason": "fix date"},
|
|
],
|
|
},
|
|
"scenario": scenario_routes_scenario_json(),
|
|
}
|
|
# #endregion Std.Semantics.TestResolveBody
|
|
|
|
# #region Std.Semantics.TestResolveSuccess [C:2] [TYPE Function]
|
|
# @BRIEF Happy path: changes become typed ResolveChange, new revision returned with hash.
|
|
def test_success_returns_new_revision(self) -> None:
|
|
resolved = SimpleNamespace(
|
|
model_dump=lambda: {"scenario_id": "fi-0080_verify", "revision_hash": SCENARIO_ROUTES_HASH},
|
|
revision_hash=SCENARIO_ROUTES_HASH,
|
|
)
|
|
with patch("src.api.routes.dashboard_testing.scenario.resolve_scenario") as m_resolve:
|
|
m_resolve.return_value = resolved
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=self._body())
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["scenario"]["scenario_id"] == "fi-0080_verify"
|
|
assert data["validation"]["valid"] is True
|
|
assert data["validation"]["graph_hash"] == SCENARIO_ROUTES_HASH
|
|
change = m_resolve.call_args.args[1][0]
|
|
assert change.kind == "parameter"
|
|
assert change.target == "test_date"
|
|
assert change.value == "2026-08-01"
|
|
assert change.reason == "fix date"
|
|
assert m_resolve.call_args.kwargs["base_revision_hash"] == SCENARIO_ROUTES_HASH
|
|
# #endregion Std.Semantics.TestResolveSuccess
|
|
|
|
# #region Std.Semantics.TestResolveStale [C:2] [TYPE Function]
|
|
# @BRIEF Stale base revision -> 409 STALE_REVISION.
|
|
def test_stale_base_409(self) -> None:
|
|
with patch("src.api.routes.dashboard_testing.scenario.resolve_scenario", side_effect=ValueError("stale base revision abc != def")):
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=self._body())
|
|
assert resp.status_code == 409
|
|
assert resp.json()["detail"]["code"] == "STALE_REVISION"
|
|
# #endregion Std.Semantics.TestResolveStale
|
|
|
|
# #region Std.Semantics.TestResolveValueError [C:2] [TYPE Function]
|
|
# @BRIEF Non-stale resolver failure -> 422 VALIDATION_ERROR.
|
|
def test_value_error_422(self) -> None:
|
|
with patch("src.api.routes.dashboard_testing.scenario.resolve_scenario", side_effect=ValueError("unknown parameter 'x'")):
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=self._body())
|
|
assert resp.status_code == 422
|
|
assert resp.json()["detail"]["code"] == "VALIDATION_ERROR"
|
|
# #endregion Std.Semantics.TestResolveValueError
|
|
|
|
# #region Std.Semantics.TestResolveEmptyChanges [C:2] [TYPE Function]
|
|
# @BRIEF Empty change list is a no-op resolution (immutable revision preserved).
|
|
def test_empty_changes_accepted(self) -> None:
|
|
with patch("src.api.routes.dashboard_testing.scenario.resolve_scenario") as m_resolve:
|
|
m_resolve.return_value = SimpleNamespace(model_dump=lambda: {}, revision_hash=SCENARIO_ROUTES_HASH)
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json=self._body(changes=[]))
|
|
assert resp.status_code == 200
|
|
assert m_resolve.call_args.args[1] == []
|
|
# #endregion Std.Semantics.TestResolveEmptyChanges
|
|
|
|
# #region Std.Semantics.TestResolveMissingScenario [C:2] [TYPE Function]
|
|
# @BRIEF Missing nested scenario body -> FastAPI 422.
|
|
def test_missing_scenario_body_422(self) -> None:
|
|
client, _ = scenario_routes_client()
|
|
resp = client.post(self.PATH, json={"req": {"base_revision_hash": SCENARIO_ROUTES_HASH, "changes": []}})
|
|
assert resp.status_code == 422
|
|
assert isinstance(resp.json()["detail"], list)
|
|
# #endregion Std.Semantics.TestResolveMissingScenario
|
|
|
|
# #region Std.Semantics.TestResolveChangeMissingKind [C:2] [TYPE Function]
|
|
# @BRIEF Edge: change dict without 'kind' raises KeyError (only ValueError is caught) -> 500.
|
|
# Pins current behavior; a typed schema would reject it earlier.
|
|
def test_change_missing_kind_500(self) -> None:
|
|
client, _ = scenario_routes_client(raise_server_exceptions=False)
|
|
resp = client.post(self.PATH, json=self._body(changes=[{"target": "test_date"}]))
|
|
assert resp.status_code == 500
|
|
# #endregion Std.Semantics.TestResolveChangeMissingKind
|