567 lines
23 KiB
Python
567 lines
23 KiB
Python
# #region Test.Api.DashboardTesting.Fixtures [C:3] [TYPE Module] [SEMANTICS testing,api,dashboard-testing,fixtures,auth]
|
|
# @defgroup Shared deterministic fixtures and builders for dashboard-testing API tests.
|
|
# @LAYER Test
|
|
# @RELATION BINDS_TO -> [Api.DashboardTesting]
|
|
from __future__ import annotations
|
|
|
|
from itertools import count
|
|
from types import SimpleNamespace
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
from uuid import uuid4
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
from src.dependencies import get_current_user
|
|
from src.models.agent_run import AgentRun
|
|
from src.models.auth import Role, User
|
|
from src.models.git import GitRepository, GitServerConfig
|
|
|
|
_VERIFICATION_REPOSITORY_DASHBOARD_IDS = count(9001)
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.MakeAdminUser [C:1] [TYPE Function] [SEMANTICS test,api,dashboard-testing,auth]
|
|
def make_dashboard_testing_admin_user() -> User:
|
|
admin_role = Role(id="admin-role-test-001", name="Admin", is_admin=True)
|
|
user = User(id="test-user-lifecycle", username="tester", email="tester@test.com")
|
|
user.roles = [admin_role]
|
|
return user
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.MakeAdminUser
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.CreateCaptureArtifact [C:2] [TYPE Function] [SEMANTICS test,api,dashboard-testing,capture,artifact]
|
|
# @BRIEF Issue current authority from independently authored original query/response bytes and explicit DB scope.
|
|
# @POST Returns the actual issued capture ID/hash; protected bytes and frozen release/source/catalog context agree.
|
|
# @RATIONALE Synthetic fixture input enters the real issuer; API lifecycle assertions cannot be authorized by copied capture metadata.
|
|
def create_dashboard_testing_capture_artifact(session, run_id: str, *, release=None,
|
|
catalog_selection=None, response_bytes: bytes | None = None) -> tuple[str, str]:
|
|
from hashlib import sha256
|
|
from dashboard_candidate_fixture_requests import _fixture_capture_parts, _canonical, _FILTERS_HASH
|
|
from tests.services.dashboard_testing.conftest import create_candidate_release_fixture
|
|
from src.schemas.dashboard_testing import CaptureCandidateRequest, NormalizedValue
|
|
from src.schemas.dashboard_testing.catalog_revision import ExactCatalogRevision
|
|
from src.services.agent_runs.artifacts import get_draft_storage
|
|
from src.services.dashboard_testing.catalog_capture_binding import freeze_catalog_selection
|
|
from src.services.dashboard_testing.catalog_store import seed_catalog
|
|
from src.services.dashboard_testing.query_envelope import QueryExecutionEnvelope
|
|
from src.services.dashboard_testing.reference_source import build_reference_source
|
|
from src.services.dashboard_testing.result_authority import capture_context_sha256, issue_result_authority
|
|
from src.services.dashboard_testing.scenario.capture_profile import capture_profile_snapshot
|
|
|
|
run = session.get(AgentRun, run_id)
|
|
if run is None or run.intent != "manual_reference_capture":
|
|
raise ValueError("API_FIXTURE_OWNED_RUN_REQUIRED")
|
|
if (release is None) != (catalog_selection is None):
|
|
raise ValueError("API_FIXTURE_RELEASE_AND_CATALOG_REQUIRED")
|
|
if release is None:
|
|
release = create_candidate_release_fixture(session, actor=run.user_id, environment_id=run.environment_id)
|
|
seed = seed_catalog(session, repository=release.repository_id, dashboard_key="dashboard-42",
|
|
actor_id=run.user_id, reason="Explicit API synthetic native fixture", idempotency_key=str(uuid4()))
|
|
catalog_selection = ExactCatalogRevision(kind="revision", catalog_id=seed.revision.catalog_id,
|
|
catalog_revision_id=seed.revision.catalog_revision_id)
|
|
frozen = freeze_catalog_selection(session, catalog_selection, release, 42)
|
|
storage = get_draft_storage()
|
|
request_bytes, literal_response, descriptor, value, policy = _fixture_capture_parts(run_id)
|
|
raw = literal_response if response_bytes is None else response_bytes
|
|
storage.store(run_id, descriptor.native_request.sha256, request_bytes)
|
|
url = "https://superset.example/superset/dashboard/42/"
|
|
url_ref = storage.store(run_id, sha256(url.encode()).hexdigest(), url.encode())
|
|
filters = {"schema_version": 1, "filters": [], "filters_hash": _FILTERS_HASH}
|
|
source = build_reference_source(url=url, url_kind="dashboard", source_url_ref=url_ref,
|
|
environment_id=run.environment_id, dashboard_id=42, filters=filters, query_model_fingerprint="sha256:" + "c" * 64)
|
|
identity = sha256(_canonical({key: item for key, item in descriptor.model_dump(mode="json").items()
|
|
if key != "native_request"})).hexdigest()
|
|
run.context_snapshot = {"release_id": release.id, "reference_source": source, "filters_hash": _FILTERS_HASH,
|
|
"query_model_fingerprint": source["query_model_fingerprint"], "capture_profile": capture_profile_snapshot("default"),
|
|
"catalog_binding": frozen.model_dump(mode="json"),
|
|
"native_result_policy": {"schema_version": 1, "result_identity_sha256": identity, "comparison_policy": policy}}
|
|
session.flush()
|
|
request = CaptureCandidateRequest(agent_run_id=run_id, release_id=release.id, dashboard_id=42,
|
|
chart_id=128, dataset_id=256, result_key="sum__revenue", label="SUM(revenue)", normalized_filters=filters,
|
|
query_model_fingerprint=source["query_model_fingerprint"], comparison_policy=policy)
|
|
envelope = QueryExecutionEnvelope(NormalizedValue.model_validate(value), sha256(raw).hexdigest(), raw)
|
|
record = issue_result_authority(session, owner_user_id=run.user_id, request=request, envelope=envelope,
|
|
descriptor=descriptor, repository_key="my-repo", dashboard_key="FI-0080", expected_version=0,
|
|
expected_context_sha256=capture_context_sha256(run, run.user_id))
|
|
session.flush()
|
|
return record.capture_artifact_id, record.source_response_hash
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.CreateCaptureArtifact
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.MakeCandidatePayload [C:2] [TYPE Function] [SEMANTICS test,api,dashboard-testing,candidate]
|
|
# @BRIEF Build current literal authoring input for one explicit run and issued capture.
|
|
# @INVARIANT For kind=metric, caller MUST provide capture_artifact_ref to satisfy server-side validation.
|
|
# source_response_hash must match the capture artifact's sha256.
|
|
def make_dashboard_testing_candidate_payload(
|
|
agent_run_id: str,
|
|
capture_artifact_ref: str,
|
|
source_response_hash: str,
|
|
) -> dict:
|
|
from src.core.database import SessionLocal
|
|
from dashboard_candidate_fixture_requests import _request_payload
|
|
if capture_artifact_ref is None or source_response_hash is None:
|
|
raise ValueError("API_FIXTURE_EXPLICIT_CAPTURE_REQUIRED")
|
|
with SessionLocal() as session:
|
|
run = session.get(AgentRun, agent_run_id)
|
|
if run is None:
|
|
raise ValueError("API_FIXTURE_OWNED_RUN_REQUIRED")
|
|
payload = _request_payload(agent_run_id, capture_artifact_ref, environment_id=run.environment_id)
|
|
payload["source_response_hash"] = source_response_hash
|
|
return payload
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.MakeCandidatePayload
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.CreateAgentRun [C:1] [TYPE Function] [SEMANTICS test,api,dashboard-testing,agent-run]
|
|
# @POST The authored default environment identity is a UUID fitting DeploymentEnvironment.id VARCHAR(36) before capture issuance.
|
|
def create_dashboard_testing_agent_run(
|
|
session, user_id: str = "test-user-lifecycle", *, environment_id: str | None = None,
|
|
) -> AgentRun:
|
|
run = AgentRun(
|
|
user_id=user_id,
|
|
dashboard_id="42",
|
|
environment_id=environment_id if environment_id is not None else str(uuid4()),
|
|
intent="manual_reference_capture", trigger="manual",
|
|
context_snapshot={},
|
|
status="CREATED",
|
|
)
|
|
session.add(run)
|
|
session.flush()
|
|
return run
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.CreateAgentRun
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.VerificationRepository [C:2] [TYPE Function] [SEMANTICS test,api,dashboard-testing,verification,repository]
|
|
# @BRIEF Create a real minimal GitServerConfig/GitRepository pair in the API database.
|
|
@pytest.fixture
|
|
def dashboard_testing_verification_repository_id() -> str:
|
|
from src.core.database import SessionLocal
|
|
|
|
session = SessionLocal()
|
|
try:
|
|
server = GitServerConfig(
|
|
id=str(uuid4()),
|
|
name="verification-api-server",
|
|
provider="GITHUB",
|
|
url="https://git.example.test",
|
|
pat="verification-api-token",
|
|
)
|
|
session.add(server)
|
|
session.flush()
|
|
repository = GitRepository(
|
|
id=str(uuid4()),
|
|
dashboard_id=next(_VERIFICATION_REPOSITORY_DASHBOARD_IDS),
|
|
config_id=server.id,
|
|
remote_url="https://git.example.test/org/verification-api.git",
|
|
local_path="/tmp/verification-api-repository",
|
|
)
|
|
session.add(repository)
|
|
session.commit()
|
|
return repository.id
|
|
finally:
|
|
session.close()
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.VerificationRepository
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.MockUser [C:2] [TYPE Function] [SEMANTICS test,api,dashboard-testing,fixture]
|
|
# @BRIEF Provide an admin user whose permission check passes through the admin bypass.
|
|
@pytest.fixture
|
|
def dashboard_testing_mock_user() -> User:
|
|
return make_dashboard_testing_admin_user()
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.MockUser
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.Client [C:2] [TYPE Function] [SEMANTICS test,api,dashboard-testing,fixture]
|
|
# @BRIEF Provide a TestClient with only the current-user dependency overridden.
|
|
@pytest.fixture
|
|
def dashboard_testing_client(dashboard_testing_mock_user: User, dashboard_testing_native_storage):
|
|
# Import the full application only when the HTTP fixture is requested, not for pure DTO/component guards.
|
|
from src.app import app
|
|
app.dependency_overrides[get_current_user] = lambda: dashboard_testing_mock_user
|
|
try:
|
|
yield TestClient(app)
|
|
finally:
|
|
app.dependency_overrides.pop(get_current_user, None)
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.Client
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.NativeStorage [C:2] [TYPE Fixture]
|
|
# @PRE A fresh test root is explicitly activated; no global hold or server authority is fabricated.
|
|
@pytest.fixture
|
|
def dashboard_testing_native_storage(tmp_path, monkeypatch, dashboard_testing_api_database):
|
|
from src.services.agent_runs import artifacts
|
|
from src.services.storage_holds import initialize_native_holds
|
|
root = tmp_path / "native-api-storage"
|
|
root.mkdir()
|
|
initialize_native_holds(root)
|
|
storage = artifacts.DraftStorage(str(root))
|
|
monkeypatch.setattr(artifacts, "_draft_storage", storage)
|
|
return storage
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.NativeStorage
|
|
|
|
|
|
# #region Test.Api.DashboardTesting.Fixtures.Database [C:3] [TYPE Fixture]
|
|
# @PRE DATABASE_URL selects an already migrated PostgreSQL database with no repository for dashboard 42.
|
|
# @POST Fresh HTTP/MCP/verification Sessions retain service commits inside one owned transaction; teardown rolls it back.
|
|
# @RATIONALE Reconfigure the existing shared factory so imported aliases and real route dependencies use the same test transaction.
|
|
# @REJECTED Deleting append-only revisions, adopting a foreign repository, and SQLite cannot isolate this lifecycle contract.
|
|
@pytest.fixture
|
|
def dashboard_testing_api_database():
|
|
from sqlalchemy import select
|
|
from src.core.database import SessionLocal, engine
|
|
|
|
if engine.dialect.name != "postgresql":
|
|
raise RuntimeError("API_FIXTURE_POSTGRES_REQUIRED")
|
|
original_options = dict(SessionLocal.kw)
|
|
with engine.connect() as connection:
|
|
transaction = connection.begin()
|
|
try:
|
|
if connection.execute(select(GitRepository.id).where(GitRepository.dashboard_id == 42)).first() is not None:
|
|
raise RuntimeError("API_FIXTURE_DASHBOARD_SCOPE_NOT_EMPTY")
|
|
SessionLocal.configure(bind=connection, join_transaction_mode="create_savepoint")
|
|
yield connection
|
|
finally:
|
|
SessionLocal.kw.clear()
|
|
SessionLocal.kw.update(original_options)
|
|
transaction.rollback()
|
|
# #endregion Test.Api.DashboardTesting.Fixtures.Database
|
|
|
|
|
|
# #endregion Test.Api.DashboardTesting.Fixtures
|
|
|
|
|
|
# #region Test.Api.EncryptionHealth.Fixtures [C:2] [TYPE Module] [SEMANTICS test,api,security,encryption,health,fixtures]
|
|
# @BRIEF Shared builders and hardcoded fixtures for encryption-health helper and route tests.
|
|
# @RELATION BINDS_TO -> [Api.EncryptionHealth.EncryptionHealthRoutes]
|
|
# @TEST_FIXTURE: fernet_like_token -> 80-char urlsafe-base64 of 60 bytes, passes is_fernet_token()
|
|
# @TEST_FIXTURE: fingerprint_expected -> sha256[:8] of mocked key bytes b"some-bytes"
|
|
|
|
# 80-char urlsafe-base64 of 60 bytes — passes is_fernet_token() length and
|
|
# decode checks, so _try_decrypt reaches the (mocked) decrypt boundary.
|
|
FERNET_LIKE_TOKEN = "a2tr" * 20
|
|
# Expected sha256[:8] of the mocked encryption key bytes b"some-bytes".
|
|
ENCRYPTION_FINGERPRINT_EXPECTED = "sha256:5dd2a96e"
|
|
|
|
|
|
def make_encryption_provider(
|
|
pid="prov-1",
|
|
name="OpenAI",
|
|
api_key=None,
|
|
provider_type="openai",
|
|
base_url="https://api.openai.com",
|
|
default_model="gpt-4o-mini",
|
|
is_active=True,
|
|
is_multimodal=None,
|
|
):
|
|
"""Build a mock LLM provider record (external boundary: LLMProviderService)."""
|
|
p = MagicMock()
|
|
p.id = pid
|
|
p.name = name
|
|
p.api_key = api_key
|
|
p.provider_type = provider_type
|
|
p.base_url = base_url
|
|
p.default_model = default_model
|
|
p.is_active = is_active
|
|
p.is_multimodal = is_multimodal
|
|
p.max_images = None
|
|
p.context_window = None
|
|
p.max_output_tokens = None
|
|
return p
|
|
|
|
|
|
def make_encryption_connection(
|
|
conn_id="conn-1",
|
|
name="PG",
|
|
password=None,
|
|
host="localhost",
|
|
database="mydb",
|
|
username="admin",
|
|
):
|
|
"""Build a mock DatabaseConnection record (external boundary: ConfigManager)."""
|
|
c = MagicMock()
|
|
c.id = conn_id
|
|
c.name = name
|
|
c.password = password
|
|
c.host = host
|
|
c.database = database
|
|
c.username = username
|
|
return c
|
|
|
|
|
|
def make_encryption_config_manager(connections=None):
|
|
"""Build a mock ConfigManager exposing config.settings.connections."""
|
|
cm = MagicMock()
|
|
cm.config.settings.connections = connections or []
|
|
return cm
|
|
|
|
|
|
def make_encryption_pref(token=None):
|
|
"""Build a mock UserDashboardPreference with a git token attribute."""
|
|
pref = MagicMock()
|
|
pref.git_personal_access_token_encrypted = token
|
|
return pref
|
|
|
|
|
|
def mock_encryption_auth_session(prefs):
|
|
"""Build a mock AuthSessionLocal session whose query().filter().all() returns prefs."""
|
|
session = MagicMock()
|
|
session.query.return_value.filter.return_value.all.return_value = prefs
|
|
return session
|
|
# #endregion Test.Api.EncryptionHealth.Fixtures
|
|
|
|
|
|
# #region Test.Api.ScenarioRoutes.Helpers [C:2] [TYPE Module] [SEMANTICS testing,api,scenario,fixtures]
|
|
# @BRIEF Shared builders for Api.DashboardTesting.Scenario route tests: fresh app with the scenario
|
|
# router, stubbed DB/current-user dependencies, and deterministic user doubles.
|
|
# @RELATION BINDS_TO -> [Api.DashboardTesting.Scenario]
|
|
|
|
SCENARIO_ROUTES_HASH = "0" * 64
|
|
|
|
|
|
def scenario_routes_scenario_json() -> dict:
|
|
"""Hardcoded valid canonical graph fixture (tests/fixtures/dashboard_scenarios/scenario_valid.json)."""
|
|
import json
|
|
from pathlib import Path
|
|
|
|
fixtures = Path(__file__).resolve().parents[1] / "fixtures" / "dashboard_scenarios"
|
|
return json.loads((fixtures / "scenario_valid.json").read_text(encoding="utf-8"))
|
|
|
|
|
|
def scenario_routes_admin_user() -> SimpleNamespace:
|
|
"""Admin user — passes the has_permission admin bypass."""
|
|
return SimpleNamespace(
|
|
id="admin", username="admin",
|
|
roles=[SimpleNamespace(is_admin=True, permissions=[])],
|
|
)
|
|
|
|
|
|
def scenario_routes_svc_user() -> SimpleNamespace:
|
|
"""id-less user — exercises the getattr(id) or username fallback in draft-pack/capture."""
|
|
return SimpleNamespace(
|
|
id=None, username="svc-user",
|
|
roles=[SimpleNamespace(is_admin=True, permissions=[])],
|
|
)
|
|
|
|
|
|
def scenario_routes_no_perm_user() -> SimpleNamespace:
|
|
"""Authenticated user with no roles — any permission dependency yields 403."""
|
|
return SimpleNamespace(id="u1", username="u1", roles=[])
|
|
|
|
|
|
def scenario_routes_client(
|
|
*,
|
|
user: SimpleNamespace | None = None,
|
|
overrides: dict | None = None,
|
|
raise_server_exceptions: bool = True,
|
|
) -> tuple[TestClient, MagicMock]:
|
|
"""Fresh FastAPI app with the scenario router; get_db/get_current_user stubbed.
|
|
|
|
Returns (client, mock_db) — mock_db is the session handed to Depends(get_db).
|
|
"""
|
|
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 src.dependencies import get_current_user
|
|
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
mock_db = MagicMock()
|
|
app.dependency_overrides[get_db] = lambda: mock_db
|
|
app.dependency_overrides[get_current_user] = lambda: user if user is not None else scenario_routes_admin_user()
|
|
for dep, fn in (overrides or {}).items():
|
|
app.dependency_overrides[dep] = fn
|
|
return TestClient(app, raise_server_exceptions=raise_server_exceptions), mock_db
|
|
# #endregion Test.Api.ScenarioRoutes.Helpers
|
|
|
|
|
|
# #region Test.Maintenance.Routes.Fixtures [C:2] [TYPE Module] [SEMANTICS testing,api,maintenance,fixtures]
|
|
# @BRIEF Shared deterministic fixtures/builders for maintenance route tests
|
|
# (test_maintenance_routes_coverage.py). Standalone FastAPI app with only the
|
|
# maintenance router; auth closures extracted from the router and overridden.
|
|
# @RELATION BINDS_TO -> [Api.Routes.MaintenanceRoutesModule]
|
|
# @TEST_FIXTURE: seed_maintenance_event -> real MaintenanceEvent row (hardcoded fields)
|
|
# @TEST_FIXTURE: seed_maintenance_settings -> real MaintenanceSettings row (hardcoded fields)
|
|
from datetime import UTC, datetime
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.pool import StaticPool
|
|
|
|
from src.api.routes.maintenance._router import router as _maintenance_router
|
|
from src.core.database import get_db
|
|
from src.dependencies import get_config_manager, get_task_manager
|
|
from src.models.api_key import APIKey
|
|
from src.models.maintenance import (
|
|
DashboardScope,
|
|
MaintenanceDashboardStateStatus,
|
|
MaintenanceEvent,
|
|
MaintenanceEventStatus,
|
|
MaintenanceSettings,
|
|
)
|
|
|
|
# has_permission(...) / require_api_key_or_jwt(...) are factories; the routes bind the
|
|
# inner closures at import time. Pull them out of the router so a standalone app can
|
|
# override them by identity (test_migration.py pattern).
|
|
_MAINT_PERM_CLOSURES: dict[str, set] = {}
|
|
_MAINT_AUTH_CLOSURES: dict[str, object] = {}
|
|
for _route in _maintenance_router.routes:
|
|
_path = _route.path
|
|
_MAINT_PERM_CLOSURES.setdefault(_path, set())
|
|
|
|
def _collect(_d, _p=_path):
|
|
for _sub in getattr(_d, "dependencies", []) or []:
|
|
_name = getattr(_sub.call, "__name__", "")
|
|
if _name == "permission_checker":
|
|
_MAINT_PERM_CLOSURES[_p].add(_sub.call)
|
|
elif _name == "_auth_dependency":
|
|
_MAINT_AUTH_CLOSURES[_p] = _sub.call
|
|
_collect(_sub, _p)
|
|
|
|
_collect(_route.dependant)
|
|
|
|
|
|
# #region Test.Maintenance.Routes.MaintenanceRouteEnv [C:2] [TYPE Class]
|
|
# @BRIEF Isolated in-memory SQLite app for one maintenance test: seed session + TestClient factory.
|
|
class MaintenanceRouteEnv:
|
|
def __init__(self):
|
|
self.engine = create_engine(
|
|
"sqlite:///:memory:",
|
|
poolclass=StaticPool,
|
|
connect_args={"check_same_thread": False},
|
|
)
|
|
from src.models.mapping import Base
|
|
|
|
Base.metadata.create_all(self.engine)
|
|
self.session_factory = sessionmaker(bind=self.engine)
|
|
self.db = self.session_factory()
|
|
|
|
def client(self, *, task_manager=None, config_manager=None, auth=None):
|
|
app = FastAPI()
|
|
app.include_router(_maintenance_router)
|
|
|
|
def _override_db():
|
|
session = self.session_factory()
|
|
try:
|
|
yield session
|
|
finally:
|
|
session.close()
|
|
|
|
app.dependency_overrides[get_db] = _override_db
|
|
app.dependency_overrides[get_task_manager] = lambda: task_manager or MagicMock()
|
|
app.dependency_overrides[get_config_manager] = lambda: config_manager or MagicMock()
|
|
for _closures in _MAINT_PERM_CLOSURES.values():
|
|
for _c in _closures:
|
|
app.dependency_overrides[_c] = lambda: None
|
|
for _path, _closure in _MAINT_AUTH_CLOSURES.items():
|
|
_principal = (auth or {}).get(_path, "jwt:admin")
|
|
app.dependency_overrides[_closure] = lambda _p=_principal: _p
|
|
return TestClient(app)
|
|
|
|
def close(self):
|
|
self.db.close()
|
|
self.engine.dispose()
|
|
|
|
|
|
# #endregion Test.Maintenance.Routes.MaintenanceRouteEnv
|
|
|
|
|
|
@pytest.fixture
|
|
def maintenance_route_env():
|
|
env = MaintenanceRouteEnv()
|
|
yield env
|
|
env.close()
|
|
|
|
|
|
# #region Test.Maintenance.Routes.Fixtures.Builders [C:1] [TYPE Function]
|
|
def maintenance_env(env_id, *, is_production=False, stage="dev"):
|
|
e = MagicMock()
|
|
e.id = env_id
|
|
e.is_production = is_production
|
|
e.stage = stage
|
|
return e
|
|
|
|
|
|
def maintenance_config_manager(*envs):
|
|
cm = MagicMock()
|
|
cm.get_environments.return_value = list(envs)
|
|
return cm
|
|
|
|
|
|
def maintenance_task_manager(*task_ids):
|
|
tm = MagicMock()
|
|
tm.create_task = AsyncMock(side_effect=[MagicMock(id=tid) for tid in task_ids])
|
|
tm.broadcast_maintenance_event = AsyncMock()
|
|
return tm
|
|
|
|
|
|
def seed_maintenance_event(
|
|
db, *, status=MaintenanceEventStatus.ACTIVE, env_id="env-1",
|
|
tables=("raw.sales",), start_time=None, end_time=None,
|
|
message=None, task_id=None,
|
|
):
|
|
event = MaintenanceEvent(
|
|
tables=list(tables),
|
|
start_time=start_time if start_time is not None else datetime.now(UTC).replace(microsecond=0, tzinfo=None),
|
|
end_time=end_time,
|
|
message=message,
|
|
status=status,
|
|
environment_id=env_id,
|
|
task_id=task_id,
|
|
)
|
|
db.add(event)
|
|
db.flush()
|
|
return event
|
|
|
|
|
|
def seed_maintenance_settings(db, **overrides):
|
|
defaults = dict(
|
|
target_environment_id="env-1",
|
|
display_timezone="Europe/Moscow",
|
|
date_format="YYYY.MM.DD hh:mm:ss",
|
|
banner_template="Tpl {message}",
|
|
default_message="Default msg",
|
|
banner_height=None,
|
|
dashboard_scope=DashboardScope.PUBLISHED_ONLY,
|
|
excluded_dashboard_ids=[],
|
|
forced_dashboard_ids=[],
|
|
)
|
|
defaults.update(overrides)
|
|
settings = MaintenanceSettings(id="default", **defaults)
|
|
db.add(settings)
|
|
db.commit()
|
|
return settings
|
|
|
|
|
|
def seed_maintenance_state(db, event, *, dashboard_id=1, status=MaintenanceDashboardStateStatus.ACTIVE, banner_id=None):
|
|
from src.models.maintenance import MaintenanceDashboardState
|
|
|
|
state = MaintenanceDashboardState(
|
|
event_id=event.id,
|
|
dashboard_id=dashboard_id,
|
|
banner_id=banner_id,
|
|
status=status,
|
|
)
|
|
db.add(state)
|
|
db.flush()
|
|
return state
|
|
|
|
|
|
def seed_maintenance_api_key(db, key_hash, environment_id):
|
|
key = APIKey(
|
|
key_hash=key_hash, prefix="ssk_x1", name="k",
|
|
environment_id=environment_id,
|
|
permissions=["maintenance:end_all"], active=True,
|
|
)
|
|
db.add(key)
|
|
db.commit()
|
|
return key
|
|
|
|
|
|
# #endregion Test.Maintenance.Routes.Fixtures.Builders
|
|
# #endregion Test.Maintenance.Routes.Fixtures
|