Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run migrations #2

Merged
merged 7 commits into from
Feb 7, 2024
Merged
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
14 changes: 7 additions & 7 deletions bookbrary/routes/api/books.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from flask import Blueprint, request, current_app as app
from marshmallow import ValidationError
from bookbrary.deps import db
from flask_jwt_extended import jwt_required

from bookbrary.models.books import Book
from bookbrary.schemas import books_schema, BookSchema, book_schema
from bookbrary.services import book_service


books = Blueprint(name="books", import_name=__name__, url_prefix="/api/books")
Expand All @@ -18,20 +18,20 @@ def index() -> list[BookSchema]:
@books.post(rule="/")
@jwt_required()
def create():
if not request.json:
if request.json is None:
return {"message": "Request must be in JSON format"}, 400

# Validate the data with Marshmallow and save the book to the database
try:
check_book_exists = Book.query.filter_by(title=request.json["title"]).one()
check_book_exists = book_service.get_book_by_title(
title=request.json.get("title")
)

if check_book_exists:
return {"message": "Book already exists"}, 409

validated_book = BookSchema().load(data=request.json)
book = Book(**validated_book)

db.session.add(instance=book)
db.session.commit()
book = book_service.create_book(**validated_book)

return book_schema.dump(obj=book), 201
except ValidationError as e:
Expand Down
4 changes: 3 additions & 1 deletion bookbrary/services/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from .user_service import UserService
from .book_service import BookService

user_service = UserService()
book_service = BookService()

__all__ = ["user_service"]
__all__ = ["user_service", "book_service"]
32 changes: 32 additions & 0 deletions bookbrary/services/book_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from bookbrary.models import Book
from bookbrary.deps import db


class BookService:
def create_book(
self,
title: str,
author: str,
year: int,
genre: str,
created_at: str,
updated_at: str,
) -> Book:
book = Book()
book.title = title
book.author = author
book.year = year
book.genre = genre
book.created_at = created_at
book.updated_at = updated_at

db.session.add(instance=book)
db.session.commit()

return book

def get_all_books(self) -> list[Book]:
return Book.query.all()

def get_book_by_title(self, title: str) -> Book | None:
return Book.query.filter_by(title=title).first()
24 changes: 21 additions & 3 deletions bookbrary/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
from typing import Any, Generator
from flask import Flask
from flask.testing import FlaskClient
import pytest

from bookbrary.app import create_app
from bookbrary.services import user_service
from bookbrary.services import user_service, book_service
from bookbrary.deps import db
from bookbrary.models import Book, User


@pytest.fixture
Expand All @@ -22,11 +25,26 @@ def app() -> Generator[Flask, Any, None]:


@pytest.fixture()
def client(app):
def client(app: Flask) -> FlaskClient:
return app.test_client()


@pytest.fixture()
def user(app) -> Any:
def user(app: Flask) -> User:
with app.app_context():
return user_service.create_user("testuser", "validpassword")


@pytest.fixture()
def book(app: Flask) -> Book:
with app.app_context():
book = book_service.create_book(
title="Test Book",
author="Test Author",
year=2021,
genre="Test Genre",
created_at="2021-01-01",
updated_at="2021-01-01",
)

return book
8 changes: 8 additions & 0 deletions bookbrary/tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,11 @@ def test_login_valid_credentials(client, user) -> None:
)
assert response.status_code == 200
assert "access_token" in response.json


def test_login_no_data(client) -> None:
response = client.post(
"/api/auth/login", headers={"Content-Type": "application/json"}
)
assert response.status_code == 400
print(response.json)
55 changes: 55 additions & 0 deletions bookbrary/tests/test_books.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,58 @@
import pytest


def test_get_all_books(client) -> None:
response = client.get("/api/books/")
assert response.status_code == 200


@pytest.mark.parametrize(
"test_title,test_created_at, expected",
[
("Test Book 1", "2021-01-01", 201),
("Test Book 2", True, 400),
("Test Book", "2021-01-01", 409),
],
)
def test_create_book(client, user, book, test_title, test_created_at, expected) -> None:
auth_response = client.post(
"/api/auth/login",
json={
"username": "testuser",
"password": "validpassword",
},
)
assert auth_response.status_code == 200
assert "access_token" in auth_response.json

response = client.post(
"/api/books/",
headers={"Authorization": f"Bearer {auth_response.json['access_token']}"},
json={
"title": test_title,
"author": "Test Author",
"year": "2021",
"genre": "Test Genre",
"created_at": test_created_at,
"updated_at": "2021-01-01",
},
)
assert response.status_code == expected


def test_no_data(client, user) -> None:
auth_response = client.post(
"/api/auth/login",
json={
"username": "testuser",
"password": "validpassword",
},
)
response = client.post(
"/api/books/",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {auth_response.json['access_token']}",
},
)
assert response.status_code == 400
2 changes: 1 addition & 1 deletion nixpacks.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
providers = ["python"]

[start]
cmd = "gunicorn wsgi:application"
cmd = "flask db upgrade && gunicorn wsgi:application"
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ python =
3.12: py12, lint

[testenv]
deps = pytest
deps =
pytest
pytest-cov
setenv =
FLASK_SQLALCHEMY_DATABASE_URI=sqlite:///:memory:
FLASK_JWT_SECRET_KEY=secret
FLASK_SECRET_KEY=secret
commands = pytest {posargs}
commands = pytest --cov=bookbrary --cov-report=xml {posargs}

[testenv:lint]
deps = ruff
Expand Down
Loading