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 16f6eaeb8032feaf614ec276708ae2aec790a784 Mon Sep 17 00:00:00 2001 From: Reviewer Swarm Date: Tue, 12 May 2026 18:35:54 +0000 Subject: [PATCH 2/2] fix: automated fixes for PR #24 --- Dockerfile | 5 +- conftest.py | 42 ++++++++++----- db.sql | 5 +- docker-compose.yml | 5 +- models.py | 5 +- repositories.py | 8 ++- routers.py | 21 +++++--- test_main.py | 130 ++++++++++++++++++++++++++++++++++++++++++--- 8 files changed, 189 insertions(+), 32 deletions(-) diff --git a/Dockerfile b/Dockerfile index b482401..438be7f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,10 @@ FROM python:3.11 RUN apt-get update && apt-get install -y libpq-dev +RUN pip install --upgrade pip wheel 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..c7ea317 100644 --- a/conftest.py +++ b/conftest.py @@ -1,18 +1,19 @@ 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""" - test_engine = create_engine(database_url) - Base.metadata.create_all(bind=test_engine) - yield test_engine - Base.metadata.drop_all(bind=test_engine) + engine = create_engine(database_url) + Base.metadata.create_all(bind=engine) + yield engine + Base.metadata.drop_all(bind=engine) @pytest.fixture(scope="function") @@ -21,8 +22,10 @@ def test_db(test_engine): 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 +37,23 @@ 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. + + Uses a single connection/transaction per test so that data written in one + request is visible to subsequent requests within the same test, while still + being rolled back at the end of the test. + """ + connection = test_engine.connect() + transaction = connection.begin() + testing_session_local = 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() + db = testing_session_local() try: yield db finally: @@ -48,7 +61,10 @@ 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 diff --git a/db.sql b/db.sql index 840a595..01c5d81 100644 --- a/db.sql +++ b/db.sql @@ -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) UNIQUE NOT NULL ); diff --git a/docker-compose.yml b/docker-compose.yml index d222eda..bb32266 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -23,8 +23,9 @@ services: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} - ports: - - "5432:5432" + # Port 5432 is intentionally NOT exposed to the host to prevent + # unauthenticated external access; the web service reaches it via + # the internal Docker network. volumes: - postgres_data:/var/lib/postgresql/data - ./db.sql:/docker-entrypoint-initdb.d/db.sql diff --git a/models.py b/models.py index dd91182..2cf29b6 100644 --- a/models.py +++ b/models.py @@ -18,7 +18,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(17), unique=True) + # Pydantic models class BookIn(BaseModel): @@ -26,6 +27,7 @@ class BookIn(BaseModel): title: str author: str + isbn: str class BookOut(BaseModel): @@ -34,5 +36,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..0de6644 100644 --- a/repositories.py +++ b/repositories.py @@ -4,7 +4,8 @@ # Create a new book def create_book(db: Session, book: models.BookIn): - db_book = models.Book(title=book.title, author=book.author) + """Create and persist a new book record.""" + db_book = models.Book(title=book.title, author=book.author, isbn=book.isbn) db.add(db_book) db.commit() db.refresh(db_book) @@ -13,20 +14,24 @@ def create_book(db: Session, book: models.BookIn): # Get all books def get_books(db: Session, skip: int = 0, limit: int = 10): + """Return a paginated list of books.""" return db.query(models.Book).offset(skip).limit(limit).all() # Get a book by ID def get_book(db: Session, book_id: int): + """Return a single book by its ID, or None if not found.""" return db.query(models.Book).filter(models.Book.id == book_id).first() # Update a book def update_book(db: Session, book_id: int, book: models.BookIn): + """Update an existing book's fields; returns None if not found.""" db_book = db.query(models.Book).filter(models.Book.id == book_id).first() 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 @@ -35,6 +40,7 @@ def update_book(db: Session, book_id: int, book: models.BookIn): # Delete a book def delete_book(db: Session, book_id: int): + """Delete a book by ID; returns the deleted object or None if not found.""" db_book = db.query(models.Book).filter(models.Book.id == book_id).first() if db_book: db.delete(db_book) diff --git a/routers.py b/routers.py index db667c3..c86014f 100644 --- a/routers.py +++ b/routers.py @@ -1,6 +1,6 @@ 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 @@ -13,28 +13,35 @@ "/books/", response_model=models.BookOut, status_code=status.HTTP_201_CREATED ) def create_book(book: models.BookIn, db: Session = Depends(get_db)): + """Create a new book.""" 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)) + except IntegrityError: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A book with that ISBN already exists or required fields are missing.", + ) from None @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)): + """Return a paginated list of books.""" try: 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="An error occurred while retrieving books.", + ) from e @router.get( "/books/{book_id}", response_model=models.BookOut, status_code=status.HTTP_200_OK ) def get_book(book_id: int, db: Session = Depends(get_db)): + """Return a single book by ID.""" db_book = repositories.get_book(db=db, book_id=book_id) if db_book is None: raise HTTPException( @@ -47,6 +54,7 @@ def get_book(book_id: int, db: Session = Depends(get_db)): "/books/{book_id}", response_model=models.BookOut, status_code=status.HTTP_200_OK ) def update_book(book_id: int, book: models.BookIn, db: Session = Depends(get_db)): + """Update an existing book by ID.""" db_book = repositories.update_book(db=db, book_id=book_id, book=book) if db_book is None: raise HTTPException( @@ -59,6 +67,7 @@ def update_book(book_id: int, book: models.BookIn, db: Session = Depends(get_db) "/books/{book_id}", response_model=models.BookOut, status_code=status.HTTP_200_OK ) def delete_book(book_id: int, db: Session = Depends(get_db)): + """Delete a book by ID.""" db_book = repositories.delete_book(db=db, book_id=book_id) if db_book is None: raise HTTPException( diff --git a/test_main.py b/test_main.py index 3fea397..548e644 100644 --- a/test_main.py +++ b/test_main.py @@ -1,14 +1,15 @@ 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""" @@ -19,6 +20,7 @@ def test_database_initialization(self, test_engine): inspector = inspect(test_engine) assert "books" in inspector.get_table_names() + # Repository Tests class TestBookRepository: def test_create_book(self, test_db): @@ -26,6 +28,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,7 +37,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) @@ -45,6 +48,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,10 +58,13 @@ 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 +74,116 @@ 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="9780000000002"), + ) + is None + ) assert delete_book(test_db, 999999) is None + + +# Router / HTTP Integration Tests +class TestBookRouter: + def test_create_book_http(self, client): + """POST /api/books/ creates a book and returns 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_payload(self, client): + """POST /api/books/ with missing fields returns 422""" + response = client.post("/api/books/", json={"title": "No Author or ISBN"}) + assert response.status_code == 422 + + def test_get_books_http(self, client): + """GET /api/books/ returns a list""" + client.post( + "/api/books/", + json={"title": "Book A", "author": "Author A", "isbn": "9780000000010"}, + ) + response = client.get("/api/books/") + assert response.status_code == 200 + assert isinstance(response.json(), list) + + def test_get_books_pagination(self, client): + """GET /api/books/ respects skip and limit parameters""" + for i in range(3): + client.post( + "/api/books/", + json={ + "title": f"Paginated Book {i}", + "author": "Author", + "isbn": f"978000000002{i}", + }, + ) + response = client.get("/api/books/?skip=0&limit=2") + assert response.status_code == 200 + assert len(response.json()) <= 2 + + def test_get_book_http(self, client): + """GET /api/books/{id} returns a single book""" + create_resp = client.post( + "/api/books/", + json={"title": "Neuromancer", "author": "William Gibson", "isbn": "9780441569595"}, + ) + 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): + """GET /api/books/{id} returns 404 for unknown ID""" + response = client.get("/api/books/999999") + assert response.status_code == 404 + + def test_update_book_http(self, client): + """PUT /api/books/{id} updates a book""" + create_resp = client.post( + "/api/books/", + json={"title": "Old Title", "author": "Old Author", "isbn": "9780000000030"}, + ) + book_id = create_resp.json()["id"] + update_payload = { + "title": "New Title", + "author": "New Author", + "isbn": "9780000000031", + } + 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"] == "9780000000031" + + def test_update_book_not_found(self, client): + """PUT /api/books/{id} returns 404 for unknown ID""" + response = client.put( + "/api/books/999999", + json={"title": "X", "author": "Y", "isbn": "9780000000032"}, + ) + assert response.status_code == 404 + + def test_delete_book_http(self, client): + """DELETE /api/books/{id} deletes a book""" + create_resp = client.post( + "/api/books/", + json={"title": "To Remove", "author": "Someone", "isbn": "9780000000040"}, + ) + 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 + # Confirm it's gone + assert client.get(f"/api/books/{book_id}").status_code == 404 + + def test_delete_book_not_found(self, client): + """DELETE /api/books/{id} returns 404 for unknown ID""" + response = client.delete("/api/books/999999") + assert response.status_code == 404