from __future__ import annotations import inspect import time from pathlib import Path from fastapi import FastAPI from fastapi.testclient import TestClient import app.store as store_module from app import main as main_module from app.models import Finding, Repository, Severity from app.rules import enrich_finding, enrich_findings from app.store import ScanStore def test_database_bound_endpoints_never_run_blocking_sqlite_on_the_event_loop() -> None: # A sync endpoint runs in the threadpool; an async one must offload its store work. assert not inspect.iscoroutinefunction(main_module.create_repository_scan) assert not inspect.iscoroutinefunction(main_module._handle_gitea_webhook) webhook_source = inspect.getsource(main_module.gitea_webhook) assert "store." not in webhook_source assert "run_in_threadpool(_handle_gitea_webhook" in webhook_source assert "asyncio.to_thread(store.save" in inspect.getsource(main_module.create_scan) def test_large_api_responses_are_gzip_compressed(tmp_path: Path) -> None: main_module.store = ScanStore(str(tmp_path / "history.db")) main_module.job_runner = None for index in range(12): main_module.store.upsert_repository( Repository( id=f"gitea:{index}", provider="gitea", provider_repository_id=str(index), owner="Jens", name=f"Repository{index}", full_name=f"Jens/Repository{index}", default_branch="main", ) ) client = TestClient(main_module.app) compressed = client.get("/api/v1/repositories", headers={"Accept-Encoding": "gzip"}) small = client.get("/health", headers={"Accept-Encoding": "gzip"}) assert compressed.status_code == 200 assert compressed.headers.get("content-encoding") == "gzip" assert len(compressed.json()) == 12 # Responses below the 1 KiB threshold are not worth compressing. assert small.headers.get("content-encoding") is None def test_hashed_frontend_assets_are_immutable_and_index_revalidates(tmp_path: Path) -> None: (tmp_path / "assets").mkdir() (tmp_path / "index.html").write_text("", encoding="utf-8") (tmp_path / "assets" / "index-abc123.js").write_text("console.log(1)", encoding="utf-8") app = FastAPI() app.mount("/", main_module._FrontendStaticFiles(directory=tmp_path, html=True), name="frontend") client = TestClient(app) asset = client.get("/assets/index-abc123.js") index = client.get("/") assert asset.headers["cache-control"] == "public, max-age=31536000, immutable" assert index.headers["cache-control"] == "no-cache" def test_finding_guidance_is_shared_and_unchanged() -> None: finding = Finding( code="security.secret-assignment", category="Security basics", severity=Severity.BLOCKER, message="m", deduction=20, ) first, second = enrich_findings([finding, finding.model_copy(update={"path": "b.py"})]) assert first.guidance is second.guidance assert first.guidance.priority == 800 assert first.guidance.priority_rationale == "Blocker signal; 20 health-point impact." assert enrich_finding(first) is first def test_expired_mirror_stats_are_served_while_refreshing_in_background(tmp_path: Path, monkeypatch) -> None: store = ScanStore(str(tmp_path / "history.db")) mirrors = tmp_path / "mirrors" mirrors.mkdir() calls: list[float] = [] def slow_walk(_root: Path) -> tuple[int, int]: calls.append(time.monotonic()) time.sleep(0.3) return len(calls), len(calls) * 100 monkeypatch.setattr(store, "_tree_stats", slow_walk) assert store._cached_mirror_stats(mirrors) == (1, 100) monkeypatch.setattr(store_module, "MIRROR_STATS_TTL_SECONDS", 0.0) started = time.monotonic() assert store._cached_mirror_stats(mirrors) == (1, 100) assert time.monotonic() - started < 0.2 deadline = time.monotonic() + 3 while store._mirror_stats_cache[2] == (1, 100) and time.monotonic() < deadline: time.sleep(0.05) assert store._mirror_stats_cache[2] == (2, 200)