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

232 lines
10 KiB
Python

# #region Test.ScenarioRun.Center [C:3] [TYPE Module] [SEMANTICS test,scenario,run,center,api,list]
# @defgroup ScenarioRun Global run operations center list route tests (045 RUNMON-FR-009).
# @LAYER Test
# @RELATION VERIFIES -> [Api.ScenarioRun.Center.List]
# @TEST_EDGE: empty->empty envelope; filters->scoped rows; waiting_for_me->only pending-human runs
# @TEST_EDGE: pending_approval->only pending_approval runs (UX-7 badge projection); page_size=1 bounded
from __future__ import annotations
from datetime import UTC, datetime
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from src.api.routes.dashboard_testing.scenario_run_center import router
from src.core.database import get_db
from src.dependencies import get_current_user
from src.models.scenario_checkpoint import HumanCheckpoint
from src.models.scenario_registry import ScenarioRegistryEntry
from src.models.scenario_run import ScenarioRun
def _register_all_model_tables() -> None:
"""Import every model module so Base.metadata.create_all resolves all FK targets
(dashboard_release -> deployment 'n', git, etc.) without weakening FK enforcement."""
import pkgutil
import src.models as _models_pkg
for _mod in pkgutil.iter_modules(_models_pkg.__path__):
__import__(f"src.models.{_mod.name}")
class RunCenterEnv:
def __init__(self):
_register_all_model_tables()
self.engine = create_engine("sqlite:///:memory:", poolclass=StaticPool, connect_args={"check_same_thread": False})
event.listen(self.engine, "connect", lambda c, _: c.execute("PRAGMA foreign_keys=ON"))
from src.models.mapping import Base
Base.metadata.create_all(self.engine)
self.session_factory = sessionmaker(bind=self.engine)
def seed(self) -> None:
session = self.session_factory()
try:
now = datetime.now(UTC)
session.add(ScenarioRegistryEntry(
scenario_id="s-1", scenario_key="sales-smoke", name="Sales smoke",
dashboard_id=42, environment_ids=["ss-preprod"], owner_id="u-1",
owner_username="dev.engineer", tags=[], metadata_version="m1",
current_revision_id="r-1", lifecycle_status="READY", validation_status="valid",
created_at=now, last_modified_at=now,
))
session.add(ScenarioRun(
id="run-1", scenario_id="s-1", scenario_revision_id="r-1",
scenario_content_hash="a" * 64, environment_id="ss-preprod",
status="waiting_human", phase="waiting_human", trigger_source="manual",
idempotency_key="idem-1", runner_plan={}, parameter_bindings={}, target_snapshot={},
created_at=now,
))
session.add(ScenarioRun(
id="run-2", scenario_id="s-1", scenario_revision_id="r-1",
scenario_content_hash="b" * 64, environment_id="ss-preprod",
status="passed", phase="terminal", trigger_source="schedule",
idempotency_key="idem-2", runner_plan={}, parameter_bindings={}, target_snapshot={},
created_at=now, started_at=now, finished_at=now,
))
# Flush parents first: the UnitOfWork may order plain-FK child inserts before
# parents when the full model graph contains FK cycles; production code always
# flushes per row. FK enforcement stays enabled (no weakening).
session.flush()
session.add(HumanCheckpoint(
id="cp-1", run_id="run-1", logical_step_id="human-review",
status="pending", evidence_refs=["artifact://run-1/e.png"],
))
session.commit()
finally:
session.close()
def client(self, *, admin: bool = True, owner_id: str = "u-admin", owner_username: str = "admin") -> TestClient:
app = FastAPI()
app.include_router(router)
def _override_db():
session = self.session_factory()
try:
yield session
finally:
session.close()
from src.models.auth import Permission, Role, User
if admin:
role = Role(id="r-admin", name="Admin", is_admin=True)
else:
role = Role(id="r-run", name="Runner", is_admin=False)
role.permissions = [Permission(resource="scenario", action="RUN")]
user = User(id=owner_id, username=owner_username, email="a@t.co")
user.roles = [role]
app.dependency_overrides[get_current_user] = lambda: user
app.dependency_overrides[get_db] = _override_db
return TestClient(app)
def close(self) -> None:
self.engine.dispose()
@pytest.fixture
def run_center_env():
env = RunCenterEnv()
yield env
env.close()
def test_list_runs_empty_envelope(run_center_env):
resp = run_center_env.client().get("/api/scenario-runs")
assert resp.status_code == 200
assert resp.json() == {"items": [], "total": 0}
def test_list_runs_with_filters_and_checkpoint_projection(run_center_env):
run_center_env.seed()
client = run_center_env.client()
body = client.get("/api/scenario-runs").json()
assert body["total"] == 2
waiting = next(item for item in body["items"] if item["id"] == "run-1")
assert waiting["scenario_key"] == "sales-smoke"
assert waiting["pending_checkpoint"]["logical_step_id"] == "human-review"
assert waiting["pending_checkpoint"]["evidence_refs"] == ["artifact://run-1/e.png"]
assert client.get("/api/scenario-runs", params={"status": "passed"}).json()["total"] == 1
assert client.get("/api/scenario-runs", params={"trigger_source": "manual"}).json()["total"] == 1
assert client.get("/api/scenario-runs", params={"owner": "dev.engineer"}).json()["total"] == 2
def test_waiting_for_me_returns_only_pending_human_runs(run_center_env):
run_center_env.seed()
body = run_center_env.client().get("/api/scenario-runs", params={"waiting_for_me": True}).json()
assert body["total"] == 1
assert body["items"][0]["id"] == "run-1"
def _seed_pending_approval_runs(env: RunCenterEnv) -> None:
"""Self-contained seeding so the shared seed() totals used by earlier tests stay intact."""
session = env.session_factory()
try:
now = datetime.now(UTC)
for i, (run_id, idem) in enumerate([("run-pa-1", "idem-pa-1"), ("run-pa-2", "idem-pa-2")]):
session.add(ScenarioRun(
id=run_id, scenario_id="s-1", scenario_revision_id="r-1",
scenario_content_hash=chr(ord("c") + i) * 64, environment_id="ss-prod",
status="pending_approval", phase="preflight", trigger_source="schedule",
idempotency_key=idem, runner_plan={}, parameter_bindings={}, target_snapshot={},
created_at=now,
))
session.commit()
finally:
session.close()
def test_pending_approval_projection_returns_only_pending_approval_runs(run_center_env):
run_center_env.seed()
_seed_pending_approval_runs(run_center_env)
client = run_center_env.client()
body = client.get("/api/scenario-runs", params={"pending_approval": True}).json()
assert body["total"] == 2
assert {item["id"] for item in body["items"]} == {"run-pa-1", "run-pa-2"}
assert all(item["status"] == "pending_approval" for item in body["items"])
assert all(item["pending_checkpoint"] is None for item in body["items"])
# waiting_for_me semantics unchanged: pending-approval runs are not human checkpoints.
waiting = client.get("/api/scenario-runs", params={"waiting_for_me": True}).json()
assert waiting["total"] == 1
assert waiting["items"][0]["id"] == "run-1"
# Same listing visibility: the unfiltered listing still sees every run.
assert client.get("/api/scenario-runs").json()["total"] == 4
def test_pending_approval_projection_bounded_envelope(run_center_env):
run_center_env.seed()
_seed_pending_approval_runs(run_center_env)
client = run_center_env.client()
body = client.get("/api/scenario-runs", params={"pending_approval": True, "page_size": 1}).json()
assert body["total"] == 2
assert len(body["items"]) == 1
def test_list_runs_pages_are_consistent_with_total(run_center_env):
"""Honest pagination: each page is a stable slice and `total` is the same server count."""
run_center_env.seed()
client = run_center_env.client()
page_one = client.get("/api/scenario-runs", params={"page": 1, "page_size": 1}).json()
page_two = client.get("/api/scenario-runs", params={"page": 2, "page_size": 1}).json()
assert page_one["total"] == 2
assert page_two["total"] == 2
assert len(page_one["items"]) == 1
assert len(page_two["items"]) == 1
assert page_one["items"][0]["id"] != page_two["items"][0]["id"]
def test_center_rejects_unsupported_filter_values(run_center_env):
"""SEC-01: free-form status/trigger_source are rejected as typed 422, not silently empty."""
run_center_env.seed()
client = run_center_env.client()
bad_status = client.get("/api/scenario-runs", params={"status": "archive"})
assert bad_status.status_code == 422
assert bad_status.json()["detail"]["code"] == "RUN_CENTER_QUERY_INVALID"
bad_trigger = client.get("/api/scenario-runs", params={"trigger_source": "webhook"})
assert bad_trigger.status_code == 422
assert bad_trigger.json()["detail"]["code"] == "RUN_CENTER_QUERY_INVALID"
def test_center_hides_foreign_scenario_runs_from_non_owners(run_center_env):
"""SEC-01: a non-admin sees only runs of scenarios they own; admin is unfiltered."""
run_center_env.seed()
owner = run_center_env.client(admin=False, owner_id="u-1", owner_username="dev.engineer")
assert owner.get("/api/scenario-runs").json()["total"] == 2 # both seeded runs belong to s-1/u-1
stranger = run_center_env.client(admin=False, owner_id="u-stranger", owner_username="stranger")
assert stranger.get("/api/scenario-runs").json() == {"items": [], "total": 0}
assert run_center_env.client().get("/api/scenario-runs").json()["total"] == 2
# #endregion Test.ScenarioRun.Center