From 3d4869501bf247175f4c7de74f9c89a0a84e13c7 Mon Sep 17 00:00:00 2001 From: vikram-blaxel Date: Mon, 11 May 2026 16:04:12 +0530 Subject: [PATCH 1/2] feat: add ISBN field to model --- models.py | 1 + 1 file changed, 1 insertion(+) diff --git a/models.py b/models.py index bd73c60..dd91182 100644 --- a/models.py +++ b/models.py @@ -18,6 +18,7 @@ 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(255), nullable=False) # Pydantic models class BookIn(BaseModel): From a2e7f575a8773e067aeae680a90e02b261b692a4 Mon Sep 17 00:00:00 2001 From: Reviewer Swarm Date: Mon, 11 May 2026 19:32:26 +0000 Subject: [PATCH 2/2] fix: automated review fixes for PR #24 --- .env.example | 5 +++ .gitignore | 6 +++ Dockerfile | 4 +- conftest.py | 45 ++++++++++++------- docker-compose.yml | 2 +- main.py | 8 ++-- models.py | 7 +-- repositories.py | 3 +- routers.py | 34 +++++++++++--- test_main.py | 108 ++++++++++++++++++++++++++++++++++++++++++--- 10 files changed, 185 insertions(+), 37 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..5df83db --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +# Copy this file to .env and fill in real values. Do NOT commit .env to version control. +POSTGRES_DB=app +POSTGRES_USER=user +POSTGRES_PASSWORD=change_me_before_use +DATABASE_URL=postgresql://user:change_me_before_use@db/app diff --git a/.gitignore b/.gitignore index aa0926b..697069d 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,9 @@ # macOS .DS_Store + +# Environment / secrets +.env + +# Test artifacts +test.db diff --git a/Dockerfile b/Dockerfile index b482401..2fed3e5 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 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"] diff --git a/conftest.py b/conftest.py index b9cb0aa..56af0dc 100644 --- a/conftest.py +++ b/conftest.py @@ -1,28 +1,41 @@ +import os 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 + +# Use an in-process SQLite database for all tests so no external Postgres is needed. +TEST_DATABASE_URL = "sqlite:///./test.db" + +# Set DATABASE_URL before importing application modules so dependencies.py does not raise. +os.environ.setdefault("DATABASE_URL", TEST_DATABASE_URL) + +from main import create_app # noqa: E402 (import after env setup) +from dependencies import get_db # noqa: E402 +from models import Base # noqa: E402 + @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 an in-memory SQLite engine for the test session.""" + engine = create_engine( + TEST_DATABASE_URL, connect_args={"check_same_thread": False} + ) + Base.metadata.create_all(bind=engine) + yield engine + Base.metadata.drop_all(bind=engine) @pytest.fixture(scope="function") def test_db(test_engine): - """Create test database session that rolls back after each test""" + """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" + autocommit=False, + autoflush=False, + bind=connection, + join_transaction_mode="create_savepoint", )() try: yield db @@ -34,13 +47,13 @@ def test_db(test_engine): @pytest.fixture def test_app(test_engine): - """Create test FastAPI application with test database""" + """Create test FastAPI application with test database override.""" def override_get_db(): - TestingSessionLocal = sessionmaker( + session_factory = sessionmaker( autocommit=False, autoflush=False, bind=test_engine ) - db = TestingSessionLocal() + db = session_factory() try: yield db finally: @@ -53,5 +66,5 @@ def override_get_db(): @pytest.fixture def client(test_app): - """Create test client""" + """Create test HTTP client.""" return TestClient(test_app) diff --git a/docker-compose.yml b/docker-compose.yml index d222eda..e4222f3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,7 +24,7 @@ services: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} ports: - - "5432:5432" + - "127.0.0.1:5432:5432" volumes: - postgres_data:/var/lib/postgresql/data - ./db.sql:/docker-entrypoint-initdb.d/db.sql diff --git a/main.py b/main.py index 5d31686..ef015a8 100644 --- a/main.py +++ b/main.py @@ -1,6 +1,6 @@ -from fastapi import FastAPI, Depends +from fastapi import FastAPI from routers import router -from dependencies import init_db, get_db +from dependencies import init_db def create_app() -> FastAPI: @@ -10,8 +10,8 @@ def create_app() -> FastAPI: # Initialize database init_db() - # Include routers - app.include_router(router, prefix="/api", dependencies=[Depends(get_db)]) + # Include routers (each route declares its own db dependency) + app.include_router(router, prefix="/api") return app diff --git a/models.py b/models.py index dd91182..14f10bc 100644 --- a/models.py +++ b/models.py @@ -7,8 +7,6 @@ class Base(DeclarativeBase): """Base class for all database models""" - pass - class Book(Base): """Book model""" @@ -18,7 +16,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(255), nullable=False) + isbn: Mapped[str] = mapped_column(String(255)) + # Pydantic models class BookIn(BaseModel): @@ -26,6 +25,7 @@ class BookIn(BaseModel): title: str author: str + isbn: str class BookOut(BaseModel): @@ -34,5 +34,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..7c42dc7 100644 --- a/routers.py +++ b/routers.py @@ -1,11 +1,17 @@ +import logging +from typing import List + from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.exc import IntegrityError, SQLAlchemyError from sqlalchemy.orm import Session -from typing import List + import models import repositories from dependencies import get_db -# Create router with prefix +logger = logging.getLogger(__name__) + +# Router for book endpoints router = APIRouter() @@ -15,20 +21,38 @@ def create_book(book: models.BookIn, db: Session = Depends(get_db)): try: return repositories.create_book(db=db, book=book) + except IntegrityError as e: + logger.exception("Integrity error creating book") + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, detail="Book already exists" + ) from e + except SQLAlchemyError as e: + logger.exception("Database error creating book") + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Internal server error", + ) from e except Exception as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + logger.exception("Unexpected error creating book") + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid request data" + ) from e @router.get( "/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)): + # Cap limit to prevent resource exhaustion + limit = min(limit, 100) try: return repositories.get_books(db=db, skip=skip, limit=limit) except Exception as e: + logger.exception("Error retrieving books") 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( diff --git a/test_main.py b/test_main.py index 3fea397..44eda09 100644 --- a/test_main.py +++ b/test_main.py @@ -1,15 +1,19 @@ +from sqlalchemy import inspect + from repositories import create_book, get_books, get_book, update_book, delete_book from models import BookIn -from sqlalchemy import create_engine, inspect # Test data constants TEST_BOOKS = [ - {"title": "Carrie", "author": "Stephen King"}, - {"title": "Ready Player One", "author": "Ernest Cline"}, + {"title": "Carrie", "author": "Stephen King", "isbn": "9780385086950"}, + {"title": "Ready Player One", "author": "Ernest Cline", "isbn": "9780307887436"}, ] + class TestMainApp: + """Tests for application-level setup.""" + def test_create_app(self, test_app): """Test application creation""" assert test_app is not None @@ -19,13 +23,17 @@ def test_database_initialization(self, test_engine): inspector = inspect(test_engine) assert "books" in inspector.get_table_names() + # Repository Tests class TestBookRepository: + """Tests for the book repository (data access layer).""" + def test_create_book(self, test_db): """Test creating a new book""" 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,7 +42,7 @@ 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) @@ -54,10 +62,11 @@ 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="9780000000001")) deleted_book = delete_book(test_db, book.id) assert deleted_book is not None @@ -67,5 +76,92 @@ def test_delete_book(self, test_db): def test_nonexistent_operations(self, test_db): """Test operations on nonexistent books""" assert get_book(test_db, 999999) is None - assert update_book(test_db, 999999, BookIn(title="Test", author="Test")) is None + assert update_book(test_db, 999999, BookIn(title="Test", author="Test", isbn="9780000000000")) is None assert delete_book(test_db, 999999) is None + + +# HTTP / Router Tests +class TestBookRoutes: + """Integration tests for the book HTTP endpoints.""" + + def test_create_book_returns_201(self, client): + """POST /api/books/ should create a book and return 201""" + payload = {"title": "Dune", "author": "Frank Herbert", "isbn": "9780441013593"} + 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_invalid_body_returns_422(self, client): + """POST /api/books/ with missing required fields should return 422""" + response = client.post("/api/books/", json={"title": "No Author or ISBN"}) + assert response.status_code == 422 + + def test_get_books_returns_200(self, client): + """GET /api/books/ should return a list and 200""" + # Create one book first + client.post("/api/books/", json={"title": "Dune", "author": "Frank Herbert", "isbn": "9780441013593"}) + response = client.get("/api/books/") + assert response.status_code == 200 + assert isinstance(response.json(), list) + + def test_get_book_returns_200(self, client): + """GET /api/books/{id} should return the book""" + created = client.post( + "/api/books/", + json={"title": "Neuromancer", "author": "William Gibson", "isbn": "9780441569595"}, + ).json() + response = client.get(f"/api/books/{created['id']}") + assert response.status_code == 200 + assert response.json()["id"] == created["id"] + + def test_get_book_not_found_returns_404(self, client): + """GET /api/books/{id} for a missing book should return 404""" + response = client.get("/api/books/999999") + assert response.status_code == 404 + + def test_update_book_returns_200(self, client): + """PUT /api/books/{id} should update the book and return 200""" + created = client.post( + "/api/books/", + json={"title": "Old Title", "author": "Old Author", "isbn": "9780000000002"}, + ).json() + updated_payload = {"title": "New Title", "author": "New Author", "isbn": "9780000000003"} + response = client.put(f"/api/books/{created['id']}", json=updated_payload) + assert response.status_code == 200 + data = response.json() + assert data["title"] == "New Title" + assert data["author"] == "New Author" + assert data["isbn"] == "9780000000003" + + def test_update_book_not_found_returns_404(self, client): + """PUT /api/books/{id} for a missing book should return 404""" + response = client.put( + "/api/books/999999", + json={"title": "X", "author": "Y", "isbn": "9780000000004"}, + ) + assert response.status_code == 404 + + def test_delete_book_returns_200(self, client): + """DELETE /api/books/{id} should delete and return the book""" + created = client.post( + "/api/books/", + json={"title": "To Delete", "author": "Author", "isbn": "9780000000005"}, + ).json() + response = client.delete(f"/api/books/{created['id']}") + assert response.status_code == 200 + # Verify it's gone + assert client.get(f"/api/books/{created['id']}").status_code == 404 + + def test_delete_book_not_found_returns_404(self, client): + """DELETE /api/books/{id} for a missing book should return 404""" + response = client.delete("/api/books/999999") + assert response.status_code == 404 + + def test_get_books_limit_cap(self, client): + """GET /api/books/ with limit > 100 should be capped to 100""" + response = client.get("/api/books/?limit=9999") + assert response.status_code == 200