feat: add FastAPI backend with SQLite models and Docker setup

Implement milestone M2 (backend setup):

- FastAPI app factory (core/app.py) with CORS, lifespan table
  creation, and global error handlers using a standardized
  {detail, code, errors?} envelope
- Endpoints: GET /health, GET /api/v1/health, GET /api/v1/version
- SQLAlchemy 2.0 ORM: Article, Author, Category models with
  relationships, unique constraints, and FK pragma for SQLite
- Pydantic v2 schemas (create/update/read) for all models
- Env-driven config (DATABASE_URL, CORS_ORIGINS) + .env.example
- pytest suite (19 tests, ~95% coverage) with per-test SQLite
  databases via fixtures
- Dockerfile (python:3.11-slim) and docker-compose.yml with a
  persistent ./data/db volume and healthcheck
This commit is contained in:
Daniel Samson committed 2026-10-30 12:44:54 +00:00
1 parent 357a72114b
commit 9a6f75ebd8
32 files changed
+1465 -1

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
"""Shared pytest fixtures for the newzy backend test suite.
The application is pointed at a throwaway SQLite file *before* it is
imported, so the module-level engine created in ``db.session`` never
touches the real database.
"""
import os
import tempfile
from collections.abc import Iterator
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import Engine, create_engine, event
from sqlalchemy.orm import Session, sessionmaker
# --- Point the application at a temporary database before import ---------
_TMP_DB_FD, _TMP_DB_PATH = tempfile.mkstemp(suffix=".db")
os.close(_TMP_DB_FD)
os.environ["DATABASE_URL"] = f"sqlite:///{_TMP_DB_PATH}"
from db.session import get_db # noqa: E402
from main import app # noqa: E402
from models import Base # noqa: E402
def _enable_foreign_keys(dbapi_connection, _connection_record) -> None:
"""Mirror the FK pragma applied to the production engine (see db.session)."""
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
@pytest.fixture()
def engine() -> Iterator[Engine]:
"""A fresh SQLite database per test (created and destroyed around it)."""
fd, path = tempfile.mkstemp(suffix=".db")
os.close(fd)
test_engine = create_engine(
f"sqlite:///{path}", connect_args={"check_same_thread": False}
)
event.listen(test_engine, "connect", _enable_foreign_keys)
Base.metadata.create_all(test_engine)
try:
yield test_engine
finally:
test_engine.dispose()
Path(path).unlink(missing_ok=True)
@pytest.fixture()
def session(engine: Engine) -> Iterator[Session]:
"""A SQLAlchemy session bound to the per-test database."""
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
db = TestingSession()
try:
yield db
finally:
db.close()
@pytest.fixture()
def client(engine: Engine) -> Iterator[TestClient]:
"""A FastAPI TestClient whose ``get_db`` dependency is overridden per test."""
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
def override_get_db() -> Iterator[Session]:
db = TestingSession()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as test_client:
yield test_client
app.dependency_overrides.clear()
+29
View File
@@ -0,0 +1,29 @@
"""Tests for the health check endpoints."""
def test_health_returns_200_ok(client) -> None:
response = client.get("/health")
assert response.status_code == 200
def test_health_returns_expected_json_structure(client) -> None:
payload = client.get("/health").json()
assert payload["status"] == "ok"
assert "version" in payload
def test_api_v1_health_returns_200_ok(client) -> None:
"""The alternative health path ``/api/v1/health`` must behave the same."""
response = client.get("/api/v1/health")
assert response.status_code == 200
payload = response.json()
assert payload["status"] == "ok"
assert "version" in payload
def test_unknown_route_returns_standardized_error(client) -> None:
response = client.get("/api/v1/does-not-exist")
assert response.status_code == 404
payload = response.json()
assert payload["code"] == "not_found"
assert "detail" in payload
+137
View File
@@ -0,0 +1,137 @@
"""Tests for ORM model instantiation and database operations."""
import pytest
from sqlalchemy.exc import IntegrityError
from models import Article, Author, Category, slugify
class TestAuthor:
def test_create_and_commit(self, session) -> None:
author = Author(
name="Ada Lovelace", email="ada@example.com", bio="First programmer."
)
session.add(author)
session.commit()
session.refresh(author)
assert author.id is not None
assert session.get(Author, author.id).email == "ada@example.com"
def test_unique_name_enforced(self, session) -> None:
session.add(Author(name="Grace Hopper", email="grace@example.com"))
session.commit()
session.add(Author(name="Grace Hopper", email="other@example.com"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_unique_email_enforced(self, session) -> None:
session.add(Author(name="Grace Hopper", email="grace@example.com"))
session.commit()
session.add(Author(name="Another Person", email="grace@example.com"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_bio_is_nullable(self, session) -> None:
author = Author(name="Alan Turing", email="alan@example.com")
session.add(author)
session.commit()
session.refresh(author)
assert author.bio is None
class TestCategory:
def test_create_and_commit(self, session) -> None:
category = Category(name="Technology", slug="technology")
session.add(category)
session.commit()
session.refresh(category)
assert category.id is not None
assert session.get(Category, category.id).name == "Technology"
def test_unique_name_enforced(self, session) -> None:
session.add(Category(name="Science", slug="science"))
session.commit()
session.add(Category(name="Science", slug="science-2"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_unique_slug_enforced(self, session) -> None:
session.add(Category(name="Science", slug="science"))
session.commit()
session.add(Category(name="Science News", slug="science"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_slug_generation(self) -> None:
assert slugify("Technology & Science") == "technology-science"
assert slugify(" Sports ") == "sports"
assert slugify("Already-fine") == "already-fine"
assert slugify("Café News") == "cafe-news"
class TestArticle:
def _make_author_category(self, session) -> tuple[Author, Category]:
author = Author(name="Byline Writer", email="writer@example.com")
category = Category(name="World", slug="world")
session.add_all([author, category])
session.commit()
session.refresh(author)
session.refresh(category)
return author, category
def test_create_and_commit(self, session) -> None:
author, category = self._make_author_category(session)
article = Article(
title="First post",
content="Hello world.",
author_id=author.id,
category_id=category.id,
)
session.add(article)
session.commit()
session.refresh(article)
assert article.id is not None
assert article.created_at is not None
assert article.published is False
def test_foreign_key_relationships(self, session) -> None:
author, category = self._make_author_category(session)
article = Article(
title="Related",
content="Body text.",
author_id=author.id,
category_id=category.id,
)
session.add(article)
session.commit()
assert article.author.name == author.name
assert article.category.slug == "world"
assert article in author.articles
assert article in category.articles
def test_unique_title_enforced(self, session) -> None:
author, category = self._make_author_category(session)
session.add(
Article(title="Dup", content="one", author_id=author.id, category_id=category.id)
)
session.commit()
session.add(
Article(title="Dup", content="two", author_id=author.id, category_id=category.id)
)
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_foreign_key_enforced(self, session) -> None:
author, category = self._make_author_category(session)
article = Article(
title="Orphan", content="No such author.", author_id=9999, category_id=category.id
)
session.add(article)
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
+23
View File
@@ -0,0 +1,23 @@
"""Tests for the version endpoint."""
import re
_SEMVER = re.compile(r"^\d+\.\d+\.\d+$")
def test_version_returns_200_ok(client) -> None:
response = client.get("/api/v1/version")
assert response.status_code == 200
def test_version_response_format(client) -> None:
payload = client.get("/api/v1/version").json()
assert payload["app"] == "newzy"
assert _SEMVER.match(payload["version"]), f"unexpected version format: {payload['version']}"
def test_version_matches_configured_app_version(client) -> None:
from config import APP_VERSION
payload = client.get("/api/v1/version").json()
assert payload["version"] == APP_VERSION