diff --git a/.gitignore b/.gitignore index aa0926b..48b6465 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,6 @@ # macOS .DS_Store + +# Environment / secrets +.env diff --git a/Dockerfile b/Dockerfile index b482401..8c07937 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 adduser --disabled-password --gecos "" 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", "warning"] diff --git a/conftest.py b/conftest.py index b9cb0aa..a9cb322 100644 --- a/conftest.py +++ b/conftest.py @@ -1,11 +1,12 @@ import pytest -from sqlalchemy import create_engine, inspect, text +from sqlalchemy import create_engine, inspect from sqlalchemy.orm import sessionmaker from fastapi.testclient import TestClient from main import create_app from dependencies import get_db, database_url from models import Base + @pytest.fixture(scope="session") def test_engine(): """Create test database engine""" @@ -32,14 +33,22 @@ def test_db(test_engine): connection.close() -@pytest.fixture +@pytest.fixture(scope="function") def test_app(test_engine): - """Create test FastAPI application with test database""" + """Create test FastAPI application with test database. + + Uses a single connection with savepoint-based rollback so that data + written during a request is visible within the same test function but + is rolled back at the end of the test. + """ + connection = test_engine.connect() + transaction = connection.begin() + TestingSessionLocal = sessionmaker( + autocommit=False, autoflush=False, bind=connection, + join_transaction_mode="create_savepoint" + ) def override_get_db(): - TestingSessionLocal = sessionmaker( - autocommit=False, autoflush=False, bind=test_engine - ) db = TestingSessionLocal() try: yield db @@ -48,10 +57,13 @@ def override_get_db(): app = create_app() app.dependency_overrides[get_db] = override_get_db - return app + yield app + transaction.rollback() + connection.close() -@pytest.fixture + +@pytest.fixture(scope="function") def client(test_app): """Create test client""" return TestClient(test_app) diff --git a/docker-compose.yml b/docker-compose.yml index d222eda..b2d13dc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -23,8 +23,6 @@ services: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} - ports: - - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data - ./db.sql:/docker-entrypoint-initdb.d/db.sql diff --git a/models.py b/models.py index bd73c60..1076311 100644 --- a/models.py +++ b/models.py @@ -1,6 +1,7 @@ +import re 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 @@ -18,6 +19,8 @@ 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(13)) + # Pydantic models class BookIn(BaseModel): @@ -25,6 +28,18 @@ class BookIn(BaseModel): title: str author: str + isbn: str + + @field_validator("isbn") + @classmethod + def validate_isbn(cls, v: str) -> str: + """Validate ISBN-10 or ISBN-13 format.""" + if not re.match(r"^(?:\d{9}[\dX]|\d{13})$", v): + raise ValueError( + "isbn must be a valid ISBN-10 (9 digits + digit or X) " + "or ISBN-13 (13 digits)" + ) + return v class BookOut(BaseModel): @@ -33,5 +48,6 @@ class BookOut(BaseModel): id: int title: str author: str + isbn: str model_config = ConfigDict(from_attributes=True) diff --git a/repositories.py b/repositories.py index dc9ff88..525d798 100644 --- a/repositories.py +++ b/repositories.py @@ -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) @@ -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 diff --git a/routers.py b/routers.py index db667c3..826c695 100644 --- a/routers.py +++ b/routers.py @@ -1,10 +1,12 @@ -from fastapi import APIRouter, Depends, HTTPException, status +import logging +from fastapi import APIRouter, Depends, HTTPException, Query, status from sqlalchemy.orm import Session -from typing import List import models import repositories from dependencies import get_db +logger = logging.getLogger(__name__) + # Create router with prefix router = APIRouter() @@ -16,19 +18,29 @@ def create_book(book: models.BookIn, db: Session = Depends(get_db)): try: return repositories.create_book(db=db, book=book) except Exception as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + logger.error("Error creating book: %s", e) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="An error occurred processing your request", + ) from e @router.get( - "/books/", response_model=List[models.BookOut], status_code=status.HTTP_200_OK + "/books/", response_model=list[models.BookOut], status_code=status.HTTP_200_OK ) -def get_books(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): +def get_books( + skip: int = Query(default=0, ge=0), + limit: int = Query(default=10, ge=1, le=100), + db: Session = Depends(get_db), +): try: return repositories.get_books(db=db, skip=skip, limit=limit) except Exception as e: + logger.error("Error retrieving books: %s", e) raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e) - ) + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="An error occurred processing your request", + ) from e @router.get( diff --git a/test_main.py b/test_main.py index 3fea397..22991bc 100644 --- a/test_main.py +++ b/test_main.py @@ -1,24 +1,27 @@ from repositories import create_book, get_books, get_book, update_book, delete_book from models import BookIn -from sqlalchemy import create_engine, inspect +from sqlalchemy import inspect # Test data constants TEST_BOOKS = [ - {"title": "Carrie", "author": "Stephen King"}, - {"title": "Ready Player One", "author": "Ernest Cline"}, + {"title": "Carrie", "author": "Stephen King", "isbn": "9780385533225"}, + {"title": "Ready Player One", "author": "Ernest Cline", "isbn": "9780307887436"}, ] + class TestMainApp: def test_create_app(self, test_app): """Test application creation""" assert test_app is not None + assert len(test_app.routes) > 0 def test_database_initialization(self, test_engine): """Test database initialization""" inspector = inspect(test_engine) assert "books" in inspector.get_table_names() + # Repository Tests class TestBookRepository: def test_create_book(self, test_db): @@ -26,6 +29,7 @@ def test_create_book(self, test_db): book = create_book(test_db, BookIn(**TEST_BOOKS[0])) assert book.title == TEST_BOOKS[0]["title"] assert book.author == TEST_BOOKS[0]["author"] + assert book.isbn == TEST_BOOKS[0]["isbn"] assert book.id is not None def test_get_books(self, test_db): @@ -34,10 +38,23 @@ def test_get_books(self, test_db): book2 = create_book(test_db, BookIn(**TEST_BOOKS[1])) books = get_books(test_db) - #assert len(books) >= 2 + assert len(books) >= 2 assert any(b.id == book1.id for b in books) assert any(b.id == book2.id for b in books) + def test_get_books_pagination(self, test_db): + """Test pagination parameters for get_books""" + create_book(test_db, BookIn(**TEST_BOOKS[0])) + create_book(test_db, BookIn(**TEST_BOOKS[1])) + + books_page1 = get_books(test_db, skip=0, limit=1) + assert len(books_page1) == 1 + + books_page2 = get_books(test_db, skip=1, limit=1) + assert len(books_page2) == 1 + + assert books_page1[0].id != books_page2[0].id + def test_get_book(self, test_db): """Test getting a specific book""" created_book = create_book(test_db, BookIn(**TEST_BOOKS[0])) @@ -45,6 +62,7 @@ def test_get_book(self, test_db): assert retrieved_book is not None assert retrieved_book.id == created_book.id assert retrieved_book.title == TEST_BOOKS[0]["title"] + assert retrieved_book.isbn == TEST_BOOKS[0]["isbn"] def test_update_book(self, test_db): """Test updating a book""" @@ -54,18 +72,140 @@ def test_update_book(self, test_db): assert updated_book is not None assert updated_book.title == TEST_BOOKS[1]["title"] assert updated_book.author == TEST_BOOKS[1]["author"] + assert updated_book.isbn == TEST_BOOKS[1]["isbn"] def test_delete_book(self, test_db): """Test deleting a book""" - book = create_book(test_db, BookIn(title="To Delete", author="Author")) + book = create_book( + test_db, BookIn(title="To Delete", author="Author", isbn="9780307887436") + ) deleted_book = delete_book(test_db, book.id) assert deleted_book is not None assert deleted_book.id == book.id assert get_book(test_db, book.id) is None - def test_nonexistent_operations(self, test_db): - """Test operations on nonexistent books""" + def test_get_nonexistent_book(self, test_db): + """Test get operation on a nonexistent book""" assert get_book(test_db, 999999) is None - assert update_book(test_db, 999999, BookIn(title="Test", author="Test")) is None + + def test_update_nonexistent_book(self, test_db): + """Test update operation on a nonexistent book""" + assert ( + update_book( + test_db, 999999, BookIn(title="Test", author="Test", isbn="9780307887436") + ) + is None + ) + + def test_delete_nonexistent_book(self, test_db): + """Test delete operation on a nonexistent book""" assert delete_book(test_db, 999999) is None + + +# HTTP / Router Tests +class TestAPIRoutes: + def test_create_book(self, client): + """Test POST /api/books/ happy path""" + payload = {"title": "Dune", "author": "Frank Herbert", "isbn": "9780340960196"} + response = client.post("/api/books/", json=payload) + assert response.status_code == 201 + data = response.json() + assert data["title"] == payload["title"] + assert data["author"] == payload["author"] + assert data["isbn"] == payload["isbn"] + assert "id" in data + + def test_create_book_missing_isbn_returns_422(self, client): + """Test POST /api/books/ returns 422 when isbn is absent""" + payload = {"title": "Dune", "author": "Frank Herbert"} + response = client.post("/api/books/", json=payload) + assert response.status_code == 422 + + def test_create_book_invalid_isbn_returns_422(self, client): + """Test POST /api/books/ returns 422 when isbn format is invalid""" + payload = {"title": "Dune", "author": "Frank Herbert", "isbn": "not-an-isbn"} + response = client.post("/api/books/", json=payload) + assert response.status_code == 422 + + def test_get_books(self, client): + """Test GET /api/books/ returns a list""" + client.post( + "/api/books/", + json={"title": "Carrie", "author": "Stephen King", "isbn": "9780385533225"}, + ) + response = client.get("/api/books/") + assert response.status_code == 200 + assert isinstance(response.json(), list) + + def test_get_books_pagination_limit(self, client): + """Test GET /api/books/ respects limit query parameter""" + for i in range(3): + client.post( + "/api/books/", + json={"title": f"Book {i}", "author": "Author", "isbn": "9780385533225"}, + ) + response = client.get("/api/books/?limit=2&skip=0") + assert response.status_code == 200 + assert len(response.json()) <= 2 + + def test_get_books_limit_exceeds_max_returns_422(self, client): + """Test GET /api/books/ returns 422 when limit exceeds maximum (100)""" + response = client.get("/api/books/?limit=1000000") + assert response.status_code == 422 + + def test_get_book(self, client): + """Test GET /api/books/{book_id} happy path""" + create_resp = client.post( + "/api/books/", + json={"title": "1984", "author": "George Orwell", "isbn": "9780451524935"}, + ) + book_id = create_resp.json()["id"] + response = client.get(f"/api/books/{book_id}") + assert response.status_code == 200 + assert response.json()["id"] == book_id + + def test_get_book_not_found(self, client): + """Test GET /api/books/{book_id} returns 404 for missing book""" + response = client.get("/api/books/999999") + assert response.status_code == 404 + + def test_update_book(self, client): + """Test PUT /api/books/{book_id} happy path""" + create_resp = client.post( + "/api/books/", + json={"title": "Old Title", "author": "Old Author", "isbn": "9780451524935"}, + ) + book_id = create_resp.json()["id"] + update_payload = { + "title": "New Title", + "author": "New Author", + "isbn": "9780385533225", + } + response = client.put(f"/api/books/{book_id}", json=update_payload) + assert response.status_code == 200 + data = response.json() + assert data["title"] == "New Title" + assert data["isbn"] == "9780385533225" + + def test_update_book_not_found(self, client): + """Test PUT /api/books/{book_id} returns 404 for missing book""" + payload = {"title": "X", "author": "Y", "isbn": "9780451524935"} + response = client.put("/api/books/999999", json=payload) + assert response.status_code == 404 + + def test_delete_book(self, client): + """Test DELETE /api/books/{book_id} happy path""" + create_resp = client.post( + "/api/books/", + json={"title": "To Delete", "author": "Author", "isbn": "9780451524935"}, + ) + book_id = create_resp.json()["id"] + response = client.delete(f"/api/books/{book_id}") + assert response.status_code == 200 + assert response.json()["id"] == book_id + + def test_delete_book_not_found(self, client): + """Test DELETE /api/books/{book_id} returns 404 for missing book""" + response = client.delete("/api/books/999999") + assert response.status_code == 404