Files
ss-tools/backend/tests/api/test_load_testing_views.py
busya 488a8f349b test(backend): raise coverage to 95%+ statements and branches (97.8%/95.0%)
- ~60 new/extended test files across api, core, plugins, services, schemas:
  routes, superset clients, task_manager, lineage, git, translate,
  dashboard-testing, load-testing, migration, llm_analysis, scheduler, ssl
- .coveragerc: enable branch coverage; exclude src/__tests__ (test files)
  and src/scripts (CLI/ops tools) from the denominator
- bug fixes found while testing:
  * settings: PUT /settings/reports registered under duplicated prefix
  * schemas/lineage: FleetReportDTO missing run_status (route always 500)
  * dashboard_testing/baseline_inheritance: visual entry read wrong field
  * superset_client/_databases: logger extra name shadowed LogRecord attr
  * routes/datasets: _yaml_string_paths recursion without yield from
  * translate/sql_generator: restore explicit-type timestamp contract
  * baseline_catalog: remove unreachable dashboard_id fallback
- conftest fixes: pytest_plugins to rootdir conftest (pytest 9), test
  filename collision, TMPDIR-safe integration fixtures
2026-08-19 17:14:32 +03:00

377 lines
15 KiB
Python

# #region Test.LoadTesting.ApiViews [C:3] [TYPE Module] [SEMANTICS test,load-testing,api,compare,blast-radius]
# @BRIEF 040 Compare + blast-radius API contract tests (LOAD-FR-015) plus route-level wiring tests.
# @TEST_EDGE: missing_base_run -> 404 load run not found
# @TEST_EDGE: missing_current_run -> 404 load run not found
# @TEST_EDGE: run_not_owned -> 403 load run access denied
# @TEST_EDGE: empty_executions -> comparison with zero samples
# @TEST_EDGE: missing_blast_radius_report -> default {} echoed
# @RELATION BINDS_TO -> [Api.LoadTesting.Routes]
from datetime import datetime
from unittest.mock import patch
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, event
from sqlalchemy.orm import Session
from src.api.routes.load_testing import compare_runs_endpoint, run_blast_radius
from src.models.load_testing import ExecutionOutcome, LoadExecution, LoadRun, RunStatus
from src.models.mapping import Base, Environment
@pytest.fixture()
def db():
from sqlalchemy.pool import StaticPool
# StaticPool: TestClient runs requests on a worker thread, and plain
# sqlite:///:memory: gives each thread its own empty database. A single
# shared connection keeps the fixture tables visible to route handlers.
engine = create_engine(
"sqlite:///:memory:",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
event.listen(engine, "connect", lambda c, _: c.execute("PRAGMA foreign_keys=ON"))
Base.metadata.create_all(bind=engine)
session = Session(bind=engine)
session.add(Environment(id="env-dev", name="dev", url="https://dev.example", credentials_id="cred"))
session.commit()
yield session
session.close()
engine.dispose()
class _TestUser:
id = "test-user"
roles = []
class _Role:
def __init__(self, *, is_admin=False):
self.is_admin = is_admin
self.permissions = []
class _AdminUser:
id = "test-user"
roles = [_Role(is_admin=True)]
class _FakeTM:
async def create_task(self, _plugin_id, _params):
from types import SimpleNamespace
return SimpleNamespace(id="task-1")
def _add_run(db: Session, run_id: str, created_by: str = "test-user", **kw) -> LoadRun:
fields = dict(
id=run_id, environment_id="env-dev", dashboard_id=400, created_by=created_by,
status=RunStatus.COMPLETED, phase="terminal", effective_concurrency=2, total_executions=2,
)
fields.update(kw)
run = LoadRun(**fields)
db.add(run)
# Commit the run row before executions are added: the unit of work does not
# order load_runs before load_executions within a single flush here, and the
# FK on load_executions.run_id is enforced (see test_load_testing.py models).
db.commit()
return run
def _add_exec(db: Session, run_id: str, chart_id: int, *, upstream: int = 100, outcome: str = ExecutionOutcome.SUCCESS) -> LoadExecution:
ex = LoadExecution(
run_id=run_id, variation_id="v1", chart_id=chart_id, outcome=outcome,
filters_hash="f1",
upstream_latency_ms=upstream, queue_wait_ms=10, resource_wait_ms=20,
cache_state="hit", worker_id="w0",
)
db.add(ex)
return ex
# ── compare_runs_endpoint ──
def test_compare_success_deltas_and_new_charts(db: Session):
_add_run(db, "base-run")
_add_run(db, "cur-run")
_add_exec(db, "base-run", chart_id=1, upstream=100)
_add_exec(db, "cur-run", chart_id=1, upstream=150)
_add_exec(db, "cur-run", chart_id=2, upstream=200)
db.commit()
resp = compare_runs_endpoint(base_run_id="base-run", current_run_id="cur-run", db=db, current_user=_TestUser(), _=None)
by_chart = {c["chart_id"]: c for c in resp["per_chart"]}
assert by_chart[1]["status"] == "compared"
assert by_chart[1]["p50_delta_ms"] == 50
assert by_chart[1]["cache_state"] == {"hit": 1}
assert by_chart[2]["status"] == "new_in_current"
assert by_chart[2]["p50_delta_ms"] is None
assert resp["summary"] == {"compared": 1, "new_in_current": 1}
assert resp["new_consistency_findings"] == []
def test_compare_base_missing_404(db: Session):
_add_run(db, "cur-run")
db.commit()
with pytest.raises(HTTPException) as exc_info:
compare_runs_endpoint(base_run_id="nope", current_run_id="cur-run", db=db, current_user=_TestUser(), _=None)
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "load run not found"
def test_compare_current_missing_404(db: Session):
_add_run(db, "base-run")
db.commit()
with pytest.raises(HTTPException) as exc_info:
compare_runs_endpoint(base_run_id="base-run", current_run_id="nope", db=db, current_user=_TestUser(), _=None)
assert exc_info.value.status_code == 404
def test_compare_base_access_denied_403(db: Session):
_add_run(db, "base-run", created_by="someone-else")
_add_run(db, "cur-run")
db.commit()
with pytest.raises(HTTPException) as exc_info:
compare_runs_endpoint(base_run_id="base-run", current_run_id="cur-run", db=db, current_user=_TestUser(), _=None)
assert exc_info.value.status_code == 403
def test_compare_current_access_denied_403(db: Session):
_add_run(db, "base-run")
_add_run(db, "cur-run", created_by="someone-else")
db.commit()
with pytest.raises(HTTPException) as exc_info:
compare_runs_endpoint(base_run_id="base-run", current_run_id="cur-run", db=db, current_user=_TestUser(), _=None)
assert exc_info.value.status_code == 403
def test_compare_empty_runs_ok(db: Session):
_add_run(db, "base-run")
_add_run(db, "cur-run")
db.commit()
resp = compare_runs_endpoint(base_run_id="base-run", current_run_id="cur-run", db=db, current_user=_TestUser(), _=None)
assert resp["per_chart"] == []
assert resp["summary"] == {"compared": 0, "new_in_current": 0}
def test_compare_error_outcome_counted(db: Session):
_add_run(db, "base-run")
_add_run(db, "cur-run")
_add_exec(db, "base-run", chart_id=1, upstream=100)
_add_exec(db, "cur-run", chart_id=1, upstream=150, outcome=ExecutionOutcome.ERROR)
db.commit()
resp = compare_runs_endpoint(base_run_id="base-run", current_run_id="cur-run", db=db, current_user=_TestUser(), _=None)
cur = resp["per_chart"][0]
assert cur["status"] == "compared"
# no success samples on the current side -> percentile 0 -> delta -100 from base 100
assert cur["p50_delta_ms"] == -100
# ── run_blast_radius ──
def test_blast_radius_success(db: Session):
_add_run(db, "br-run", blast_radius_fingerprint="fp-abc", blast_radius_report={"dependent_dashboard_count": 2, "probes": 3})
db.commit()
resp = run_blast_radius("br-run", db=db, current_user=_TestUser(), _=None)
assert resp["load_run_id"] == "br-run"
assert resp["blast_radius_fingerprint"] == "fp-abc"
assert resp["blast_radius_report"] == {"dependent_dashboard_count": 2, "probes": 3}
def test_blast_radius_missing_report_defaults_empty(db: Session):
_add_run(db, "br-run2", blast_radius_fingerprint=None, blast_radius_report=None)
db.commit()
resp = run_blast_radius("br-run2", db=db, current_user=_TestUser(), _=None)
assert resp["blast_radius_fingerprint"] is None
assert resp["blast_radius_report"] == {}
def test_blast_radius_404(db: Session):
with pytest.raises(HTTPException) as exc_info:
run_blast_radius("missing", db=db, current_user=_TestUser(), _=None)
assert exc_info.value.status_code == 404
def test_blast_radius_forbidden_403(db: Session):
_add_run(db, "br-run3", created_by="someone-else")
db.commit()
with pytest.raises(HTTPException) as exc_info:
run_blast_radius("br-run3", db=db, current_user=_TestUser(), _=None)
assert exc_info.value.status_code == 403
# ── route-level wiring (TestClient + dependency_overrides) ──
class TestLoadTestingRoutes:
"""Router wiring: permission dependency enforced, endpoints reachable over HTTP."""
VALIDATE_BODY = {
"dashboard_id": 400, "environment_id": "env-dev", "stage": "dev", "pool_size": 20,
"concurrency_requested": 2, "execution_mode": "iterations", "iterations": 5,
"axes": {"filters": [{"region": "north"}]},
}
START_BODY = {
"dashboard_id": 400, "environment_id": "env-dev", "stage": "dev", "pool_size": 20,
"concurrency_requested": 2, "execution_mode": "iterations", "iterations": 5,
"axes": {"filters": [{"region": "north"}]},
}
APPROVAL_BODY = {
"dashboard_id": 400, "environment_id": "env-prod", "stage": "PROD", "pool_size": 20,
"concurrency_requested": 2, "execution_mode": "iterations", "iterations": 5,
"axes": {"filters": [{"region": "north"}]},
"approval_reason": "release window", "approval_id": "approver-1",
}
@staticmethod
def _make_client(db: Session, user=None, task_manager=None) -> TestClient:
from src.api.routes.load_testing import router
from src.core.database import get_db
from src.dependencies import get_current_user, get_task_manager
from src.schemas.auth import PermissionSchema, RoleSchema, User
if user is None:
user = User(
id="u1", username="tester", email="t@x.com", auth_source="LOCAL",
created_at=datetime.now(),
roles=[RoleSchema(id="r1", name="Tester", description="", is_admin=True,
permissions=[PermissionSchema(resource="dashboard:loadtest", action="EXECUTE")])],
)
app = FastAPI()
app.include_router(router)
app.dependency_overrides[get_db] = lambda: db
app.dependency_overrides[get_current_user] = lambda: user
app.dependency_overrides[get_task_manager] = lambda: task_manager or _FakeTM()
return TestClient(app)
@staticmethod
def _plain_user():
from src.schemas.auth import RoleSchema, User
return User(
id="u1", username="tester", email="t@x.com", auth_source="LOCAL", created_at=datetime.now(),
roles=[RoleSchema(id="r1", name="T", description="", is_admin=False, permissions=[])],
)
@staticmethod
def _executor_user():
from src.schemas.auth import PermissionSchema, RoleSchema, User
return User(
id="u1", username="tester", email="t@x.com", auth_source="LOCAL", created_at=datetime.now(),
roles=[RoleSchema(id="r1", name="T", description="", is_admin=False,
permissions=[PermissionSchema(resource="dashboard:loadtest", action="EXECUTE")])],
)
def test_validate_success(self, db: Session):
client = self._make_client(db)
resp = client.post("/api/load-testing/profiles/validate", json=self.VALIDATE_BODY)
assert resp.status_code == 200
assert resp.json()["valid"] is True
assert resp.json()["cap"] == 2
def test_validate_permission_denied(self, db: Session):
client = self._make_client(db, user=self._plain_user())
resp = client.post("/api/load-testing/profiles/validate", json=self.VALIDATE_BODY)
assert resp.status_code == 403
def test_validate_environment_not_found(self, db: Session):
client = self._make_client(db)
body = dict(self.VALIDATE_BODY, environment_id="env-missing")
resp = client.post("/api/load-testing/profiles/validate", json=body)
assert resp.status_code == 404
def test_start_success(self, db: Session):
client = self._make_client(db)
resp = client.post("/api/load-testing/runs/start", json=self.START_BODY)
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "queued"
assert data["task_id"] == "task-1"
assert db.get(LoadRun, data["load_run_id"]) is not None
def test_start_permission_denied(self, db: Session):
client = self._make_client(db, user=self._plain_user())
resp = client.post("/api/load-testing/runs/start", json=self.START_BODY)
assert resp.status_code == 403
def test_status_not_found(self, db: Session):
client = self._make_client(db)
resp = client.get("/api/load-testing/runs/nope/status")
assert resp.status_code == 404
def test_status_forbidden(self, db: Session):
_add_run(db, "run-route-other", created_by="someone-else")
client = self._make_client(db, user=self._executor_user())
resp = client.get("/api/load-testing/runs/run-route-other/status")
assert resp.status_code == 403
def test_stop_success(self, db: Session):
_add_run(db, "run-route-stop", created_by="test-user", status=RunStatus.STEADY, phase="steady")
db.commit()
client = self._make_client(db)
resp = client.post("/api/load-testing/runs/run-route-stop/stop")
assert resp.status_code == 200
assert resp.json()["status"] == "stopped_by_user"
assert db.get(LoadRun, "run-route-stop").stop_reason == "user_stop"
def test_stop_permission_denied(self, db: Session):
client = self._make_client(db, user=self._plain_user())
resp = client.post("/api/load-testing/runs/run-route-stop/stop")
assert resp.status_code == 403
def test_approval_success(self, db: Session):
from src.services.environment_resolver import ResolvedEnvironment
client = self._make_client(db)
prod_env = ResolvedEnvironment(id="env-prod", stage="PROD", is_production=True)
with patch("src.api.routes.load_testing.resolve_environment", return_value=prod_env):
resp = client.post("/api/load-testing/runs/approval", json=self.APPROVAL_BODY)
assert resp.status_code == 200
assert resp.json()["status"] == "approved"
def test_approval_non_prod_environment_400(self, db: Session):
client = self._make_client(db)
body = dict(self.APPROVAL_BODY, environment_id="env-dev", stage="dev")
resp = client.post("/api/load-testing/runs/approval", json=body)
assert resp.status_code == 400
def test_approval_permission_denied(self, db: Session):
client = self._make_client(db, user=self._plain_user())
resp = client.post("/api/load-testing/runs/approval", json=self.APPROVAL_BODY)
assert resp.status_code == 403
def test_compare_not_found(self, db: Session):
client = self._make_client(db)
resp = client.get("/api/load-testing/runs/compare?base_run_id=nope&current_run_id=nope2")
assert resp.status_code == 404
def test_compare_success(self, db: Session):
_add_run(db, "base-run")
_add_run(db, "cur-run")
_add_exec(db, "base-run", chart_id=1, upstream=100)
_add_exec(db, "cur-run", chart_id=1, upstream=150)
db.commit()
client = self._make_client(db)
resp = client.get("/api/load-testing/runs/compare?base_run_id=base-run&current_run_id=cur-run")
assert resp.status_code == 200
assert resp.json()["summary"]["compared"] == 1
def test_blast_radius_success(self, db: Session):
_add_run(db, "br-route", blast_radius_fingerprint="fp1", blast_radius_report={})
db.commit()
client = self._make_client(db)
resp = client.get("/api/load-testing/runs/br-route/blast-radius")
assert resp.status_code == 200
assert resp.json()["blast_radius_fingerprint"] == "fp1"
def test_blast_radius_not_found(self, db: Session):
client = self._make_client(db)
resp = client.get("/api/load-testing/runs/br-missing/blast-radius")
assert resp.status_code == 404
# #endregion Test.LoadTesting.ApiViews