- ~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
326 lines
13 KiB
Python
326 lines
13 KiB
Python
# #region Test.Settings.EdgePaths [C:3] [TYPE Module] [SEMANTICS test,settings,routes,edge]
|
|
# @BRIEF Edge-path tests for settings routes — password masking, masked-env updates,
|
|
# logging merge, consolidated notifications and scalar patch branches.
|
|
# @RELATION BINDS_TO -> [Api.Settings.SettingsRouter]
|
|
# @TEST_EDGE: empty_password_env -> GET /settings leaves empty passwords empty (no masking)
|
|
# @TEST_EDGE: masked_password_no_old_env -> PUT /environments masked password without existing env validates then updates
|
|
# @TEST_EDGE: logging_blank_file_path -> PATCH /logging blank file_path pops the field and keeps existing
|
|
# @TEST_EDGE: consolidated_notifications_record -> GET /consolidated surfaces AppConfigRecord notifications
|
|
# @TEST_EDGE: consolidated_record_no_notifications -> GET /consolidated falls back to {} when key missing
|
|
# @TEST_EDGE: consolidated_connection_no_password -> PATCH connections with blank password skips encryption
|
|
# @TEST_EDGE: consolidated_logging_non_object -> PATCH logging as non-object returns 422
|
|
# @TEST_EDGE: consolidated_scalar_branches -> PATCH retention/auth/assistant/translate scalars persist
|
|
|
|
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("DEV_MODE", "true")
|
|
|
|
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)
|
|
|
|
|
|
# ── Part A: standalone router app (mirrors test_settings.py) ──────────────
|
|
|
|
|
|
def _make_real_config(environments=None):
|
|
"""Build a real AppConfig with default settings for mock testing."""
|
|
from src.core.config_models import AppConfig, GlobalSettings
|
|
return AppConfig(settings=GlobalSettings(), environments=environments or [])
|
|
|
|
|
|
def _make_client(overrides: dict | None = None) -> TestClient:
|
|
from src.api.routes.settings import router
|
|
from src.core.database import get_db
|
|
from src.dependencies import get_config_manager, get_current_user
|
|
from src.schemas.auth import RoleSchema, User
|
|
|
|
app = FastAPI()
|
|
app.include_router(router, prefix="/api/settings")
|
|
|
|
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", description="", is_admin=True, permissions=[])],
|
|
)
|
|
|
|
app.dependency_overrides[get_db] = lambda: MagicMock()
|
|
app.dependency_overrides[get_current_user] = lambda: mock_user
|
|
app.dependency_overrides[get_config_manager] = lambda: MagicMock()
|
|
if overrides:
|
|
for dep, fn in overrides.items():
|
|
app.dependency_overrides[dep] = fn
|
|
return TestClient(app)
|
|
|
|
|
|
class TestGetSettingsEmptyPassword:
|
|
"""GET /api/settings — environment with empty password must not be masked."""
|
|
|
|
def test_empty_password_left_alone(self):
|
|
from src.core.config_models import Environment
|
|
env = Environment(
|
|
id="env-1", name="No Secret", url="https://example.com",
|
|
username="admin", password="", stage="DEV",
|
|
)
|
|
mock_config = MagicMock()
|
|
mock_config.get_config.return_value = _make_real_config(environments=[env])
|
|
|
|
from src.dependencies import get_config_manager
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.get("/api/settings")
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["environments"][0]["password"] == ""
|
|
|
|
|
|
class TestUpdateEnvironmentMaskedNoOldEnv:
|
|
"""PUT /api/settings/environments/{id} — masked password with no existing env
|
|
still validates the (masked) connection and updates."""
|
|
|
|
PAYLOAD = {
|
|
"id": "env-new",
|
|
"name": "New Env",
|
|
"url": "https://superset.example.com",
|
|
"username": "admin",
|
|
"password": "********",
|
|
"stage": "DEV",
|
|
}
|
|
|
|
def test_masked_password_without_old_env(self):
|
|
mock_config = MagicMock()
|
|
# old_env lookup finds nothing → env_to_validate keeps the masked password
|
|
mock_config.get_environments.return_value = []
|
|
mock_config.update_environment.return_value = True
|
|
|
|
with patch("src.api.routes.settings.AsyncSupersetClient") as mock_client_cls:
|
|
mock_client = MagicMock()
|
|
mock_client.authenticate = AsyncMock()
|
|
mock_client.get_dashboards_page = AsyncMock(return_value=(0, []))
|
|
mock_client_cls.return_value = mock_client
|
|
|
|
from src.dependencies import get_config_manager
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.put("/api/settings/environments/env-new", json=self.PAYLOAD)
|
|
assert resp.status_code == 200
|
|
mock_config.update_environment.assert_called_once()
|
|
assert mock_config.update_environment.call_args[0][0] == "env-new"
|
|
# Validation ran even though the password was masked and no old env existed
|
|
mock_client.authenticate.assert_awaited_once()
|
|
|
|
|
|
class TestUpdateLoggingConfigBlankFilePath:
|
|
"""PATCH /api/settings/logging — explicit blank file_path is dropped so the
|
|
existing file logging is preserved (exclude_unset merge)."""
|
|
|
|
def test_blank_file_path_keeps_existing(self):
|
|
from src.core.config_models import GlobalSettings, LoggingConfig
|
|
|
|
real_settings = GlobalSettings(
|
|
logging=LoggingConfig(level="INFO", file_path="logs/app.log")
|
|
)
|
|
mock_cfg = MagicMock()
|
|
mock_cfg.settings = real_settings
|
|
mock_config = MagicMock()
|
|
mock_config.get_config.return_value = mock_cfg
|
|
mock_config.update_global_settings.side_effect = lambda s: MagicMock(settings=s)
|
|
|
|
from src.dependencies import get_config_manager
|
|
client = _make_client({get_config_manager: lambda: mock_config})
|
|
resp = client.patch("/api/settings/logging", json={
|
|
"level": "WARNING", "file_path": "",
|
|
})
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["level"] == "WARNING"
|
|
assert real_settings.logging.file_path == "logs/app.log"
|
|
|
|
|
|
# ── Part B: real app + dependency overrides (mirrors test_settings_consolidated.py) ──
|
|
|
|
mock_user = MagicMock()
|
|
mock_user.username = "testuser"
|
|
mock_user.roles = []
|
|
admin_role = MagicMock()
|
|
admin_role.name = "Admin"
|
|
admin_role.permissions = []
|
|
mock_user.roles.append(admin_role)
|
|
|
|
|
|
def _make_conn_dict(**overrides) -> dict:
|
|
"""Build a raw connection dict as the frontend would send it."""
|
|
return {
|
|
"id": overrides.get("id", "conn-1"),
|
|
"name": overrides.get("name", "Test DB"),
|
|
"host": overrides.get("host", "localhost"),
|
|
"port": overrides.get("port", 5432),
|
|
"database": overrides.get("database", "testdb"),
|
|
"username": overrides.get("username", "admin"),
|
|
"password": overrides.get("password", "secret"),
|
|
"dialect": overrides.get("dialect", "postgresql"),
|
|
"extra_params": overrides.get("extra_params", {}),
|
|
"pool_size": overrides.get("pool_size", 5),
|
|
}
|
|
|
|
|
|
def _make_conn_model(**overrides):
|
|
from src.core.config_models import DatabaseConnection
|
|
return DatabaseConnection(**_make_conn_dict(**overrides))
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def mock_deps():
|
|
"""Override FastAPI dependencies for consolidated-settings routes with a real
|
|
GlobalSettings so typed-field assignment is testable."""
|
|
from src.app import app
|
|
from src.core.config_models import GlobalSettings
|
|
from src.dependencies import get_config_manager, get_current_user
|
|
|
|
mock_user.roles = [admin_role]
|
|
real_settings = GlobalSettings()
|
|
app_config = MagicMock()
|
|
app_config.settings = real_settings
|
|
app_config.environments = []
|
|
mock_config_manager = MagicMock()
|
|
mock_config_manager.get_config.return_value = app_config
|
|
|
|
app.dependency_overrides[get_config_manager] = lambda: mock_config_manager
|
|
app.dependency_overrides[get_current_user] = lambda: mock_user
|
|
yield {"config": mock_config_manager, "settings": real_settings}
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
from src.app import app
|
|
|
|
client = TestClient(app)
|
|
|
|
|
|
class TestConsolidatedGetNotifications:
|
|
"""GET /api/settings/consolidated — AppConfigRecord notifications payload."""
|
|
|
|
def test_reads_notifications_from_record(self, mock_deps):
|
|
mock_db = MagicMock()
|
|
record = MagicMock()
|
|
record.payload = {"notifications": {"email": {"enabled": True}}}
|
|
mock_db.query.return_value.filter.return_value.first.return_value = record
|
|
|
|
with patch("src.core.database.SessionLocal", return_value=mock_db):
|
|
resp = client.get("/api/settings/consolidated")
|
|
assert resp.status_code == 200
|
|
assert resp.json()["notifications"] == {"email": {"enabled": True}}
|
|
|
|
def test_record_without_notifications_key(self, mock_deps):
|
|
mock_db = MagicMock()
|
|
record = MagicMock()
|
|
record.payload = {"other": 1}
|
|
mock_db.query.return_value.filter.return_value.first.return_value = record
|
|
|
|
with patch("src.core.database.SessionLocal", return_value=mock_db):
|
|
resp = client.get("/api/settings/consolidated")
|
|
assert resp.status_code == 200
|
|
assert resp.json()["notifications"] == {}
|
|
|
|
def test_record_non_dict_payload(self, mock_deps):
|
|
mock_db = MagicMock()
|
|
record = MagicMock()
|
|
record.payload = "corrupted"
|
|
mock_db.query.return_value.filter.return_value.first.return_value = record
|
|
|
|
with patch("src.core.database.SessionLocal", return_value=mock_db):
|
|
resp = client.get("/api/settings/consolidated")
|
|
assert resp.status_code == 200
|
|
assert resp.json()["notifications"] == {}
|
|
|
|
def test_no_record(self, mock_deps):
|
|
mock_db = MagicMock()
|
|
mock_db.query.return_value.filter.return_value.first.return_value = None
|
|
|
|
with patch("src.core.database.SessionLocal", return_value=mock_db):
|
|
resp = client.get("/api/settings/consolidated")
|
|
assert resp.status_code == 200
|
|
assert resp.json()["notifications"] == {}
|
|
|
|
|
|
class TestConsolidatedPatchEdges:
|
|
"""PATCH /api/settings/consolidated — connection, logging and scalar branches."""
|
|
|
|
def test_connections_blank_password_skips_encryption(self, mock_deps):
|
|
settings = mock_deps["settings"]
|
|
settings.connections = [
|
|
_make_conn_model(id="c-exist", name="Existing", password="encrypted-vault"),
|
|
]
|
|
mock_config = mock_deps["config"]
|
|
|
|
payload = {"connections": [_make_conn_dict(id="c-exist", name="Existing", password="")]}
|
|
resp = client.patch("/api/settings/consolidated", json=payload)
|
|
assert resp.status_code == 200
|
|
|
|
args, _ = mock_config.update_global_settings.call_args
|
|
conn = args[0].connections[0]
|
|
assert conn.password == "", "blank password must not be masked or encrypted"
|
|
|
|
def test_logging_non_object_returns_422(self, mock_deps):
|
|
resp = client.patch("/api/settings/consolidated", json={"logging": "oops"})
|
|
assert resp.status_code == 422
|
|
assert mock_deps["config"].update_global_settings.call_count == 0
|
|
|
|
def test_logging_blank_file_path_keeps_existing(self, mock_deps):
|
|
from src.core.config_models import LoggingConfig
|
|
settings = mock_deps["settings"]
|
|
settings.logging = LoggingConfig(level="INFO", file_path="/var/log/app.log")
|
|
mock_config = mock_deps["config"]
|
|
|
|
resp = client.patch("/api/settings/consolidated", json={
|
|
"logging": {"level": "DEBUG", "file_path": ""},
|
|
})
|
|
assert resp.status_code == 200
|
|
|
|
args, _ = mock_config.update_global_settings.call_args
|
|
updated_logging = args[0].logging
|
|
assert updated_logging.file_path == "/var/log/app.log"
|
|
assert updated_logging.level == "DEBUG"
|
|
|
|
def test_scalar_branches_persisted(self, mock_deps):
|
|
mock_config = mock_deps["config"]
|
|
payload = {
|
|
"task_retention_limit": 50,
|
|
"default_environment_id": "env-prod",
|
|
"auth_attempt_window": 600,
|
|
"auth_ban_duration": 1800,
|
|
"assistant_archive_after_days": 7,
|
|
"assistant_message_ttl_days": 30,
|
|
"translate_baseline_expiry_days": 60,
|
|
}
|
|
resp = client.patch("/api/settings/consolidated", json=payload)
|
|
assert resp.status_code == 200
|
|
|
|
args, _ = mock_config.update_global_settings.call_args
|
|
updated = args[0]
|
|
assert updated.task_retention_limit == 50
|
|
assert updated.default_environment_id == "env-prod"
|
|
assert updated.auth_attempt_window == 600
|
|
assert updated.auth_ban_duration == 1800
|
|
assert updated.assistant_archive_after_days == 7
|
|
assert updated.assistant_message_ttl_days == 30
|
|
assert updated.translate_baseline_expiry_days == 60
|
|
|
|
def test_blank_default_environment_clears(self, mock_deps):
|
|
mock_config = mock_deps["config"]
|
|
resp = client.patch("/api/settings/consolidated", json={"default_environment_id": ""})
|
|
assert resp.status_code == 200
|
|
|
|
args, _ = mock_config.update_global_settings.call_args
|
|
assert args[0].default_environment_id is None
|
|
# #endregion Test.Settings.EdgePaths
|