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).
363 lines
16 KiB
Python
363 lines
16 KiB
Python
# #region Test.Lineage.Api [C:3] [TYPE Module] [SEMANTICS test,lineage,api,rbac]
|
|
# @BRIEF 041 API contract + RBAC tests (T037): dependents read-model with fingerprint pinning (R6),
|
|
# default-deny mutations, typed errors.
|
|
# @RELATION BINDS_TO -> [Api.Lineage.Routes]
|
|
from datetime import UTC, datetime
|
|
from types import SimpleNamespace
|
|
import pytest
|
|
|
|
from fastapi import HTTPException
|
|
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.orm import Session
|
|
|
|
from src.api.routes.lineage import (
|
|
get_dependents,
|
|
mark_dataset_deprecated,
|
|
migrate_dependent,
|
|
trigger_fanout,
|
|
)
|
|
from src.models.lineage import (
|
|
DatasetImpactRecord,
|
|
DatasetUsageEdge,
|
|
FanoutPlan,
|
|
LineageIndexSnapshot,
|
|
ProjectionConfidence,
|
|
)
|
|
from src.models.mapping import Base, Environment, ResourceMapping, ResourceType
|
|
|
|
_ENV = "env-api"
|
|
_D1 = "d77a1234-0000-4000-8000-000000000077"
|
|
_D1_ID = 77
|
|
|
|
|
|
@pytest.fixture()
|
|
def db():
|
|
engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False})
|
|
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, name="api", url="https://s.example.com", credentials_id="c1"))
|
|
session.add(
|
|
ResourceMapping(environment_id=_ENV, resource_type=ResourceType.DATASET, uuid=_D1, remote_integer_id=str(_D1_ID), resource_name="D1", last_synced_at=datetime.now(UTC))
|
|
)
|
|
session.add(LineageIndexSnapshot(environment_id=_ENV, index_fingerprint="fp-current", stale_index=False))
|
|
session.flush()
|
|
session.add(
|
|
DatasetUsageEdge(
|
|
environment_id=_ENV, dataset_uuid=_D1, chart_uuid="c1", dashboard_uuid="dash-a",
|
|
dashboard_title="Dash A", consumed_columns=["amount"], consumed_metrics=["sum__amount"],
|
|
projection_confidence=ProjectionConfidence.EXACT.value, unresolved_refs=[], edge_fingerprint="e" * 64,
|
|
)
|
|
)
|
|
session.commit()
|
|
yield session
|
|
session.close()
|
|
engine.dispose()
|
|
|
|
|
|
# #region Test.Lineage.Api.Dependents [C:2] [TYPE Class] [SEMANTICS test,lineage,dependents]
|
|
# @ingroup Test
|
|
class TestDependents:
|
|
def test_returns_pinned_snapshot(self, db: Session) -> None:
|
|
resp = get_dependents(_D1_ID, env_id=_ENV, fingerprint="fp-current", db=db, _=None)
|
|
assert resp.fingerprint == "fp-current"
|
|
assert resp.stale_index is False
|
|
assert resp.stale_notice is False
|
|
assert len(resp.dependents) == 1
|
|
assert resp.dependents[0].dashboard_id == "dash-a"
|
|
assert resp.dependents[0].chart_count == 1
|
|
|
|
def test_fingerprint_mismatch_surfaces_stale_notice(self, db: Session) -> None:
|
|
# R6: mismatch -> stale_notice, never silent drift.
|
|
resp = get_dependents(_D1_ID, env_id=_ENV, fingerprint="fp-stale", db=db, _=None)
|
|
assert resp.stale_notice is True
|
|
assert resp.fingerprint == "fp-current"
|
|
|
|
def test_unknown_dataset_returns_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
get_dependents(999999, env_id=_ENV, db=db, _=None)
|
|
assert exc_info.value.status_code == 404
|
|
# #endregion Test.Lineage.Api.Dependents
|
|
|
|
|
|
# #region Test.Lineage.Api.Deprecation [C:2] [TYPE Class] [SEMANTICS test,lineage,api,deprecation]
|
|
# @ingroup Test
|
|
class TestDeprecation:
|
|
def test_mark_and_migrate(self, db: Session) -> None:
|
|
dto = mark_dataset_deprecated(_D1_ID, env_id=_ENV, successor_dataset_id=None, grace_window_days=30, db=db, _=None)
|
|
assert dto.dataset == _D1
|
|
assert dto.grace_window_days == 30
|
|
migrated = migrate_dependent(_D1_ID, env_id=_ENV, dashboard_uuid="dash-a", db=db, _=None)
|
|
assert migrated.dependent_status == {"dash-a": "migrated"}
|
|
# #endregion Test.Lineage.Api.Deprecation
|
|
|
|
|
|
# #region Test.Lineage.Api.Fanout [C:2] [TYPE Class] [SEMANTICS test,lineage,api,fanout]
|
|
# @ingroup Test
|
|
class TestFanout:
|
|
def test_trigger_requires_impact_record(self, db: Session) -> None:
|
|
# No impact record yet -> 404.
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
trigger_fanout(_D1_ID, env_id=_ENV, db=db, _=None)
|
|
assert exc_info.value.status_code == 404
|
|
|
|
def test_trigger_creates_plan(self, db: Session) -> None:
|
|
db.add(
|
|
DatasetImpactRecord(
|
|
environment_id=_ENV, dataset_uuid=_D1, diff={"changes": []}, rules_version="v1",
|
|
max_severity="critical",
|
|
affected_dashboards=[{"dashboard_id": "dash-a", "severity": "critical", "baseline_entries": [{"b": 1}]}],
|
|
)
|
|
)
|
|
db.commit()
|
|
dto = trigger_fanout(_D1_ID, env_id=_ENV, db=db, _=None)
|
|
assert dto.trigger == "dataset_updated"
|
|
assert dto.status == "running"
|
|
assert len(dto.entries) == 1
|
|
# #endregion Test.Lineage.Api.Fanout
|
|
|
|
# #endregion Test.Lineage.Api
|
|
|
|
|
|
# #region Test.Lineage.Api.Additional [C:3] [TYPE Module]
|
|
# @defgroup Remaining endpoint branches: impacts, deprecation, fanout approval/trigger/report, env 404.
|
|
|
|
from src.api.routes.lineage import (
|
|
create_fanout_approval_endpoint,
|
|
get_fanout_report,
|
|
list_impacts,
|
|
)
|
|
from src.services.lineage.fanout import FanoutApprovalRequiredError
|
|
|
|
_D2 = "d88b5678-0000-4000-8000-000000000088"
|
|
|
|
|
|
def _prod_db():
|
|
"""A DB with a production environment for fanout tests."""
|
|
engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False})
|
|
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-prod", name="prod", url="https://p.example.com", credentials_id="c1"))
|
|
session.add(
|
|
ResourceMapping(environment_id="env-prod", resource_type=ResourceType.DATASET, uuid=_D1, remote_integer_id=str(_D1_ID), resource_name="D1", last_synced_at=datetime.now(UTC))
|
|
)
|
|
session.commit()
|
|
return session
|
|
|
|
|
|
# #region Test.Lineage.Api.Additional.Impacts
|
|
class TestListImpacts:
|
|
def test_happy_path(self, db: Session) -> None:
|
|
db.add(DatasetImpactRecord(
|
|
environment_id=_ENV, dataset_uuid=_D1, rules_version="v1",
|
|
max_severity="critical", diff={}, affected_dashboards=[],
|
|
created_at=datetime.now(UTC),
|
|
))
|
|
db.commit()
|
|
resp = list_impacts(_D1_ID, env_id=_ENV, db=db, _=None)
|
|
assert len(resp) == 1
|
|
assert resp[0].dataset == _D1
|
|
assert resp[0].max_severity == "critical"
|
|
|
|
def test_unknown_dataset_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
list_impacts(999999, env_id=_ENV, db=db, _=None)
|
|
assert exc.value.status_code == 404
|
|
|
|
def test_unknown_env_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
list_impacts(_D1_ID, env_id="nope", db=db, _=None)
|
|
assert exc.value.status_code == 404
|
|
# #endregion Test.Lineage.Api.Additional.Impacts
|
|
|
|
|
|
# #region Test.Lineage.Api.Additional.Deprecation
|
|
class TestDeprecationManage:
|
|
def test_mark_with_successor(self, db: Session) -> None:
|
|
db.add(ResourceMapping(
|
|
environment_id=_ENV, resource_type=ResourceType.DATASET, uuid=_D2,
|
|
remote_integer_id="88", resource_name="D2", last_synced_at=datetime.now(UTC),
|
|
))
|
|
db.commit()
|
|
dto = mark_dataset_deprecated(_D1_ID, env_id=_ENV, successor_dataset_id=88, grace_window_days=7, db=db, _=None)
|
|
assert dto.dataset == _D1
|
|
assert dto.successor == _D2
|
|
assert dto.grace_window_days == 7
|
|
|
|
def test_mark_unknown_dataset_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
mark_dataset_deprecated(999999, env_id=_ENV, db=db, _=None)
|
|
assert exc.value.status_code == 404
|
|
|
|
def test_migrate_no_record_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
migrate_dependent(_D1_ID, env_id=_ENV, dashboard_uuid="dash-x", db=db, _=None)
|
|
assert exc.value.status_code == 404
|
|
|
|
def test_migrate_unknown_dataset_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
migrate_dependent(999999, env_id=_ENV, dashboard_uuid="dash-x", db=db, _=None)
|
|
assert exc.value.status_code == 404
|
|
# #endregion Test.Lineage.Api.Additional.Deprecation
|
|
|
|
|
|
# #region Test.Lineage.Api.Additional.FanoutApproval
|
|
class TestFanoutApprovalEndpoint:
|
|
def test_non_production_400(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
create_fanout_approval_endpoint(_D1_ID, env_id=_ENV, reason="go", db=db, current_user=SimpleNamespace(id="u1"))
|
|
assert exc.value.status_code == 400
|
|
|
|
def test_unknown_dataset_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
create_fanout_approval_endpoint(999999, env_id=_ENV, reason="go", db=db, current_user=SimpleNamespace(id="u1"))
|
|
assert exc.value.status_code == 404
|
|
|
|
def test_production_happy(self) -> None:
|
|
from unittest.mock import patch
|
|
db = _prod_db()
|
|
try:
|
|
with patch("src.api.routes.lineage.resolve_environment", return_value=SimpleNamespace(id="env-prod", is_production=True)):
|
|
resp = create_fanout_approval_endpoint(_D1_ID, env_id="env-prod", reason="go", db=db, current_user=SimpleNamespace(id="u1"))
|
|
assert resp["environment_id"] == "env-prod"
|
|
assert resp["dataset_uuid"] == _D1
|
|
finally:
|
|
db.close()
|
|
# #endregion Test.Lineage.Api.Additional.FanoutApproval
|
|
|
|
|
|
# #region Test.Lineage.Api.Additional.FanoutTrigger
|
|
class TestFanoutTrigger:
|
|
def _add_impact(self, db: Session) -> None:
|
|
db.add(DatasetImpactRecord(
|
|
environment_id=_ENV, dataset_uuid=_D1, rules_version="v1",
|
|
max_severity="warning", diff=[], affected_dashboards=["dash-a"],
|
|
created_at=datetime.now(UTC),
|
|
))
|
|
db.commit()
|
|
|
|
def test_no_impact_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
trigger_fanout(_D1_ID, env_id=_ENV, db=db, _=None, current_user=SimpleNamespace(id="u1"))
|
|
assert exc.value.status_code == 404
|
|
|
|
def test_production_requires_approval(self) -> None:
|
|
from unittest.mock import patch
|
|
db = _prod_db()
|
|
try:
|
|
db.add(DatasetImpactRecord(
|
|
environment_id="env-prod", dataset_uuid=_D1, rules_version="v1",
|
|
max_severity="warning", diff={}, affected_dashboards=[],
|
|
created_at=datetime.now(UTC),
|
|
))
|
|
db.commit()
|
|
with patch("src.api.routes.lineage.resolve_environment", return_value=SimpleNamespace(id="env-prod", is_production=True)):
|
|
with pytest.raises(HTTPException) as exc:
|
|
trigger_fanout(_D1_ID, env_id="env-prod", approval_id=None, db=db, _=None, current_user=SimpleNamespace(id="u1"))
|
|
assert exc.value.status_code == 403
|
|
finally:
|
|
db.close()
|
|
|
|
def test_non_production_happy(self, db: Session) -> None:
|
|
from unittest.mock import patch
|
|
self._add_impact(db)
|
|
plan = SimpleNamespace(id="plan-1", trigger="dataset_updated", status="planning", entries=[])
|
|
with patch("src.api.routes.lineage.create_plan", return_value=plan) as mock_create:
|
|
dto = trigger_fanout(_D1_ID, env_id=_ENV, db=db, _=None, current_user=SimpleNamespace(id="u1"))
|
|
assert dto.id == "plan-1"
|
|
mock_create.assert_called_once()
|
|
# #endregion Test.Lineage.Api.Additional.FanoutTrigger
|
|
|
|
|
|
# #region Test.Lineage.Api.Additional.FanoutReport
|
|
class TestFanoutReport:
|
|
def test_unknown_plan_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
get_fanout_report("no-such-plan", db=db, _=None)
|
|
assert exc.value.status_code == 404
|
|
|
|
def test_happy_path(self, db: Session) -> None:
|
|
from unittest.mock import patch
|
|
plan = SimpleNamespace(id="plan-1")
|
|
record = DatasetImpactRecord(
|
|
environment_id=_ENV, dataset_uuid=_D1, rules_version="v1",
|
|
max_severity="warning", diff={}, affected_dashboards=[], created_at=datetime.now(UTC),
|
|
)
|
|
db.add(record)
|
|
db.flush()
|
|
db.add(FanoutPlan(id="plan-1", environment_id=_ENV, dataset_impact_id=record.id, trigger="dataset_updated", status="planning", entries=[]))
|
|
db.commit()
|
|
with patch("src.api.routes.lineage.fleet_report", return_value={"plan_id": "plan-1", "per_dashboard": [], "run_status": "completed"}) as mock_fr:
|
|
dto = get_fanout_report("plan-1", db=db, _=None)
|
|
assert dto.plan_id == "plan-1"
|
|
assert dto.run_status == "completed"
|
|
mock_fr.assert_called_once()
|
|
# #endregion Test.Lineage.Api.Additional.FanoutReport
|
|
|
|
|
|
# #endregion Test.Lineage.Api.Additional
|
|
# #region Test.Lineage.Api.FinalBranches [C:3] [TYPE Module]
|
|
# @defgroup Conservative projection, prod approval consumption, ValueError mapping.
|
|
|
|
from unittest.mock import patch
|
|
|
|
|
|
# #region Test.Lineage.Api.FinalBranches.Dependents
|
|
class TestDependentsConservative:
|
|
def test_conservative_projection(self, db: Session) -> None:
|
|
db.add(DatasetUsageEdge(
|
|
environment_id=_ENV, dataset_uuid=_D1, chart_uuid="c2", dashboard_uuid="dash-a",
|
|
dashboard_title="Dash A", consumed_columns=[], consumed_metrics=[],
|
|
projection_confidence="conservative", unresolved_refs=[], edge_fingerprint="f" * 64,
|
|
))
|
|
db.commit()
|
|
resp = get_dependents(_D1_ID, env_id=_ENV, db=db, _=None)
|
|
assert resp.dependents[0].projection_confidence == "conservative"
|
|
# #endregion Test.Lineage.Api.FinalBranches.Dependents
|
|
|
|
|
|
# #region Test.Lineage.Api.FinalBranches.Fanout
|
|
class TestFanoutTriggerFinal:
|
|
def test_unknown_dataset_404(self, db: Session) -> None:
|
|
with pytest.raises(HTTPException) as exc:
|
|
trigger_fanout(999999, env_id=_ENV, db=db, _=None, current_user=SimpleNamespace(id="u1"))
|
|
assert exc.value.status_code == 404
|
|
|
|
def test_production_with_approval_consumes(self) -> None:
|
|
db = _prod_db()
|
|
try:
|
|
db.add(DatasetImpactRecord(
|
|
environment_id="env-prod", dataset_uuid=_D1, rules_version="v1",
|
|
max_severity="warning", diff={}, affected_dashboards=[], created_at=datetime.now(UTC),
|
|
))
|
|
db.commit()
|
|
plan = SimpleNamespace(id="plan-1", trigger="dataset_updated", status="planning", entries=[])
|
|
approval = SimpleNamespace(reason="approved by ops")
|
|
with patch("src.api.routes.lineage.resolve_environment", return_value=SimpleNamespace(id="env-prod", is_production=True)), \
|
|
patch("src.api.routes.lineage.consume_fanout_approval", return_value=approval) as mock_consume, \
|
|
patch("src.api.routes.lineage.create_plan", return_value=plan) as mock_create:
|
|
dto = trigger_fanout(
|
|
_D1_ID, env_id="env-prod", approval_id="appr-1",
|
|
db=db, _=None, current_user=SimpleNamespace(id="u1"),
|
|
)
|
|
mock_consume.assert_called_once()
|
|
assert mock_create.call_args.kwargs["approval_granted"] is True
|
|
assert mock_create.call_args.kwargs["approval_reason"] == "approved by ops"
|
|
assert dto.id == "plan-1"
|
|
finally:
|
|
db.close()
|
|
|
|
def test_create_plan_value_error_400(self, db: Session) -> None:
|
|
db.add(DatasetImpactRecord(
|
|
environment_id=_ENV, dataset_uuid=_D1, rules_version="v1",
|
|
max_severity="warning", diff={}, affected_dashboards=[], created_at=datetime.now(UTC),
|
|
))
|
|
db.commit()
|
|
with patch("src.api.routes.lineage.create_plan", side_effect=ValueError("no dashboards")):
|
|
with pytest.raises(HTTPException) as exc:
|
|
trigger_fanout(_D1_ID, env_id=_ENV, db=db, _=None, current_user=SimpleNamespace(id="u1"))
|
|
assert exc.value.status_code == 400
|
|
# #endregion Test.Lineage.Api.FinalBranches.Fanout
|
|
# #endregion Test.Lineage.Api.FinalBranches
|