Files
ss-tools/backend/tests/api/test_dashboard_testing.py

465 lines
24 KiB
Python

# #region Test.Api.DashboardTesting [C:4] [TYPE Module] [SEMANTICS testing,api,dashboard-testing,lifecycle,durability]
# @defgroup API contract + lifecycle durability tests for dashboard-testing endpoints.
# @LAYER Test
# @RELATION VERIFIES -> [Api.DashboardTesting]
# @RELATION BINDS_TO -> [BaselineEngine.Candidates.Create]
# @TEST_EDGE: candidate_persistence -> DraftArtifact row exists in DB after 201.
# @TEST_EDGE: request_decide_consume_lifecycle -> Full FSM transitions persist at each step.
# @TEST_EDGE: cross_candidate_gate_rejection -> Gate bound to A cannot consume on B (409).
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import json
import pytest
from src.core.database import SessionLocal
from src.core.cot_formatter import CotJsonFormatter
from src.models.agent_run import ApprovalGate, DraftArtifact
from .conftest import (
create_dashboard_testing_agent_run as _create_agent_run,
create_dashboard_testing_capture_artifact as _create_capture_artifact,
make_dashboard_testing_candidate_payload as _make_candidate_payload,
)
# #region Test.Api.DashboardTesting.RouterRegistered [C:2] [TYPE Function] [SEMANTICS test,api,dashboard-testing,registration]
# @BRIEF The dashboard-testing router is importable and declares its API prefix.
def test_router_registered():
"""T034: Verify router is importable and has correct routes."""
from src.api.routes.dashboard_testing import router
assert len(router.routes) >= 9
paths = [route.path for route in router.routes if hasattr(route, "path")]
assert "/api/dashboard-testing/query-model" in paths
assert "/api/dashboard-testing/structure-diff" in paths
assert "/api/dashboard-testing/verification-runs" in paths
# #endregion Test.Api.DashboardTesting.RouterRegistered
# #region Test.Api.DashboardTesting.LifecycleTests [C:4] [TYPE Class] [SEMANTICS test,api,dashboard-testing,lifecycle,durability]
# @BRIEF Prove DraftArtifact and ApprovalGate durability through HTTP lifecycle.
class TestLifecycleDurability:
"""API-level lifecycle durability — create, request, decide, consume, cross-candidate reject."""
# #region Test.Api.DashboardTesting.LifecycleTests.TestCreateCandidatePersistence [C:2] [TYPE Function] [SEMANTICS test,api,candidate,persistence]
# @BRIEF POST /baseline-candidates → 201 + DraftArtifact exists in fresh DB session.
# @TEST_EDGE: candidate_persistence -> DraftArtifact row queryable after request commits.
def test_create_candidate_persistence(self, dashboard_testing_client):
"""Create baseline candidate, verify DraftArtifact row survives in DB."""
setup_session = SessionLocal()
try:
run = _create_agent_run(setup_session)
run_id = run.id
artifact_id, sha256 = _create_capture_artifact(setup_session, run_id)
setup_session.commit()
finally:
setup_session.close()
payload = _make_candidate_payload(run_id, capture_artifact_ref=artifact_id, source_response_hash=sha256)
response = dashboard_testing_client.post(
"/api/dashboard-testing/baseline-candidates", json=payload
)
assert response.status_code == 201, (
f"Expected 201, got {response.status_code}: {response.text}"
)
data = response.json()
candidate_id = data["candidate_id"]
assert data["status"] == "draft"
verify_session = SessionLocal()
try:
draft = (
verify_session.query(DraftArtifact)
.filter(DraftArtifact.id == candidate_id)
.first()
)
assert draft is not None, f"DraftArtifact {candidate_id} not found in DB"
assert draft.kind == "baseline_candidate"
assert draft.run_id == run_id
assert (draft.capture_meta or {}).get("candidate_status") == "draft"
finally:
verify_session.close()
# #endregion Test.Api.DashboardTesting.LifecycleTests.TestCreateCandidatePersistence
# #region Test.Api.DashboardTesting.LifecycleTests.TestReleaseProvenance [C:2] [TYPE Function] [SEMANTICS test,baseline,release,provenance]
# @BRIEF A verified capture release id survives candidate creation for gate validation and review.
# @TEST_INVARIANT The release id comes from the server capture artifact, not the request body.
def test_candidate_carries_verified_capture_release(self, dashboard_testing_client):
session = SessionLocal()
try:
run = _create_agent_run(session)
artifact_id, sha256 = _create_capture_artifact(session, run.id)
capture = session.query(DraftArtifact).filter(DraftArtifact.id == artifact_id).one()
captured_release_id = capture.capture_meta["release_id"]
session.commit()
run_id = run.id
finally:
session.close()
payload = _make_candidate_payload(run_id, artifact_id, sha256)
assert "release_id" not in payload
response = dashboard_testing_client.post("/api/dashboard-testing/baseline-candidates", json=payload)
assert response.status_code == 201, response.text
verify = SessionLocal()
try:
draft = verify.query(DraftArtifact).filter(DraftArtifact.id == response.json()["candidate_id"]).one()
assert draft.capture_meta["release_id"] == captured_release_id
finally:
verify.close()
# #endregion Test.Api.DashboardTesting.LifecycleTests.TestReleaseProvenance
# #region Test.Api.DashboardTesting.LifecycleTests.TestFullLifecyclePersistence [C:2] [TYPE Function] [SEMANTICS test,api,candidate,approval,lifecycle]
# @BRIEF Full request→decide→consume lifecycle, verifying DB state after each step.
# @TEST_EDGE: request_decide_consume_lifecycle -> ApprovalGate FSM persists.
# @TEST_EDGE: 201 returned for approval-gate creation with OpenAPI-compliant body.
def test_full_lifecycle_persistence(self, dashboard_testing_client):
"""Create → request_approval → decide_confirm → consume, verify persistence at each step."""
setup_session = SessionLocal()
try:
run = _create_agent_run(setup_session)
run_id = run.id
artifact_id, sha256 = _create_capture_artifact(setup_session, run_id)
setup_session.commit()
finally:
setup_session.close()
response = dashboard_testing_client.post(
"/api/dashboard-testing/baseline-candidates",
json=_make_candidate_payload(run_id, capture_artifact_ref=artifact_id, source_response_hash=sha256),
)
assert response.status_code == 201, f"Create failed: {response.text}"
candidate_id = response.json()["candidate_id"]
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_id}/approval-gate",
json={
"agent_run_id": run_id,
"release_version": "v1.0.0",
"release_commit_hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b",
"reason": "approve this candidate",
"reason_required": False,
},
)
assert response.status_code == 201, f"Request approval failed: {response.text}"
gate_data = response.json()
gate_id = gate_data["gate_id"]
assert gate_data["status"] == "pending"
gate_session = SessionLocal()
try:
gate = gate_session.query(ApprovalGate).filter(ApprovalGate.id == gate_id).first()
assert gate is not None, f"ApprovalGate {gate_id} not in DB"
assert gate.status == "pending"
finally:
gate_session.close()
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_id}/approval-gate/{gate_id}/decide",
json={"decision": "confirm", "reason": "Reviewed capture and provenance"},
)
assert response.status_code == 200, f"Decide confirm failed: {response.text}"
assert response.json()["status"] == "confirmed"
decide_session = SessionLocal()
try:
gate = decide_session.query(ApprovalGate).filter(ApprovalGate.id == gate_id).first()
assert gate is not None
assert gate.status == "confirmed"
assert gate.actor_id == "test-user-lifecycle"
finally:
decide_session.close()
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_id}/approval-gate/{gate_id}/consume"
"?release_version=v1.0.0&release_commit_hash=9f86d081884c7d659a2feaa0c55ad015a3bf4f1b",
)
assert response.status_code == 200, f"Consume failed: {response.text}"
assert response.json()["consumed"] is True
consume_session = SessionLocal()
try:
gate = consume_session.query(ApprovalGate).filter(ApprovalGate.id == gate_id).first()
assert gate is not None
assert gate.status == "consumed", f"Expected consumed, got {gate.status}"
draft = (
consume_session.query(DraftArtifact)
.filter(DraftArtifact.id == candidate_id)
.first()
)
assert draft is not None
assert draft.persisted_at is not None, "Bound draft was not marked persisted"
metadata = draft.capture_meta or {}
assert metadata.get("bound_release_version") == "v1.0.0"
assert metadata.get("bound_release_commit_hash") == "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b"
finally:
consume_session.close()
# #endregion Test.Api.DashboardTesting.LifecycleTests.TestFullLifecyclePersistence
# #region Test.Api.DashboardTesting.LifecycleTests.TestCrossCandidateGateRejection [C:2] [TYPE Function] [SEMANTICS test,api,candidate,gate,rejection,cross-candidate]
# @BRIEF Gate bound to candidate A cannot be used to consume candidate B (409).
# @TEST_EDGE: cross_candidate_gate_rejection -> Consume with wrong gate returns 409.
def test_cross_candidate_gate_rejection(self, dashboard_testing_client):
"""Gate G1 bound to candidate A cannot consume on candidate B → 409."""
setup_session = SessionLocal()
try:
run = _create_agent_run(setup_session)
run_id = run.id
second_run = _create_agent_run(setup_session, environment_id=run.environment_id)
second_run_id = second_run.id
artifact_a_id, sha256_a = _create_capture_artifact(setup_session, run_id)
from src.models.dashboard_release import DashboardRelease
from src.schemas.dashboard_testing.catalog_revision import ExactCatalogRevision
captured = setup_session.get(DraftArtifact, artifact_a_id).capture_meta
release = setup_session.get(DashboardRelease, captured["release_id"])
selector = ExactCatalogRevision(kind="revision", catalog_id=captured["catalog_binding"]["catalog_id"],
catalog_revision_id=captured["catalog_binding"]["catalog_revision_id"])
artifact_b_id, sha256_b = _create_capture_artifact(setup_session, second_run_id,
release=release, catalog_selection=selector)
setup_session.commit()
finally:
setup_session.close()
payload_a = _make_candidate_payload(run_id, capture_artifact_ref=artifact_a_id, source_response_hash=sha256_a)
payload_a["label"] = "candidate-A"
response_a = dashboard_testing_client.post(
"/api/dashboard-testing/baseline-candidates", json=payload_a
)
assert response_a.status_code == 201
candidate_a_id = response_a.json()["candidate_id"]
payload_b = _make_candidate_payload(second_run_id, capture_artifact_ref=artifact_b_id, source_response_hash=sha256_b)
payload_b["label"] = "candidate-B"
response_b = dashboard_testing_client.post(
"/api/dashboard-testing/baseline-candidates", json=payload_b
)
assert response_b.status_code == 201
candidate_b_id = response_b.json()["candidate_id"]
gate_body = {
"agent_run_id": run_id,
"release_version": "v1.0.0",
"release_commit_hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b",
}
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_a_id}/approval-gate",
json=gate_body,
)
assert response.status_code == 201, f"Gate creation failed: {response.text}"
gate_a_id = response.json()["gate_id"]
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_a_id}/approval-gate/{gate_a_id}/decide",
json={"decision": "confirm", "reason": "Reviewed candidate A"},
)
assert response.status_code == 200
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_b_id}/approval-gate",
json={**gate_body, "agent_run_id": second_run_id},
)
assert response.status_code == 201, f"Gate creation failed: {response.text}"
gate_b_id = response.json()["gate_id"]
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_b_id}/approval-gate/{gate_b_id}/decide",
json={"decision": "confirm", "reason": "Reviewed candidate B"},
)
assert response.status_code == 200
consume_query = "?release_version=v1.0.0&release_commit_hash=9f86d081884c7d659a2feaa0c55ad015a3bf4f1b"
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_b_id}/approval-gate/{gate_a_id}/consume{consume_query}",
)
assert response.status_code == 409, (
f"Expected 409 (conflict) for cross-candidate gate consume, "
f"got {response.status_code}: {response.text}"
)
assert "gate" in response.json().get("detail", "").lower()
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_a_id}/approval-gate/{gate_a_id}/consume{consume_query}",
)
assert response.status_code == 200, (
f"Expected 200 consuming A with own gate, "
f"got {response.status_code}: {response.text}"
)
def persisted_state():
import json
from sqlalchemy import select
from src.models.agent_run import AgentRun, AgentRunEvent
from tests.services.dashboard_testing.test_catalog_write_transfer import _catalog_rows
with SessionLocal() as session:
state = _catalog_rows(session, selector.catalog_id)
for model in (AgentRun, AgentRunEvent, DraftArtifact, ApprovalGate):
owned = model.id.in_([run_id, second_run_id]) if model is AgentRun else model.run_id.in_([run_id, second_run_id])
rows = session.execute(select(model.__table__).where(owned)
.order_by(*model.__table__.primary_key.columns)).mappings()
state[model.__tablename__] = json.dumps([dict(row) for row in rows], sort_keys=True, default=str)
return state
prior_state = persisted_state()
response = dashboard_testing_client.post(
f"/api/dashboard-testing/baseline-candidates/{candidate_b_id}/approval-gate/{gate_b_id}/consume{consume_query}",
)
# B still owns its gate, but its frozen parent predates A's successful CAS successor.
assert response.status_code == 409
assert response.json()["detail"] == "CATALOG_CAS_CONFLICT"
assert persisted_state() == prior_state
# #endregion Test.Api.DashboardTesting.LifecycleTests.TestCrossCandidateGateRejection
# #endregion Test.Api.DashboardTesting.LifecycleTests
# #region Test.Api.DashboardTesting.QueryCapabilityFixtures [C:2] [TYPE TestFixture]
# @POST Actual environment resolver remains delegated; all forbidden query/storage seams are observed without I/O.
@pytest.fixture
def query_capability_spies(monkeypatch):
from src.api.routes.dashboard_testing import core
from src.services.dashboard_testing import query_executor
from src.services.agent_runs import artifacts
manager = Mock()
manager.get_environment.return_value = None
resolver = AsyncMock(wraps=core._resolve_env)
client, inspection, envelope = AsyncMock(), AsyncMock(), AsyncMock()
storage = Mock(side_effect=AssertionError("UNEXPECTED_QUERY_STORAGE"))
monkeypatch.setattr(core, "get_config_manager", lambda: manager)
monkeypatch.setattr(core, "_resolve_env", resolver)
monkeypatch.setattr(core, "get_superset_client", client)
monkeypatch.setattr(core, "inspect_dashboard_query_model", inspection)
monkeypatch.setattr(query_executor, "execute_dashboard_query_envelope", envelope)
monkeypatch.setattr(artifacts, "get_draft_storage", storage)
return SimpleNamespace(manager=manager, resolver=resolver, client=client,
inspection=inspection, envelope=envelope, storage=storage)
def _query_capability_payload():
return {"environment_id": "configured", "dashboard_id": 1, "chart_id": 128,
"dataset_id": 256, "result_key": "PRIVATE_QUERY_SELECTOR_SENTINEL",
"normalized_filters": {"schema_version": 1, "filters": [],
"filters_hash": "sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945"}}
def _assert_query_io_absent(spies):
spies.client.assert_not_awaited()
spies.inspection.assert_not_awaited()
spies.envelope.assert_not_awaited()
spies.storage.assert_not_called()
def _assert_query_capability_log(caplog, code, *, environment, resolved):
events = [json.loads(CotJsonFormatter().format(record)) for record in caplog.records
if getattr(record, "error_code", None) == code]
assert len(events) == 1
event = events[0]
assert event["src"] == "Api.DashboardTesting.ExecuteQuery"
assert event["marker"] == "EXPLORE"
assert event["payload"] == {"environment_id": environment, "environment_resolved": resolved,
"query_io_started": False, "wire_evidence_present": False}
assert "PRIVATE_QUERY_SELECTOR_SENTINEL" not in json.dumps(event)
# #endregion Test.Api.DashboardTesting.QueryCapabilityFixtures
# #region Test.Api.DashboardTesting.EnvironmentResolution [C:3] [TYPE Class] [SEMANTICS test,api,dashboard-testing,environment]
# @BRIEF Environment resolution through ConfigManager — 404 for unknown, success for valid.
class TestEnvironmentResolution:
"""API environment resolution — invalid IDs return 404, valid IDs proceed."""
# #region Test.Api.DashboardTesting.EnvironmentResolution.TestQueryModelUnknownEnv [C:2] [TYPE Function] [SEMANTICS test,api,environment,404]
# @BRIEF GET /query-model with unknown environment_id returns 404.
def test_query_model_unknown_environment(self, dashboard_testing_client):
"""Unknown environment_id returns 404 for inspect-query-model."""
response = dashboard_testing_client.get(
"/api/dashboard-testing/query-model",
params={"environment_id": "nonexistent", "dashboard_id": 1},
)
assert response.status_code == 404
assert "not found" in response.json()["detail"].lower()
# #endregion Test.Api.DashboardTesting.EnvironmentResolution.TestQueryModelUnknownEnv
# #region Test.Api.DashboardTesting.EnvironmentResolution.TestExecuteQueryUnknownEnv [C:2] [TYPE Function] [SEMANTICS test,api,environment,404]
# @BRIEF POST /queries/execute with unknown environment_id returns 404.
def test_execute_query_unknown_environment(self, dashboard_testing_client, query_capability_spies, caplog):
"""Unknown environment_id returns 404 for execute-query."""
response = dashboard_testing_client.post(
"/api/dashboard-testing/queries/execute",
json={
"environment_id": "nonexistent",
"dashboard_id": 1,
"chart_id": 128,
"dataset_id": 256,
"result_key": "count",
"normalized_filters": {"schema_version": 1, "filters": [],
"filters_hash": "sha256:4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945"},
},
)
assert response.status_code == 404
assert "not found" in response.json()["detail"].lower()
assert response.json() == {"detail": "Environment 'nonexistent' not found."}
query_capability_spies.resolver.assert_awaited_once_with("nonexistent")
query_capability_spies.manager.get_environment.assert_called_once_with("nonexistent")
_assert_query_io_absent(query_capability_spies)
_assert_query_capability_log(caplog, "ENVIRONMENT_MISSING", environment="nonexistent", resolved=False)
# #endregion Test.Api.DashboardTesting.EnvironmentResolution.TestExecuteQueryUnknownEnv
# #region Test.Api.DashboardTesting.EnvironmentResolution.TestNormalizeFiltersUnknownEnv [C:2] [TYPE Function] [SEMANTICS test,api,environment,404]
# @BRIEF POST /filters/normalize with unknown environment_id returns 404.
def test_normalize_filters_unknown_environment(self, dashboard_testing_client):
"""Unknown environment_id returns 404 for normalize-filters."""
response = dashboard_testing_client.post(
"/api/dashboard-testing/filters/normalize",
json={
"environment_id": "nonexistent",
"dashboard_id": 1,
"filter_inputs": [],
},
)
assert response.status_code == 404
assert "not found" in response.json()["detail"].lower()
# #endregion Test.Api.DashboardTesting.EnvironmentResolution.TestNormalizeFiltersUnknownEnv
# #endregion Test.Api.DashboardTesting.EnvironmentResolution
# #region Test.Api.DashboardTesting.QueryCapability [C:3] [TYPE TestSuite]
# @TEST_INVARIANT Api.DashboardTesting.ExecuteQuery: known requests remain explicit501 before query/storage; permissions and schema still fail closed.
class TestQueryCapability:
def test_known_environment_is_explicitly_unavailable(self, dashboard_testing_client, query_capability_spies, caplog):
query_capability_spies.manager.get_environment.return_value = SimpleNamespace(id="configured")
response = dashboard_testing_client.post("/api/dashboard-testing/queries/execute", json=_query_capability_payload())
assert response.status_code == 501
assert response.json() == {"detail": {"code": "CHART_RESPONSE_OWNED_OBSERVATION_REQUIRED"}}
query_capability_spies.resolver.assert_awaited_once_with("configured")
query_capability_spies.manager.get_environment.assert_called_once_with("configured")
_assert_query_io_absent(query_capability_spies)
_assert_query_capability_log(caplog, "CHART_RESPONSE_OWNED_OBSERVATION_REQUIRED", environment="configured", resolved=True)
def test_execute_permission_denied_before_environment(self, dashboard_testing_client, query_capability_spies):
from src.dependencies import get_current_user
from src.models.auth import User
user = User(id="query-no-execute", username="query-no-execute")
user.roles = []
dashboard_testing_client.app.dependency_overrides[get_current_user] = lambda: user
response = dashboard_testing_client.post("/api/dashboard-testing/queries/execute", json=_query_capability_payload())
assert response.status_code == 403
assert response.json() == {"detail": "Permission denied for dashboard:testing:EXECUTE"}
query_capability_spies.resolver.assert_not_awaited()
query_capability_spies.manager.get_environment.assert_not_called()
_assert_query_io_absent(query_capability_spies)
@pytest.mark.parametrize("extra", ["sql", "query_context", "endpoint"])
def test_raw_input_is_forbidden_before_environment(self, dashboard_testing_client, query_capability_spies, extra):
response = dashboard_testing_client.post("/api/dashboard-testing/queries/execute",
json={**_query_capability_payload(), extra: "PRIVATE_RAW_QUERY_SENTINEL"})
assert response.status_code == 422
assert [(issue["loc"], issue["type"]) for issue in response.json()["detail"]] == [(["body", extra], "extra_forbidden")]
query_capability_spies.resolver.assert_not_awaited()
_assert_query_io_absent(query_capability_spies)
# #endregion Test.Api.DashboardTesting.QueryCapability
# #endregion Test.Api.DashboardTesting