T0: absorb shared/ into backend — cot_logger→src/core, CotJsonFormatter→src/core/cot_formatter.py, _llm_http/_llm_health/ssl→src/core/utils; imports rewritten (26 prod + tests, patch targets); run.sh/backend.Dockerfile/requirements/.axiom source_dirs/semantic_health/AGENTS/INSTALL cleaned; ADR-0022 supersedes ADR-0015; fixed latent CI defects (ss_tools ImportError, record.message in logger tests, same-name test-module collision). ADR-0021 wire enrichment (additive): contract_id/claim/error_code/loc fields; _contract_id ContextVar + resolve_contract_id (explicit > belief_scope > declared-src mirror, derived src never mirrors); EXPLORE auto-loc via single frame walk; facade error auto-fill; 2KB payload cap with payload_truncated/payload_bytes markers; migrated 85 error="CODE" sites to error_code= (12 files); pilot editor/load.py; superset preview payload-bomb inlined bodies removed. Analytics SSOT src/core/log_stats.py (bond transition matrix, orphan-EXPLORE ratio, REFLECT pairing, intent families, coverage, insufficient-sample flag); pretty_cot.py --stats/--digest/--trajectory/--story over one engine; log_gap_service three-tier ground-truth triangulation (FAILED w/o EXPLORE etc.) + GET /api/reports/log-stats|task-log-gaps (polling-suppressed); scripts/cot_audit.py CLI; enriched fields persisted into task_logs.payload for tier queries. Frontend: ReportsAnalyticsModel + AnalyticsStatsPanel (Logs tab) + TaskGapPanel and per-row T1/T2/T3 gap badges (Tasks tab); cot-logger.ts ADR-0021 opts; i18n en/ru. Scheduler console spam fixed: apscheduler logger demoted to WARNING via LoggingConfig.scheduler_log_level. .axiom belief patterns -> $OBJ.* (alias undercount). molecular-cot-logging skill updated (fields, decision rules, tie-break, CLI) and synced. Reviewed orthogonally: F1 cot_span contract pollution, F2 cap boundary accounting, F3 digest over-dedup, F4 trace-state bound, F5 tier metadata — fixed with regression tests. Validation: backend 11287 passed + ruff + compileall; frontend 3446 passed + lint + build; CLI smoke on live app.log.
292 lines
11 KiB
Python
292 lines
11 KiB
Python
# #region Test.Api.ReportsRoutes [C:3] [TYPE Module] [SEMANTICS test,reports,api]
|
|
# @BRIEF Tests for reports.py — list reports and get report detail.
|
|
# @RELATION BINDS_TO -> [Api.Reports.ReportsRouter]
|
|
# @TEST_EDGE: parse_invalid_task_type -> 400
|
|
# @TEST_EDGE: parse_invalid_status -> 400
|
|
# @TEST_EDGE: general_query_exception -> 400
|
|
# @TEST_EDGE: report_not_found -> 404
|
|
|
|
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")
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, patch, AsyncMock
|
|
|
|
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_client(overrides: dict | None = None, raise_server_exceptions: bool = True) -> TestClient:
|
|
from src.api.routes.reports import router
|
|
from src.dependencies import get_clean_release_repository, get_task_manager, get_current_user, has_permission
|
|
from src.schemas.auth import User, RoleSchema
|
|
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
|
|
mock_user = User(
|
|
id="user-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=[])],
|
|
)
|
|
|
|
defaults = {
|
|
get_task_manager: lambda: MagicMock(),
|
|
get_clean_release_repository: lambda: MagicMock(),
|
|
get_current_user: lambda: mock_user,
|
|
has_permission: lambda *a, **kw: lambda: None,
|
|
}
|
|
if overrides:
|
|
defaults.update(overrides)
|
|
for dep, mock_fn in defaults.items():
|
|
app.dependency_overrides[dep] = mock_fn
|
|
return TestClient(app, raise_server_exceptions=raise_server_exceptions)
|
|
|
|
|
|
# ── _parse_csv_enum_list ──
|
|
|
|
class TestParseCsvEnumList:
|
|
"""_parse_csv_enum_list — parse comma-separated values into enum list."""
|
|
|
|
def test_none_returns_empty(self):
|
|
from src.api.routes.reports import _parse_csv_enum_list
|
|
from src.models.report import TaskType
|
|
assert _parse_csv_enum_list(None, TaskType, "task_types") == []
|
|
|
|
def test_empty_string_returns_empty(self):
|
|
from src.api.routes.reports import _parse_csv_enum_list
|
|
from src.models.report import TaskType
|
|
assert _parse_csv_enum_list("", TaskType, "task_types") == []
|
|
|
|
def test_valid_values_parsed(self):
|
|
from src.api.routes.reports import _parse_csv_enum_list
|
|
from src.models.report import TaskType
|
|
result = _parse_csv_enum_list("backup, migration", TaskType, "task_types")
|
|
assert TaskType.BACKUP in result
|
|
assert TaskType.MIGRATION in result
|
|
|
|
def test_invalid_values_raise_400(self):
|
|
from fastapi import HTTPException
|
|
from src.api.routes.reports import _parse_csv_enum_list
|
|
from src.models.report import TaskType
|
|
with pytest.raises(HTTPException) as exc:
|
|
_parse_csv_enum_list("INVALID_TYPE", TaskType, "task_types")
|
|
assert exc.value.status_code == 400
|
|
|
|
|
|
# ── list_reports ──
|
|
|
|
class TestListReports:
|
|
"""GET /api/reports"""
|
|
|
|
def test_list_success(self):
|
|
from src.models.report import ReportCollection, ReportQuery
|
|
with patch("src.api.routes.reports.ReportsService") as MockService:
|
|
instance = MockService.return_value
|
|
instance.list_reports.return_value = ReportCollection(
|
|
items=[], total=0, page=1, page_size=20, has_next=False,
|
|
applied_filters=ReportQuery(),
|
|
)
|
|
client = _make_client()
|
|
resp = client.get("/api/reports?page=1&page_size=20")
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert "items" in data
|
|
assert "total" in data
|
|
|
|
def test_list_with_filters(self):
|
|
from src.models.report import ReportCollection, ReportQuery
|
|
with patch("src.api.routes.reports.ReportsService") as MockService:
|
|
instance = MockService.return_value
|
|
instance.list_reports.return_value = ReportCollection(
|
|
items=[], total=0, page=1, page_size=20, has_next=False,
|
|
applied_filters=ReportQuery(search="test", sort_by="updated_at", sort_order="asc"),
|
|
)
|
|
client = _make_client()
|
|
resp = client.get("/api/reports?page=1&page_size=20&search=test&sort_by=updated_at&sort_order=asc")
|
|
assert resp.status_code == 200
|
|
|
|
def test_list_invalid_task_type_400(self):
|
|
client = _make_client()
|
|
resp = client.get("/api/reports?task_types=INVALID")
|
|
assert resp.status_code == 400
|
|
|
|
def test_list_invalid_status_400(self):
|
|
client = _make_client()
|
|
resp = client.get("/api/reports?statuses=INVALID")
|
|
assert resp.status_code == 400
|
|
|
|
def test_list_service_exception_500(self):
|
|
with patch("src.api.routes.reports.ReportsService") as MockService:
|
|
instance = MockService.return_value
|
|
instance.list_reports.side_effect = ValueError("Internal error")
|
|
client = _make_client(raise_server_exceptions=False)
|
|
resp = client.get("/api/reports?page=1&page_size=20")
|
|
# Exception from service call is outside try-except -> 500
|
|
assert resp.status_code == 500
|
|
|
|
def test_list_invalid_page_size_400(self):
|
|
mock_task_manager = MagicMock()
|
|
mock_clean_repo = MagicMock()
|
|
|
|
from src.dependencies import get_task_manager, get_clean_release_repository
|
|
client = _make_client({
|
|
get_task_manager: lambda: mock_task_manager,
|
|
get_clean_release_repository: lambda: mock_clean_repo,
|
|
})
|
|
# page_size=0 is rejected by Query(ge=1) -> FastAPI 422
|
|
resp = client.get("/api/reports?page_size=0")
|
|
assert resp.status_code == 422
|
|
|
|
|
|
# ── get_report_detail ──
|
|
|
|
class TestGetReportDetail:
|
|
"""GET /api/reports/{report_id}"""
|
|
|
|
def test_detail_success(self):
|
|
from src.models.report import ReportDetailView, TaskReport, ReportStatus, TaskType
|
|
dt = __import__("datetime").datetime.now()
|
|
with patch("src.api.routes.reports.ReportsService") as MockService:
|
|
instance = MockService.return_value
|
|
instance.get_report_detail.return_value = ReportDetailView(
|
|
report=TaskReport(
|
|
report_id="report-1",
|
|
task_id="task-1",
|
|
task_type=TaskType.BACKUP,
|
|
status=ReportStatus.SUCCESS,
|
|
updated_at=dt,
|
|
summary="Backup completed successfully",
|
|
),
|
|
diagnostics=None,
|
|
next_actions=[],
|
|
)
|
|
client = _make_client()
|
|
resp = client.get("/api/reports/report-1")
|
|
assert resp.status_code == 200
|
|
data = resp.json()
|
|
assert data["report"]["report_id"] == "report-1"
|
|
|
|
def test_detail_not_found(self):
|
|
mock_task_manager = MagicMock()
|
|
mock_clean_repo = MagicMock()
|
|
|
|
from src.dependencies import get_task_manager, get_clean_release_repository
|
|
client = _make_client({
|
|
get_task_manager: lambda: mock_task_manager,
|
|
get_clean_release_repository: lambda: mock_clean_repo,
|
|
})
|
|
|
|
with patch("src.api.routes.reports.ReportsService") as MockService:
|
|
instance = MockService.return_value
|
|
instance.get_report_detail.return_value = None
|
|
resp = client.get("/api/reports/report-missing")
|
|
assert resp.status_code == 404
|
|
assert "REPORT_NOT_FOUND" in resp.text
|
|
# ── analytics endpoints (ADR-0021) ──
|
|
|
|
class TestTailLines:
|
|
"""_tail_lines — seek-from-end reading for the polled window=file mode."""
|
|
|
|
def test_small_file_fully_read(self, tmp_path):
|
|
from src.api.routes.reports import _tail_lines
|
|
p = tmp_path / "small.log"
|
|
p.write_text("a\nb\nc\n", encoding="utf-8")
|
|
assert _tail_lines(p, 10) == ["a", "b", "c"]
|
|
|
|
def test_returns_last_limit_lines(self, tmp_path):
|
|
from src.api.routes.reports import _tail_lines
|
|
p = tmp_path / "app.log"
|
|
p.write_text("".join(f'{{"i": {i}}}\n' for i in range(100)), encoding="utf-8")
|
|
lines = _tail_lines(p, 5)
|
|
assert len(lines) == 5
|
|
import json as _json
|
|
assert _json.loads(lines[-1])["i"] == 99
|
|
|
|
def test_large_file_seek_drops_partial_line(self, tmp_path):
|
|
import json as _json
|
|
from src.api.routes.reports import _tail_lines
|
|
p = tmp_path / "big.log"
|
|
line = '{"i": %d, "pad": "' + "x" * 80 + '"}'
|
|
p.write_text("".join((line % i) + "\n" for i in range(3000)), encoding="utf-8")
|
|
assert p.stat().st_size > 64 * 1024 # forces the seek path
|
|
lines = _tail_lines(p, 25)
|
|
assert len(lines) == 25
|
|
for raw in lines:
|
|
_json.loads(raw) # no partial line fragments
|
|
assert _json.loads(lines[-1])["i"] == 2999
|
|
|
|
def test_missing_file_returns_empty(self, tmp_path):
|
|
from src.api.routes.reports import _tail_lines
|
|
assert _tail_lines(tmp_path / "nope.log", 10) == []
|
|
|
|
|
|
class TestGetLogStats:
|
|
"""GET /api/reports/log-stats — single-engine analytics endpoint."""
|
|
|
|
def test_buffer_window_shape(self):
|
|
client = _make_client()
|
|
resp = client.get("/api/reports/log-stats")
|
|
assert resp.status_code == 200
|
|
body = resp.json()
|
|
assert body["window"] == "buffer"
|
|
assert "lines" in body["stats"]
|
|
assert "marker_mix" in body["stats"]
|
|
assert "transitions_normalized" in body["stats"]
|
|
|
|
def test_invalid_window_rejected(self):
|
|
client = _make_client()
|
|
resp = client.get("/api/reports/log-stats", params={"window": "nope"})
|
|
assert resp.status_code == 422
|
|
|
|
def test_file_window_shape(self):
|
|
client = _make_client()
|
|
resp = client.get("/api/reports/log-stats", params={"window": "file"})
|
|
assert resp.status_code == 200
|
|
assert resp.json()["window"] == "file"
|
|
|
|
|
|
class TestGetTaskLogGaps:
|
|
"""GET /api/reports/task-log-gaps — three-tier triangulation endpoint."""
|
|
|
|
def test_returns_three_tiers(self):
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.pool import StaticPool
|
|
|
|
from src.core.database import get_db
|
|
from src.models.task import TaskLogRecord, TaskRecord
|
|
|
|
# TestClient runs the ASGI app in a worker thread — share one in-memory
|
|
# connection across threads (StaticPool + check_same_thread=False).
|
|
engine = create_engine(
|
|
"sqlite:///:memory:",
|
|
connect_args={"check_same_thread": False},
|
|
poolclass=StaticPool,
|
|
)
|
|
TaskRecord.__table__.create(engine)
|
|
TaskLogRecord.__table__.create(engine)
|
|
session = sessionmaker(bind=engine)()
|
|
try:
|
|
client = _make_client(overrides={get_db: lambda: session})
|
|
resp = client.get("/api/reports/task-log-gaps")
|
|
assert resp.status_code == 200
|
|
body = resp.json()
|
|
for key in ("tier1_invisible_failures", "tier2_unbound_explore",
|
|
"tier3_silent_fallbacks"):
|
|
assert isinstance(body[key], list)
|
|
finally:
|
|
session.close()
|
|
|
|
|
|
# #endregion Test.Api.ReportsRoutes
|