Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

7.6 KB
Raw Blame
"""Shared fixtures for server unit tests.

Creates a test FastAPI app with an in-memory SQLite database and
provides an httpx AsyncClient for making requests.
"""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any

import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import StaticPool

from repowise.core.persistence.database import init_db
from repowise.core.persistence.search import FullTextSearch
from repowise.core.persistence.vector_store import InMemoryVectorStore
from repowise.core.providers.embedding.base import MockEmbedder


def _create_test_app():
    """Create a FastAPI app without the lifespan (we manage state manually)."""
    from contextlib import asynccontextmanager

    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    from fastapi.responses import JSONResponse

    from repowise.server.routers import (
        areas,
        blast_radius,
        c4,
        changes,
        code_health,
        costs,
        coupling,
        dead_code,
        decisions,
        doc_drift,
        episodes,
        events,
        external_systems,
        files,
        git,
        graph,
        health,
        jobs,
        meta,
        modules,
        overview,
        owners,
        pages,
        providers,
        refactoring,
        repos,
        search,
        security,
        symbols,
        webhooks,
        wins,
    )

    @asynccontextmanager
    async def noop_lifespan(app: FastAPI):
        yield

    app = FastAPI(title="repowise API Test", lifespan=noop_lifespan)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @app.exception_handler(LookupError)
    async def not_found_handler(request, exc):
        return JSONResponse(status_code=404, content={"detail": str(exc)})

    @app.exception_handler(ValueError)
    async def bad_request_handler(request, exc):
        return JSONResponse(status_code=400, content={"detail": str(exc)})

    app.include_router(health.router)
    app.include_router(repos.router)
    app.include_router(costs.router)
    app.include_router(pages.router)
    app.include_router(search.router)
    app.include_router(jobs.router)
    app.include_router(symbols.router)
    app.include_router(graph.router)
    app.include_router(blast_radius.router)
    app.include_router(c4.router)
    app.include_router(meta.router)
    app.include_router(webhooks.router)
    app.include_router(git.router)
    app.include_router(changes.router)
    app.include_router(wins.router)
    app.include_router(events.router)
    app.include_router(files.router)
    app.include_router(dead_code.router)
    app.include_router(doc_drift.router)
    # Same position as app.py, so route precedence in tests matches production.
    app.include_router(code_health.router)
    app.include_router(owners.router)
    app.include_router(modules.router)
    app.include_router(areas.router)
    app.include_router(coupling.router)
    app.include_router(decisions.router)
    app.include_router(episodes.router)
    app.include_router(external_systems.router)
    app.include_router(overview.router)
    app.include_router(refactoring.router)
    app.include_router(providers.router)
    app.include_router(security.router)

    return app


@pytest.fixture
async def test_engine():
    """In-memory SQLite engine with all tables created."""
    engine = create_async_engine(
        "sqlite+aiosqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    await init_db(engine)
    yield engine
    await engine.dispose()


@pytest.fixture
async def session_factory(test_engine):
    """Async session factory for the test engine."""
    return async_sessionmaker(test_engine, expire_on_commit=False, class_=AsyncSession)


@pytest.fixture
async def app(test_engine, session_factory):
    """Test FastAPI app with all state configured."""
    test_app = _create_test_app()

    fts = FullTextSearch(test_engine)
    await fts.ensure_index()

    embedder = MockEmbedder()
    vector_store = InMemoryVectorStore(embedder=embedder)

    test_app.state.engine = test_engine
    test_app.state.session_factory = session_factory
    test_app.state.fts = fts
    test_app.state.vector_store = vector_store
    test_app.state.background_tasks = set()  # Strong refs for background job tasks

    yield test_app
    await vector_store.close()


@pytest.fixture
async def client(app) -> AsyncClient:
    """httpx AsyncClient for making requests to the test app."""
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        yield c


@pytest.fixture
async def session(session_factory) -> AsyncSession:
    """A raw DB session for test setup (inserting test data directly)."""
    async with session_factory() as s:
        yield s
        await s.commit()


async def create_test_repo(client: AsyncClient, tmp_path: Path | None = None) -> dict:
    """Helper: create a test repository via the API and return its response.

    Uses a real temp directory with a ``.git`` folder to pass server-side
    path validation (``RepoCreate.validate_local_path``).
    """
    import tempfile

    if tmp_path is None:
        tmp_path = Path(tempfile.mkdtemp())
    repo_dir = tmp_path / "test-repo"
    repo_dir.mkdir(exist_ok=True)
    (repo_dir / ".git").mkdir(exist_ok=True)

    resp = await client.post(
        "/api/repos",
        json={
            "index": False,
            "name": "test-repo",
            "local_path": str(repo_dir),
            "url": "https://github.com/example/test-repo",
        },
    )
    assert resp.status_code == 201
    return resp.json()


def normalize_payload(value: Any, replace: dict[str, str]) -> Any:
    """Swap per-run substrings (temp paths, generated ids) for placeholders.

    Values, nesting and key order are kept exact; freeze the clock instead of
    masking timestamps, so a moved timestamp still fails the golden.
    """
    if isinstance(value, dict):
        return {k: normalize_payload(v, replace) for k, v in value.items()}
    if isinstance(value, list):
        return [normalize_payload(v, replace) for v in value]
    if isinstance(value, str):
        for old, new in replace.items():
            value = value.replace(old, new)
    return value


def path_placeholders(root: str | Path, placeholder: str = "<repo>") -> dict[str, str]:
    """Map a temp root, in either slash style, to one spelling on every OS.

    A separator right after the root becomes ``/`` too, so a joined path
    reads the same on Windows and Linux. Longest first, so the joined forms win.
    """
    native = str(root)
    replace: dict[str, str] = {}
    for form in {native, native.replace("\\", "/")}:
        replace[form + "\\"] = placeholder + "/"
        replace[form + "/"] = placeholder + "/"
        replace[form] = placeholder
    return dict(sorted(replace.items(), key=lambda kv: len(kv[0]), reverse=True))


def assert_payload_golden(path: Path, payload: Any) -> None:
    """Compare a normalized payload byte for byte, key order included.

    ``REPOWISE_REWRITE_GOLDEN=1`` rewrites the file instead, only for an
    intended behaviour change.
    """
    text = json.dumps(payload, indent=2, sort_keys=False) + "\n"
    if os.environ.get("REPOWISE_REWRITE_GOLDEN") == "1":
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(text, encoding="utf-8", newline="\n")
        pytest.skip("golden rewritten")
    assert text == path.read_text(encoding="utf-8")