407 lines
17 KiB
Python
407 lines
17 KiB
Python
# #region Test.Api.EnvironmentsStats [C:3] [TYPE Module] [SEMANTICS test,environments,stats,api]
|
|
# @BRIEF Tests for GET /api/environments/stats — counts, health probes, cache, error paths.
|
|
# @RELATION BINDS_TO -> [Api.Environments.EnvironmentsApi]
|
|
# @TEST_EDGE: env_unreachable -> status "error", reachable False, counts zero
|
|
# @TEST_EDGE: profile_binding_failure -> mine defaults to 0
|
|
# @TEST_EDGE: stats_fetch_failure -> status "error", counts zero
|
|
# @TEST_EDGE: cache_hit -> second request serves cached counts
|
|
# @TEST_EDGE: forbidden -> 403 without environments:READ
|
|
|
|
import os
|
|
|
|
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
|
|
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:")
|
|
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-tests")
|
|
os.environ.setdefault("ENCRYPTION_KEY", "MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=") # gitleaks:allow
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
_src = str(Path(__file__).resolve().parent.parent.parent / "src")
|
|
if _src not in sys.path:
|
|
sys.path.insert(0, _src)
|
|
|
|
from src.services.environment_stats_cache import env_stats_cache
|
|
|
|
|
|
def _make_env(id: str = "env-1", name: str = "Dev"):
|
|
env = MagicMock()
|
|
env.id = id
|
|
env.name = name
|
|
return env
|
|
|
|
|
|
def _make_superset_client(dashboards=None, page_error=None, summary_error=None):
|
|
client = AsyncMock()
|
|
client.get_dashboards_page.return_value = {"result": []}
|
|
if page_error is not None:
|
|
client.get_dashboards_page.side_effect = page_error
|
|
client.get_dashboards_summary.return_value = dashboards if dashboards is not None else []
|
|
if summary_error is not None:
|
|
client.get_dashboards_summary.side_effect = summary_error
|
|
return client
|
|
|
|
|
|
def _make_client(overrides: dict | None = None, is_admin: bool = True) -> TestClient:
|
|
from src.api.routes.environments import router
|
|
from src.core.database import get_db
|
|
from src.dependencies import get_config_manager, get_current_user
|
|
from src.schemas.auth import User, RoleSchema
|
|
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
|
|
mock_user = User(
|
|
id="admin-1", username="admin", email="admin@x.com",
|
|
auth_source="LOCAL",
|
|
created_at=__import__("datetime").datetime.now(),
|
|
roles=[RoleSchema(
|
|
id="r1", name="Admin" if is_admin else "Viewer", description="",
|
|
is_admin=is_admin, permissions=[],
|
|
)],
|
|
)
|
|
|
|
defaults = {
|
|
get_db: lambda: MagicMock(),
|
|
get_current_user: lambda: mock_user,
|
|
get_config_manager: lambda: MagicMock(),
|
|
}
|
|
if overrides:
|
|
defaults.update(overrides)
|
|
for dep, mock_fn in defaults.items():
|
|
app.dependency_overrides[dep] = mock_fn
|
|
return TestClient(app)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _clear_stats_cache():
|
|
"""Process-local stats cache must not leak counts between tests."""
|
|
env_stats_cache._entries.clear()
|
|
env_stats_cache._inflight.clear()
|
|
yield
|
|
env_stats_cache._entries.clear()
|
|
env_stats_cache._inflight.clear()
|
|
|
|
|
|
class TestGetEnvironmentStats:
|
|
"""GET /api/environments/stats"""
|
|
|
|
def test_stats_success_with_counts(self):
|
|
"""Happy path: total/published/drafts/mine computed, reachable ok."""
|
|
env = _make_env(id="env-1", name="Dev")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
dashboards = [
|
|
{"id": 1, "status": "published", "owners": [{"username": "alice"}], "modified_by": "alice"},
|
|
{"id": 2, "status": "draft", "owners": [{"username": "bob"}], "modified_by": "bob"},
|
|
]
|
|
superset = _make_superset_client(dashboards=dashboards)
|
|
resolve_aliases = AsyncMock(return_value=["alice"])
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client", return_value=superset),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "alice",
|
|
"superset_username": "Alice",
|
|
}),
|
|
patch("src.api.routes.environments._resolve_profile_actor_aliases", new=resolve_aliases),
|
|
patch("src.api.routes.environments._matches_dashboard_actor_aliases", side_effect=[True, False]),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
assert resp.status_code == 200
|
|
items = resp.json()
|
|
assert len(items) == 1
|
|
item = items[0]
|
|
assert item["env_id"] == "env-1"
|
|
assert item["name"] == "Dev"
|
|
assert item["total"] == 2
|
|
assert item["published"] == 1
|
|
assert item["drafts"] == 1
|
|
assert item["mine"] == 1
|
|
assert item["reachable"] is True
|
|
assert item["status"] == "ok"
|
|
assert item["error"] is None
|
|
assert item["latency_ms"] is not None
|
|
resolve_aliases.assert_awaited_once_with(env, "alice")
|
|
|
|
def test_stats_aliases_empty_falls_back_to_username(self):
|
|
"""Alias resolution returning [] falls back to the bound username for mine counts."""
|
|
env = _make_env(id="env-1", name="")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
dashboards = [
|
|
{"id": 1, "status": "published", "owners": [{"username": "alice"}], "modified_by": None},
|
|
]
|
|
superset = _make_superset_client(dashboards=dashboards)
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client", return_value=superset),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "alice",
|
|
"superset_username": "Alice",
|
|
}),
|
|
patch("src.api.routes.environments._resolve_profile_actor_aliases", new=AsyncMock(return_value=[])),
|
|
patch("src.api.routes.environments._matches_dashboard_actor_aliases", return_value=True),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
item = resp.json()[0]
|
|
# Empty name falls back to env id; empty aliases fall back to the bound username.
|
|
assert item["name"] == "env-1"
|
|
assert item["mine"] == 1
|
|
assert item["total"] == 1
|
|
|
|
def test_stats_no_bound_username_mine_zero(self):
|
|
"""Anonymous user (no superset username) gets mine=0 and skips alias resolution."""
|
|
env = _make_env(id="env-1")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
dashboards = [{"id": 1, "status": "published"}]
|
|
superset = _make_superset_client(dashboards=dashboards)
|
|
resolve_aliases = AsyncMock(return_value=["x"])
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client", return_value=superset),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "",
|
|
"superset_username": "",
|
|
}),
|
|
patch("src.api.routes.environments._resolve_profile_actor_aliases", new=resolve_aliases),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
item = resp.json()[0]
|
|
assert item["total"] == 1
|
|
assert item["published"] == 1
|
|
assert item["mine"] == 0
|
|
resolve_aliases.assert_not_awaited()
|
|
|
|
def test_stats_raw_username_only(self):
|
|
"""Normalized username empty: raw superset username is used as the bound identity."""
|
|
env = _make_env(id="env-1")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
dashboards = [{"id": 1, "status": "draft"}]
|
|
superset = _make_superset_client(dashboards=dashboards)
|
|
resolve_aliases = AsyncMock(return_value=["bob"])
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client", return_value=superset),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "",
|
|
"superset_username": " Bob ",
|
|
}),
|
|
patch("src.api.routes.environments._resolve_profile_actor_aliases", new=resolve_aliases),
|
|
patch("src.api.routes.environments._matches_dashboard_actor_aliases", return_value=True),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
item = resp.json()[0]
|
|
assert item["mine"] == 1
|
|
resolve_aliases.assert_awaited_once_with(env, "bob")
|
|
|
|
def test_stats_profile_binding_exception_defaults_mine_zero(self):
|
|
"""Profile binding failure degrades gracefully: mine counts default to 0."""
|
|
env = _make_env(id="env-1")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
dashboards = [{"id": 1, "status": "published"}]
|
|
superset = _make_superset_client(dashboards=dashboards)
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client", return_value=superset),
|
|
patch("src.api.routes.environments._get_profile_filter_binding",
|
|
side_effect=RuntimeError("profile service down")),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
assert resp.status_code == 200
|
|
item = resp.json()[0]
|
|
assert item["mine"] == 0
|
|
assert item["total"] == 1
|
|
assert item["status"] == "ok"
|
|
|
|
def test_stats_probe_failure_marks_env_unreachable(self):
|
|
"""Unreachable env: health probe failure yields status error, reachable False."""
|
|
env = _make_env(id="env-1")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
superset = _make_superset_client(page_error=RuntimeError("Connection refused"))
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client", return_value=superset),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "",
|
|
"superset_username": "",
|
|
}),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
item = resp.json()[0]
|
|
assert item["status"] == "error"
|
|
assert item["reachable"] is False
|
|
assert item["error"] == "Connection refused"
|
|
assert item["total"] == 0
|
|
assert item["mine"] == 0
|
|
assert item["latency_ms"] is not None
|
|
|
|
def test_stats_client_factory_failure(self):
|
|
"""Client registry failure (timeout) marks the env unreachable."""
|
|
env = _make_env(id="env-1")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client",
|
|
side_effect=TimeoutError("client timeout")),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "",
|
|
"superset_username": "",
|
|
}),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
item = resp.json()[0]
|
|
assert item["status"] == "error"
|
|
assert item["reachable"] is False
|
|
assert item["total"] == 0
|
|
|
|
def test_stats_counts_fetch_failure(self):
|
|
"""Probe ok but catalog scan fails: status error, counts zero, error set."""
|
|
env = _make_env(id="env-1")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
superset = _make_superset_client(summary_error=RuntimeError("catalog scan failed"))
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client", return_value=superset),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "",
|
|
"superset_username": "",
|
|
}),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
item = resp.json()[0]
|
|
assert item["status"] == "error"
|
|
assert item["reachable"] is False
|
|
assert item["total"] == 0
|
|
assert item["error"] == "catalog scan failed"
|
|
|
|
def test_stats_cache_hit_on_second_request(self):
|
|
"""Second request within TTL serves cached counts without re-running the catalog scan."""
|
|
env = _make_env(id="env-1")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env]
|
|
|
|
dashboards = [{"id": 1, "status": "published"}]
|
|
superset = _make_superset_client(dashboards=dashboards)
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client", return_value=superset),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "alice",
|
|
"superset_username": "Alice",
|
|
}),
|
|
patch("src.api.routes.environments._resolve_profile_actor_aliases",
|
|
new=AsyncMock(return_value=["alice"])),
|
|
patch("src.api.routes.environments._matches_dashboard_actor_aliases", return_value=True),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
first = client.get("/api/environments/stats")
|
|
second = client.get("/api/environments/stats")
|
|
assert first.status_code == 200
|
|
assert second.status_code == 200
|
|
assert first.json() == second.json()
|
|
# Cached: the expensive catalog scan ran exactly once across both requests.
|
|
assert superset.get_dashboards_summary.await_count == 1
|
|
|
|
def test_stats_multiple_environments_one_unreachable(self):
|
|
"""Concurrent probes: one reachable env + one unreachable env both reported."""
|
|
env_ok = _make_env(id="env-1", name="Dev")
|
|
env_bad = _make_env(id="env-2", name="Broken")
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = [env_ok, env_bad]
|
|
|
|
superset_ok = _make_superset_client(dashboards=[{"id": 1, "status": "published"}])
|
|
|
|
from src.dependencies import get_config_manager
|
|
with (
|
|
patch("src.api.routes.environments.get_superset_client",
|
|
side_effect=[superset_ok, TimeoutError("no route to host")]),
|
|
patch("src.api.routes.environments._get_profile_filter_binding", return_value={
|
|
"superset_username_normalized": "",
|
|
"superset_username": "",
|
|
}),
|
|
):
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
items = resp.json()
|
|
assert len(items) == 2
|
|
assert items[0]["env_id"] == "env-1"
|
|
assert items[0]["status"] == "ok"
|
|
assert items[0]["total"] == 1
|
|
assert items[1]["env_id"] == "env-2"
|
|
assert items[1]["status"] == "error"
|
|
assert items[1]["reachable"] is False
|
|
assert items[1]["total"] == 0
|
|
|
|
def test_stats_envs_not_a_list(self):
|
|
"""Non-list environments config degrades to an empty stats response."""
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = None
|
|
|
|
from src.dependencies import get_config_manager
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
assert resp.status_code == 200
|
|
assert resp.json() == []
|
|
|
|
def test_stats_empty_envs(self):
|
|
"""No configured environments yields an empty stats response."""
|
|
mock_config = MagicMock()
|
|
mock_config.get_environments.return_value = []
|
|
|
|
from src.dependencies import get_config_manager
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/environments/stats")
|
|
assert resp.status_code == 200
|
|
assert resp.json() == []
|
|
|
|
def test_stats_forbidden_without_permission(self):
|
|
"""Non-admin user without environments:READ gets 403 before any env work."""
|
|
mock_config = MagicMock()
|
|
|
|
from src.dependencies import get_config_manager
|
|
client = _make_client(
|
|
{get_config_manager: lambda: mock_config},
|
|
is_admin=False,
|
|
)
|
|
resp = client.get("/api/environments/stats")
|
|
assert resp.status_code == 403
|
|
assert "Permission denied" in resp.json()["detail"]
|
|
mock_config.get_environments.assert_not_called()
|
|
# #endregion Test.Api.EnvironmentsStats
|