feat: scaffold Brain of Reese — FastAPI RAG chat over Postgres 17 + pgvector
Foundation (phase 01, verified): - FastAPI app: /api/health, /api/suggestions, /api/chat (placeholder), static frontend served locally (no CDN) - Postgres 17 + pgvector via db/Containerfile + compose.yaml (podman compose up -d db), Alembic initial migration (documents, chunks with vector(768), query_log) - LLM client targeting https://aipi.reeseapps.com/v1 (turbo/embed); scripts/llm_probe.py verified models + 768-dim embeddings live - Conditional debugpy: imported only when DEBUGPY=1 (attach on demand, :5678); logging config for clean single-line logs - Frontend shell: mobile-first chat + Sources pages, tokens, a11y baselines - Tests: 24 unit+integration (99% coverage on app/), ruff + pyright clean, Playwright smoke E2E (3 tests) against a deterministic mock LLM - Planning: .agent/PLAN.md (architecture + LOCKED decisions), AGENTS.md, 6 user stories, 7 phase files (one story / one phase / one Playwright suite each)
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
"""Unit tests: settings defaults & env overrides."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.config import Settings
|
||||
|
||||
|
||||
def _settings(**kwargs: Any) -> Settings:
|
||||
"""Build Settings without reading a .env file (deterministic tests)."""
|
||||
kwargs.setdefault("_env_file", None)
|
||||
return Settings(**kwargs) # pyright: ignore[reportCallIssue] (kwarg exists at runtime)
|
||||
|
||||
|
||||
def test_defaults_match_locked_decisions() -> None:
|
||||
s = _settings()
|
||||
assert s.llm_chat_model == "turbo"
|
||||
assert s.llm_embed_model == "embed"
|
||||
assert s.embedding_dim == 768
|
||||
assert s.llm_base_url.endswith("/v1")
|
||||
assert 0 < s.relevance_threshold < 1
|
||||
assert s.top_k_chunks >= 1
|
||||
assert s.top_n_docs >= 1
|
||||
assert len(s.suggestions) >= 3
|
||||
|
||||
|
||||
def test_env_override(monkeypatch) -> None:
|
||||
monkeypatch.setenv("BOR_RELEVANCE_THRESHOLD", "0.42")
|
||||
monkeypatch.setenv("BOR_LLM_CHAT_MODEL", "juggernaut")
|
||||
s = _settings()
|
||||
assert s.relevance_threshold == 0.42
|
||||
assert s.llm_chat_model == "juggernaut"
|
||||
|
||||
|
||||
def test_effective_api_key_fallback(monkeypatch) -> None:
|
||||
monkeypatch.delenv("AIPI_KEY", raising=False)
|
||||
s = _settings()
|
||||
assert s.effective_api_key == "not-needed"
|
||||
|
||||
monkeypatch.setenv("AIPI_KEY", "sk-from-env")
|
||||
s2 = _settings()
|
||||
assert s2.effective_api_key == "sk-from-env"
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Unit tests: engine/session helpers (no live database required).
|
||||
|
||||
Creating a SQLAlchemy engine/session is lazy — no connection opens until the
|
||||
first query — so these run anywhere.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import db as app_db
|
||||
|
||||
|
||||
def test_engine_and_session_factory_are_lazy() -> None:
|
||||
assert isinstance(app_db.engine, Engine)
|
||||
session = app_db.SessionLocal()
|
||||
try:
|
||||
assert isinstance(session, Session)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_get_db_yields_session_and_closes_generator() -> None:
|
||||
gen = app_db.get_db()
|
||||
session = next(gen)
|
||||
assert isinstance(session, Session)
|
||||
session.close()
|
||||
gen.close() # exercises the finally: db.close()
|
||||
|
||||
|
||||
def test_db_available_true_on_select_one(monkeypatch) -> None:
|
||||
class _FakeConn:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc: object) -> None:
|
||||
return None
|
||||
|
||||
def execute(self, _stmt: object) -> None:
|
||||
return None
|
||||
|
||||
class _FakeEngine:
|
||||
def connect(self) -> _FakeConn:
|
||||
return _FakeConn()
|
||||
|
||||
monkeypatch.setattr(app_db, "engine", _FakeEngine())
|
||||
assert app_db.db_available() is True
|
||||
|
||||
|
||||
def test_db_available_false_on_error(monkeypatch) -> None:
|
||||
class _BrokenEngine:
|
||||
def connect(self) -> object:
|
||||
raise ConnectionError("db is down")
|
||||
|
||||
monkeypatch.setattr(app_db, "engine", _BrokenEngine())
|
||||
assert app_db.db_available() is False
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Unit tests: conditional debugpy gating (PLAN anchor A14).
|
||||
|
||||
Rules under test:
|
||||
* DEBUGPY unset or 0 -> configure_debugging() is False, debugpy NOT imported.
|
||||
* DEBUGPY=1 -> configure_debugging() is True, listener on DEBUGPY_PORT.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
import app.core.debugging as dbg
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def free_port() -> int:
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def test_disabled_by_default(monkeypatch) -> None:
|
||||
monkeypatch.delenv("DEBUGPY", raising=False)
|
||||
monkeypatch.delenv("DEBUGPY_PORT", raising=False)
|
||||
sys.modules.pop("debugpy", None)
|
||||
assert dbg.configure_debugging() is False
|
||||
assert "debugpy" not in sys.modules # zero overhead: never imported
|
||||
|
||||
|
||||
def test_explicit_zero(monkeypatch) -> None:
|
||||
monkeypatch.setenv("DEBUGPY", "0")
|
||||
sys.modules.pop("debugpy", None)
|
||||
assert dbg.configure_debugging() is False
|
||||
assert "debugpy" not in sys.modules
|
||||
|
||||
|
||||
def test_invalid_value_treated_as_disabled(monkeypatch) -> None:
|
||||
monkeypatch.setenv("DEBUGPY", "yes-please")
|
||||
assert dbg.configure_debugging() is False
|
||||
|
||||
|
||||
def test_enabled_starts_listener(monkeypatch, free_port) -> None:
|
||||
monkeypatch.setenv("DEBUGPY", "1")
|
||||
monkeypatch.setenv("DEBUGPY_PORT", str(free_port))
|
||||
try:
|
||||
assert dbg.configure_debugging() is True
|
||||
assert "debugpy" in sys.modules
|
||||
finally:
|
||||
dbg.shutdown_debugpy()
|
||||
|
||||
|
||||
def test_port_falls_back_on_invalid_value(monkeypatch) -> None:
|
||||
monkeypatch.setenv("DEBUGPY_PORT", "not-a-port")
|
||||
assert dbg._port() == 5678
|
||||
|
||||
|
||||
def test_shutdown_is_idempotent_when_disabled() -> None:
|
||||
dbg.shutdown_debugpy() # no listener → no-op, no error
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Unit tests: app factory edge cases (no live DB needed)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import app.main as main_mod
|
||||
|
||||
|
||||
def test_create_app_warns_and_serves_api_only_without_static_dir(
|
||||
monkeypatch, tmp_path
|
||||
) -> None:
|
||||
"""If the frontend directory is missing, the API still boots (PLAN §7)."""
|
||||
monkeypatch.setattr(
|
||||
main_mod.settings, "static_dir", str(tmp_path / "definitely-missing")
|
||||
)
|
||||
app2 = main_mod.create_app()
|
||||
client = TestClient(app2)
|
||||
# /api still works…
|
||||
assert client.get("/api/health").status_code == 200
|
||||
# …but the static mount is absent (no index page).
|
||||
assert client.get("/").status_code == 404
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Unit tests: SQLAlchemy models register the pgvector schema on the metadata.
|
||||
|
||||
Importing :mod:`app.models` is what Alembic's ``env.py`` and the runtime rely
|
||||
on; these tests lock the table/column contract (PLAN §5) without a live DB.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pgvector.sqlalchemy import Vector
|
||||
from sqlalchemy import UniqueConstraint
|
||||
|
||||
import app.models # noqa: F401 (import registers all tables on Base.metadata)
|
||||
from app.db import Base
|
||||
|
||||
|
||||
def test_all_tables_registered() -> None:
|
||||
tables = Base.metadata.tables
|
||||
assert "documents" in tables
|
||||
assert "chunks" in tables
|
||||
assert "query_log" in tables
|
||||
|
||||
|
||||
def test_chunks_embedding_is_vector_768() -> None:
|
||||
chunks = Base.metadata.tables["chunks"]
|
||||
col = chunks.c["embedding"]
|
||||
assert isinstance(col.type, Vector)
|
||||
assert col.type.dim == 768
|
||||
# Embeddings are two-phase: inserted first, embedded later.
|
||||
assert col.nullable is True
|
||||
|
||||
|
||||
def test_chunks_reference_documents_cascade() -> None:
|
||||
chunks = Base.metadata.tables["chunks"]
|
||||
fkc = list(chunks.foreign_key_constraints)[0]
|
||||
assert fkc.elements[0].column.table.name == "documents"
|
||||
assert fkc.ondelete == "CASCADE"
|
||||
|
||||
|
||||
def test_documents_unique_source_path() -> None:
|
||||
documents = Base.metadata.tables["documents"]
|
||||
uq = [
|
||||
c
|
||||
for c in documents.constraints
|
||||
if isinstance(c, UniqueConstraint)
|
||||
and {col.name for col in c.columns} == {"source", "path"}
|
||||
]
|
||||
assert uq, "documents must be unique on (source, path) — the upsert key"
|
||||
Reference in New Issue
Block a user