Repair broken/unclosed semantic-protocol markup across the codebase: - INV_3 region pairing: restore 87 bare '# #endregion' (6 test_structure_* files) and 321 bare '// #endregion' (13 frontend test files) with their matching IDs; hand-fix 26 Python + 12 frontend + 2 E2E files with mismatched/missing/premature/duplicate closes; fully migrate test_orthogonal_fixes.py from single- to double-hash anchors. Workspace-wide stack-pair scan now passes 6569 code files with 0 problems. - Relations: normalize legacy predicates USES/CONTAINS/BELONGS_TO to canonical DEPENDS_ON/BINDS_TO (28 edits). - Metadata: normalize @LAYER and [TYPE] enum values to the canonical vocabulary (App->Application, lib->Infra, Service/Route/Checklist/ Declaration/Decorator/Functions -> Module/Function/Block, etc.). - Config: extend tags.LAYER.enum; fix tools.py prose '#region' phantom that broke anchor nesting. - Remove dead scratch scripts backend/_convert_defs.py, _batch_convert_defs.py. Index refresh: contract count 9576 -> 10821; schema_unclosed_anchor 1179 -> 729 (remaining 729 are markdown legacy [DEF:]/brace anchors, a separate migration phase).
450 lines
18 KiB
Python
450 lines
18 KiB
Python
# #region Test.Api.Datasets [C:3] [TYPE Module] [SEMANTICS test,datasets,routes,api]
|
|
# @BRIEF Route tests for Api.Datasets.DatasetsApi — ids listing, hub listing with stats/filters/search/pagination, map-columns, generate-docs, permissions.
|
|
# @RELATION BINDS_TO -> [Api.Datasets.DatasetsApi]
|
|
# @TEST_EDGE: missing_env -> {status: 404, detail: "Environment not found"}
|
|
# @TEST_EDGE: invalid_pagination -> {status: 400}
|
|
# @TEST_EDGE: empty_ids -> {status: 400}
|
|
# @TEST_EDGE: external_failure -> {status: 503}
|
|
# @TEST_EDGE: permission_denied -> {status: 403}
|
|
|
|
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")
|
|
os.environ.setdefault("TASKS_DATABASE_URL", "sqlite:///:memory:")
|
|
|
|
import sys
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
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)
|
|
|
|
|
|
def _make_env(env_id: str = "prod"):
|
|
env = MagicMock()
|
|
env.id = env_id
|
|
env.name = env_id
|
|
env.url = "https://superset.example.com"
|
|
return env
|
|
|
|
|
|
def _make_user(is_admin: bool = True):
|
|
from src.schemas.auth import RoleSchema, User
|
|
|
|
role = RoleSchema(
|
|
id="r-admin" if is_admin else "r-viewer",
|
|
name="Admin" if is_admin else "Viewer",
|
|
description="",
|
|
is_admin=is_admin,
|
|
permissions=[],
|
|
)
|
|
return User(
|
|
id="u-1",
|
|
username="tester",
|
|
email="tester@x.com",
|
|
auth_source="LOCAL",
|
|
created_at=datetime.now(),
|
|
roles=[role],
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def api():
|
|
"""Isolated FastAPI app with the datasets router and mocked service deps.
|
|
|
|
Real has_permission runs against an Admin user, so authorization itself
|
|
is exercised (not short-circuited) on every request.
|
|
"""
|
|
from src.api.routes.datasets import router
|
|
from src.dependencies import (
|
|
get_config_manager,
|
|
get_current_user,
|
|
get_resource_service,
|
|
get_task_manager,
|
|
)
|
|
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
|
|
config_manager = MagicMock()
|
|
task_manager = MagicMock()
|
|
resource_service = MagicMock()
|
|
|
|
app.dependency_overrides[get_current_user] = lambda: _make_user(is_admin=True)
|
|
app.dependency_overrides[get_config_manager] = lambda: config_manager
|
|
app.dependency_overrides[get_task_manager] = lambda: task_manager
|
|
app.dependency_overrides[get_resource_service] = lambda: resource_service
|
|
|
|
deps = {
|
|
"config": config_manager,
|
|
"task": task_manager,
|
|
"resource": resource_service,
|
|
"app": app,
|
|
}
|
|
return deps
|
|
|
|
|
|
@pytest.fixture
|
|
def api_denied():
|
|
"""Same isolated app but with a non-admin user → real has_permission raises 403."""
|
|
from src.api.routes.datasets import router
|
|
from src.dependencies import (
|
|
get_config_manager,
|
|
get_current_user,
|
|
get_resource_service,
|
|
get_task_manager,
|
|
)
|
|
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
|
|
app.dependency_overrides[get_current_user] = lambda: _make_user(is_admin=False)
|
|
app.dependency_overrides[get_config_manager] = lambda: MagicMock()
|
|
app.dependency_overrides[get_task_manager] = lambda: MagicMock()
|
|
app.dependency_overrides[get_resource_service] = lambda: MagicMock()
|
|
return {"app": app}
|
|
|
|
|
|
# ── GET /api/datasets/ids ──
|
|
|
|
class TestGetDatasetIds:
|
|
"""GET /api/datasets/ids — all dataset ids, optional search filter."""
|
|
|
|
def test_success_no_search(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].get_all_tasks.return_value = []
|
|
api["resource"].get_datasets_with_status = AsyncMock(
|
|
return_value=[{"id": 1}, {"id": 2, "table_name": "sales"}]
|
|
)
|
|
resp = TestClient(api["app"]).get("/api/datasets/ids?env_id=prod")
|
|
assert resp.status_code == 200
|
|
assert resp.json() == {"dataset_ids": [1, 2]}
|
|
|
|
def test_success_with_search(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].get_all_tasks.return_value = []
|
|
api["resource"].get_datasets_with_status = AsyncMock(
|
|
return_value=[
|
|
{"id": 1, "table_name": "Sales Data"},
|
|
{"id": 2, "table_name": "Users"},
|
|
{"id": 3}, # no table_name -> treated as ""
|
|
]
|
|
)
|
|
resp = TestClient(api["app"]).get("/api/datasets/ids?env_id=prod&search=sales")
|
|
assert resp.status_code == 200
|
|
assert resp.json() == {"dataset_ids": [1]}
|
|
|
|
def test_env_not_found(self, api):
|
|
api["config"].get_environments.return_value = []
|
|
resp = TestClient(api["app"]).get("/api/datasets/ids?env_id=ghost")
|
|
assert resp.status_code == 404
|
|
assert resp.json()["detail"] == "Environment not found"
|
|
|
|
def test_external_failure_503(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].get_all_tasks.return_value = []
|
|
api["resource"].get_datasets_with_status = AsyncMock(
|
|
side_effect=Exception("connection reset")
|
|
)
|
|
resp = TestClient(api["app"]).get("/api/datasets/ids?env_id=prod")
|
|
assert resp.status_code == 503
|
|
assert "Failed to fetch dataset IDs" in resp.json()["detail"]
|
|
|
|
def test_permission_denied(self, api_denied):
|
|
resp = TestClient(api_denied["app"]).get("/api/datasets/ids?env_id=prod")
|
|
assert resp.status_code == 403
|
|
|
|
|
|
# ── GET /api/datasets ──
|
|
|
|
class TestGetDatasets:
|
|
"""GET /api/datasets — hub listing with stats, filters, search, pagination."""
|
|
|
|
_ROWS = [
|
|
# unmapped, not linked
|
|
{"id": 1, "table_name": "Sales Data", "schema": "public", "database": "d",
|
|
"mapped_fields": {"total": 5, "mapped": 0}},
|
|
# mapped + linked
|
|
{"id": 2, "table_name": "Users", "schema": "public", "database": "d",
|
|
"mapped_fields": {"total": 5, "mapped": 3}, "linked_dashboard_count": 2},
|
|
# no mapped_fields at all
|
|
{"id": 3, "table_name": "Orders", "schema": "public", "database": "d"},
|
|
]
|
|
|
|
def _setup(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].get_all_tasks.return_value = []
|
|
api["resource"].get_datasets_with_status = AsyncMock(return_value=list(self._ROWS))
|
|
|
|
def test_success_with_stats(self, api):
|
|
self._setup(api)
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod")
|
|
assert resp.status_code == 200
|
|
body = resp.json()
|
|
assert body["total"] == 3
|
|
assert body["page"] == 1
|
|
assert body["page_size"] == 10
|
|
assert body["total_pages"] == 1
|
|
assert body["stats"] == {"total": 3, "unmapped_count": 1, "mapped_count": 1, "linked_count": 1}
|
|
assert len(body["datasets"]) == 3
|
|
|
|
def test_filter_unmapped(self, api):
|
|
self._setup(api)
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod&filter=unmapped")
|
|
assert resp.status_code == 200
|
|
assert [d["id"] for d in resp.json()["datasets"]] == [1]
|
|
|
|
def test_filter_mapped(self, api):
|
|
self._setup(api)
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod&filter=mapped")
|
|
assert resp.status_code == 200
|
|
assert [d["id"] for d in resp.json()["datasets"]] == [2]
|
|
|
|
def test_filter_linked(self, api):
|
|
self._setup(api)
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod&filter=linked")
|
|
assert resp.status_code == 200
|
|
assert [d["id"] for d in resp.json()["datasets"]] == [2]
|
|
|
|
def test_filter_unknown_is_noop(self, api):
|
|
self._setup(api)
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod&filter=bogus")
|
|
assert resp.status_code == 200
|
|
assert len(resp.json()["datasets"]) == 3
|
|
|
|
def test_search_filters_by_table_name(self, api):
|
|
self._setup(api)
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod&search=users")
|
|
assert resp.status_code == 200
|
|
assert [d["id"] for d in resp.json()["datasets"]] == [2]
|
|
|
|
def test_empty_result_pagination(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].get_all_tasks.return_value = []
|
|
api["resource"].get_datasets_with_status = AsyncMock(return_value=[])
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod")
|
|
assert resp.status_code == 200
|
|
body = resp.json()
|
|
assert body["datasets"] == []
|
|
assert body["total"] == 0
|
|
assert body["total_pages"] == 1
|
|
|
|
def test_page_slice(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].get_all_tasks.return_value = []
|
|
api["resource"].get_datasets_with_status = AsyncMock(
|
|
return_value=[{"id": i, "table_name": f"t{i}", "schema": "s", "database": "d"} for i in range(1, 6)]
|
|
)
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod&page=2&page_size=2")
|
|
assert resp.status_code == 200
|
|
body = resp.json()
|
|
assert [d["id"] for d in body["datasets"]] == [3, 4]
|
|
assert body["total_pages"] == 3
|
|
|
|
def test_env_not_found(self, api):
|
|
api["config"].get_environments.return_value = []
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=ghost")
|
|
assert resp.status_code == 404
|
|
assert resp.json()["detail"] == "Environment not found"
|
|
|
|
def test_page_lt_one_rejected(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod&page=0")
|
|
assert resp.status_code == 400
|
|
assert resp.json()["detail"] == "Page must be >= 1"
|
|
|
|
def test_page_size_out_of_range_rejected(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod&page_size=101")
|
|
assert resp.status_code == 400
|
|
assert resp.json()["detail"] == "Page size must be between 1 and 100"
|
|
|
|
def test_external_failure_503(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].get_all_tasks.return_value = []
|
|
api["resource"].get_datasets_with_status = AsyncMock(
|
|
side_effect=Exception("refused")
|
|
)
|
|
resp = TestClient(api["app"]).get("/api/datasets?env_id=prod")
|
|
assert resp.status_code == 503
|
|
assert "Failed to fetch datasets" in resp.json()["detail"]
|
|
|
|
def test_permission_denied(self, api_denied):
|
|
resp = TestClient(api_denied["app"]).get("/api/datasets?env_id=prod")
|
|
assert resp.status_code == 403
|
|
|
|
|
|
# ── POST /api/datasets/map-columns ──
|
|
|
|
class TestMapColumns:
|
|
"""POST /api/datasets/map-columns — bulk column-mapping task creation."""
|
|
|
|
def _success_setup(self, api, task_id="task-map-1"):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
task_obj = MagicMock()
|
|
task_obj.id = task_id
|
|
api["task"].create_task = AsyncMock(return_value=task_obj)
|
|
return task_obj
|
|
|
|
def test_sqllab_success(self, api):
|
|
self._success_setup(api)
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/map-columns",
|
|
json={"env_id": "prod", "dataset_ids": [1, 2], "source_type": "sqllab",
|
|
"database_id": 4, "sql_query": "SELECT 1", "file_data": None},
|
|
)
|
|
assert resp.status_code == 200
|
|
assert resp.json() == {"task_id": "task-map-1"}
|
|
_, kwargs = api["task"].create_task.call_args
|
|
assert kwargs["plugin_id"] == "dataset-mapper"
|
|
assert kwargs["params"]["source"] == "sqllab"
|
|
assert kwargs["params"]["dataset_id"] == 1
|
|
assert kwargs["params"]["database_id"] == 4
|
|
assert kwargs["params"]["sql_query"] == "SELECT 1"
|
|
|
|
def test_xlsx_success(self, api):
|
|
self._success_setup(api)
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/map-columns",
|
|
json={"env_id": "prod", "dataset_ids": [9], "source_type": "xlsx",
|
|
"file_data": "/tmp/book.xlsx"},
|
|
)
|
|
assert resp.status_code == 200
|
|
_, kwargs = api["task"].create_task.call_args
|
|
assert kwargs["params"]["source"] == "excel"
|
|
assert kwargs["params"]["database_id"] is None
|
|
assert kwargs["params"]["file_data"] == "/tmp/book.xlsx"
|
|
|
|
def test_empty_ids_rejected(self, api):
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/map-columns",
|
|
json={"env_id": "prod", "dataset_ids": [], "source_type": "sqllab", "database_id": 1},
|
|
)
|
|
assert resp.status_code == 400
|
|
assert "At least one dataset ID" in resp.json()["detail"]
|
|
|
|
def test_invalid_source_rejected(self, api):
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/map-columns",
|
|
json={"env_id": "prod", "dataset_ids": [1], "source_type": "csv"},
|
|
)
|
|
assert resp.status_code == 400
|
|
assert "Source type must be 'sqllab' or 'xlsx'" in resp.json()["detail"]
|
|
|
|
def test_sqllab_without_database_id_rejected(self, api):
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/map-columns",
|
|
json={"env_id": "prod", "dataset_ids": [1], "source_type": "sqllab"},
|
|
)
|
|
assert resp.status_code == 400
|
|
assert "database_id is required" in resp.json()["detail"]
|
|
|
|
def test_env_not_found(self, api):
|
|
api["config"].get_environments.return_value = []
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/map-columns",
|
|
json={"env_id": "ghost", "dataset_ids": [1], "source_type": "xlsx"},
|
|
)
|
|
assert resp.status_code == 404
|
|
assert resp.json()["detail"] == "Environment not found"
|
|
|
|
def test_task_creation_failure_503(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].create_task = AsyncMock(side_effect=Exception("queue down"))
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/map-columns",
|
|
json={"env_id": "prod", "dataset_ids": [1], "source_type": "xlsx"},
|
|
)
|
|
assert resp.status_code == 503
|
|
assert "Failed to create mapping task" in resp.json()["detail"]
|
|
|
|
def test_permission_denied(self, api_denied):
|
|
resp = TestClient(api_denied["app"]).post(
|
|
"/api/datasets/map-columns",
|
|
json={"env_id": "prod", "dataset_ids": [1], "source_type": "xlsx"},
|
|
)
|
|
assert resp.status_code == 403
|
|
|
|
|
|
# ── POST /api/datasets/generate-docs ──
|
|
|
|
class TestGenerateDocs:
|
|
"""POST /api/datasets/generate-docs — bulk documentation task creation."""
|
|
|
|
def _success_setup(self, api, task_id="task-docs-1"):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
task_obj = MagicMock()
|
|
task_obj.id = task_id
|
|
api["task"].create_task = AsyncMock(return_value=task_obj)
|
|
return task_obj
|
|
|
|
def test_success_with_options(self, api):
|
|
self._success_setup(api)
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/generate-docs",
|
|
json={"env_id": "prod", "dataset_ids": [1], "llm_provider": "openai",
|
|
"options": {"language": "ru"}},
|
|
)
|
|
assert resp.status_code == 200
|
|
assert resp.json() == {"task_id": "task-docs-1"}
|
|
_, kwargs = api["task"].create_task.call_args
|
|
assert kwargs["plugin_id"] == "llm_documentation"
|
|
assert kwargs["params"]["provider_id"] == "openai"
|
|
assert kwargs["params"]["dataset_id"] == "1"
|
|
assert kwargs["params"]["options"] == {"language": "ru"}
|
|
|
|
def test_success_without_options(self, api):
|
|
self._success_setup(api)
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/generate-docs",
|
|
json={"env_id": "prod", "dataset_ids": [2], "llm_provider": "anthropic"},
|
|
)
|
|
assert resp.status_code == 200
|
|
_, kwargs = api["task"].create_task.call_args
|
|
assert kwargs["params"]["options"] == {}
|
|
|
|
def test_empty_ids_rejected(self, api):
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/generate-docs",
|
|
json={"env_id": "prod", "dataset_ids": [], "llm_provider": "openai"},
|
|
)
|
|
assert resp.status_code == 400
|
|
assert "At least one dataset ID" in resp.json()["detail"]
|
|
|
|
def test_env_not_found(self, api):
|
|
api["config"].get_environments.return_value = []
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/generate-docs",
|
|
json={"env_id": "ghost", "dataset_ids": [1], "llm_provider": "openai"},
|
|
)
|
|
assert resp.status_code == 404
|
|
assert resp.json()["detail"] == "Environment not found"
|
|
|
|
def test_task_creation_failure_503(self, api):
|
|
api["config"].get_environments.return_value = [_make_env()]
|
|
api["task"].create_task = AsyncMock(side_effect=Exception("llm backend down"))
|
|
resp = TestClient(api["app"]).post(
|
|
"/api/datasets/generate-docs",
|
|
json={"env_id": "prod", "dataset_ids": [1], "llm_provider": "openai"},
|
|
)
|
|
assert resp.status_code == 503
|
|
assert "Failed to create documentation generation task" in resp.json()["detail"]
|
|
|
|
def test_permission_denied(self, api_denied):
|
|
resp = TestClient(api_denied["app"]).post(
|
|
"/api/datasets/generate-docs",
|
|
json={"env_id": "prod", "dataset_ids": [1], "llm_provider": "openai"},
|
|
)
|
|
assert resp.status_code == 403
|
|
|
|
# #endregion Test.Api.Datasets
|