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
79 lines
2.4 KiB
Python
79 lines
2.4 KiB
Python
"""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()
|