Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
POSTGRES_DB=app
POSTGRES_USER=user
POSTGRES_PASSWORD=secret
DATABASE_URL=sqlite:///./dev.db
7 changes: 7 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Copy this file to .env and fill in the values.
# Do NOT commit the .env file to version control.

POSTGRES_DB=app
POSTGRES_USER=user
POSTGRES_PASSWORD=changeme
DATABASE_URL=postgresql://user:changeme@localhost:5432/app
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,9 @@

# macOS
.DS_Store

# Environment / secrets
.env

# SQLite databases
*.db
4 changes: 3 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ RUN apt-get update && apt-get install -y libpq-dev
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
RUN useradd -m appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--log-level", "trace"]
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--log-level", "info"]
57 changes: 34 additions & 23 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,57 @@
import pytest
from sqlalchemy import create_engine, inspect, text
from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from fastapi.testclient import TestClient
from main import create_app
from dependencies import get_db, database_url
from dependencies import get_db
from models import Base


def _make_sqlite_engine():
"""Return a fresh SQLite in-memory engine with the full schema."""
engine = create_engine(
"sqlite:///:memory:",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
Base.metadata.create_all(bind=engine)
return engine


@pytest.fixture(scope="session")
def test_engine():
"""Create test database engine"""
test_engine = create_engine(database_url)
Base.metadata.create_all(bind=test_engine)
yield test_engine
Base.metadata.drop_all(bind=test_engine)
"""Create test database engine (SQLite in-memory for portability)."""
engine = _make_sqlite_engine()
yield engine
engine.dispose()


@pytest.fixture(scope="function")
def test_db(test_engine):
"""Create test database session that rolls back after each test"""
connection = test_engine.connect()
transaction = connection.begin()
db = sessionmaker(
autocommit=False, autoflush=False, bind=connection,
join_transaction_mode="create_savepoint"
)()
def test_db():
"""Provide a clean, isolated DB session for each repository test.

Each test gets its own in-memory SQLite database so there is zero
state leakage between tests regardless of what the repository commits.
"""
engine = _make_sqlite_engine()
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db = Session()
try:
yield db
finally:
db.close()
transaction.rollback()
connection.close()
engine.dispose()


@pytest.fixture
def test_app(test_engine):
"""Create test FastAPI application with test database"""
def test_app():
"""Create a test FastAPI application backed by a fresh in-memory SQLite DB."""
engine = _make_sqlite_engine()

def override_get_db():
TestingSessionLocal = sessionmaker(
autocommit=False, autoflush=False, bind=test_engine
)
db = TestingSessionLocal()
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db = Session()
try:
yield db
finally:
Expand Down
5 changes: 3 additions & 2 deletions db.sql
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ DROP TABLE IF EXISTS books;

CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(50) UNIQUE NOT NULL,
author VARCHAR(100) UNIQUE NOT NULL
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
isbn VARCHAR(17) NOT NULL UNIQUE
);
24 changes: 21 additions & 3 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import re
from typing import Annotated

from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String
from pydantic import BaseModel, ConfigDict
from pydantic import BaseModel, ConfigDict, field_validator


# SQLAlchemy models
class Base(DeclarativeBase):
"""Base class for all database models"""

pass


class Book(Base):
"""Book model"""
Expand All @@ -18,13 +19,29 @@ class Book(Base):
id: Mapped[int] = mapped_column(primary_key=True, index=True)
title: Mapped[str] = mapped_column(String(255), index=True)
author: Mapped[str] = mapped_column(String(255))
isbn: Mapped[str] = mapped_column(String(17), nullable=False, unique=True)


# Pydantic models
class BookIn(BaseModel):
"""Pydantic model for book input"""

title: str
author: str
isbn: str

@field_validator("isbn")
@classmethod
def validate_isbn(cls, value: str) -> str:
"""Validate ISBN-10 or ISBN-13 format (digits only, or with hyphens)."""
# Strip hyphens for normalisation
digits = value.replace("-", "")
if re.fullmatch(r"\d{10}", digits) or re.fullmatch(r"\d{13}", digits):
return value
raise ValueError(
"isbn must be a valid ISBN-10 (10 digits) or ISBN-13 (13 digits), "
"optionally separated by hyphens."
)


class BookOut(BaseModel):
Expand All @@ -33,5 +50,6 @@ class BookOut(BaseModel):
id: int
title: str
author: str
isbn: str

model_config = ConfigDict(from_attributes=True)
3 changes: 2 additions & 1 deletion repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

# Create a new book
def create_book(db: Session, book: models.BookIn):
db_book = models.Book(title=book.title, author=book.author)
db_book = models.Book(title=book.title, author=book.author, isbn=book.isbn)
db.add(db_book)
db.commit()
db.refresh(db_book)
Expand All @@ -27,6 +27,7 @@ def update_book(db: Session, book_id: int, book: models.BookIn):
if db_book:
db_book.title = book.title
db_book.author = book.author
db_book.isbn = book.isbn
db.commit()
db.refresh(db_book)
return db_book
Expand Down
20 changes: 16 additions & 4 deletions routers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from typing import List

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from sqlalchemy.exc import IntegrityError

import models
import repositories
from dependencies import get_db
Expand All @@ -15,8 +18,16 @@
def create_book(book: models.BookIn, db: Session = Depends(get_db)):
try:
return repositories.create_book(db=db, book=book)
except IntegrityError as e:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="A book with the given ISBN already exists.",
) from e
except Exception as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Unable to create book.",
) from e


@router.get(
Expand All @@ -27,8 +38,9 @@ def get_books(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
return repositories.get_books(db=db, skip=skip, limit=limit)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
)
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error.",
) from e


@router.get(
Expand Down
Loading
Loading