diff --git a/app/__init__.py b/app/__init__.py index 4ab3975b8..454da7d68 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -8,6 +8,7 @@ migrate = Migrate() load_dotenv() + def create_app(test_config=None): app = Flask(__name__) app.url_map.strict_slashes = False @@ -15,13 +16,14 @@ def create_app(test_config=None): if test_config is None: app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + "SQLALCHEMY_DATABASE_URI" + ) else: app.config["TESTING"] = True app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_TEST_DATABASE_URI") + "SQLALCHEMY_TEST_DATABASE_URI" + ) - # import models for Alembic Setup from app.models.customer import Customer from app.models.video import Video @@ -31,6 +33,11 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - #Register Blueprints Here + # Register Blueprints Here + from .routes import rentals_bp, videos_bp, customers_bp + + app.register_blueprint(rentals_bp) + app.register_blueprint(videos_bp) + app.register_blueprint(customers_bp) - return app \ No newline at end of file + return app diff --git a/app/models/customer.py b/app/models/customer.py index e3aece97b..ff799f57d 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -1,4 +1,19 @@ from app import db + class Customer(db.Model): - id = db.Column(db.Integer, primary_key=True) \ No newline at end of file + id = db.Column(db.Integer, primary_key=True) + name = db.Column(db.String) + postal_code = db.Column(db.String) + phone = db.Column(db.String) + registered_at = db.Column(db.DateTime, nullable=True) + rentals = db.relationship("Rental", backref="customer", lazy=True) + + def customer_information(self): + return { + "id": self.id, + "name": self.name, + "postal_code": self.postal_code, + "phone": self.phone, + "registered_at": self.registered_at, + } diff --git a/app/models/rental.py b/app/models/rental.py index 11009e593..b7deee259 100644 --- a/app/models/rental.py +++ b/app/models/rental.py @@ -1,4 +1,9 @@ from app import db + class Rental(db.Model): - id = db.Column(db.Integer, primary_key=True) \ No newline at end of file + id = db.Column(db.Integer, primary_key=True) + customer_id = db.Column(db.Integer, db.ForeignKey("customer.id")) + video_id = db.Column(db.Integer, db.ForeignKey("video.id")) + due_date = db.Column(db.DateTime) + checked_out = db.Column(db.Boolean, default=False) diff --git a/app/models/video.py b/app/models/video.py index 9893a6ef9..9929e62fd 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -1,4 +1,18 @@ from app import db + class Video(db.Model): - id = db.Column(db.Integer, primary_key=True) \ No newline at end of file + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + release_date = db.Column(db.DateTime) + total_inventory = db.Column(db.Integer) + available_inventory = db.Column(db.Integer) + rentals = db.relationship("Rental", backref="video", lazy=True) + + def video_information(self): + return { + "id": self.id, + "title": self.title, + "release_date": self.release_date, + "total_inventory": self.total_inventory, + } diff --git a/app/routes.py b/app/routes.py index e69de29bb..a27ae83fc 100644 --- a/app/routes.py +++ b/app/routes.py @@ -0,0 +1,313 @@ +import os +from flask.signals import request_tearing_down +import requests +from sqlalchemy.orm import query +from app import db +from datetime import datetime, timedelta +from dotenv import load_dotenv +from app.models.rental import Rental +from app.models.video import Video +from app.models.customer import Customer +from flask import Blueprint, json, jsonify, request + +rentals_bp = Blueprint("rentals", __name__, url_prefix="/rentals") +videos_bp = Blueprint("videos", __name__, url_prefix="/videos") +customers_bp = Blueprint("customer", __name__, url_prefix="/customers") + + +def return_none_400(): + return jsonify(None), 400 + + +def word_not_included_in_request_body(missing_field): + return jsonify({"details": f"Request body must include {missing_field}."}), 400 + + +@videos_bp.route("", methods=["GET", "POST"]) +def handle_videos(): + videos = Video.query.all() + + if videos is None: + return jsonify([]), 200 + + elif request.method == "GET": + videos_list = [video.video_information() for video in videos] + + return jsonify(videos_list), 200 + + elif request.method == "POST": + request_body = request.get_json() + + missing_field_list = ["title", "release_date", "total_inventory"] + + for word in missing_field_list: + if word not in request_body: + return word_not_included_in_request_body(word) + + new_video = Video( + title=request_body["title"], + release_date=request_body["release_date"], + total_inventory=request_body["total_inventory"], + ) + + db.session.add(new_video) + db.session.commit() + + return new_video.video_information(), 201 + + +@videos_bp.route("/", methods=["GET", "PUT", "DELETE"]) +def handle_video_id(video_id): + + if video_id.isnumeric() is False: + return return_none_400() + + video = Video.query.get(video_id) + + if video is None: + return jsonify({"message": f"Video {video_id} was not found"}), 404 + + elif request.method == "GET": + return video.video_information(), 200 + + elif request.method == "PUT": + updated_body = request.get_json() + + if ( + "title" not in updated_body + or "release_date" not in updated_body + or "total_inventory" not in updated_body + ): + return return_none_400() + + video.title = updated_body["title"] + video.release_date = updated_body["release_date"] + video.total_inventory = updated_body["total_inventory"] + db.session.commit() + + return video.video_information(), 200 + + elif request.method == "DELETE": + db.session.delete(video) + db.session.commit() + + return jsonify({"id": video.id}), 200 + + +@customers_bp.route("", methods=["GET", "POST"]) +def active_customers(): + if request.method == "GET": + customers = Customer.query.all() + + customers_response = [] + for customer in customers: + customers_response.append(customer.customer_information()) + + return jsonify(customers_response), 200 + + elif request.method == "POST": + request_body = request.get_json() + + missing_field_list = ["name", "postal_code", "phone"] + + for word in missing_field_list: + if word not in request_body: + return word_not_included_in_request_body(word) + + new_customer = Customer( + name=request_body["name"], + phone=request_body["phone"], + postal_code=request_body["postal_code"], + ) + + db.session.add(new_customer) + db.session.commit() + + return jsonify(new_customer.customer_information()), 201 + + +@customers_bp.route("/", methods=["GET", "PUT", "DELETE"]) +def retrieve_customer(customer_id): + + if customer_id.isdigit() is False: + return return_none_400() + + customer = Customer.query.get(customer_id) + + if customer == None: + return jsonify({"message": "Customer 1 was not found"}), 404 + + elif request.method == "GET": + response_body = customer.customer_information() + return jsonify(response_body), 200 + + elif request.method == "PUT": + request_body = request.get_json() + if ( + "name" not in request_body + or "postal_code" not in request_body + or "phone" not in request_body + ): + return return_none_400() + + customer.name = request_body["name"] + customer.postal_code = request_body["postal_code"] + customer.phone = request_body["phone"] + db.session.commit() + + response_body = customer.customer_information() + return jsonify(response_body), 200 + + elif request.method == "DELETE": + db.session.delete(customer) + db.session.commit() + return jsonify({"id": customer.id}), 200 + + +@customers_bp.route("//rentals", methods=["GET"]) +def get_rentals_for_customer(customer_id): + customer = Customer.query.get(customer_id) + if customer is None: + return jsonify({"message": f"Customer {customer_id} was not found"}), 404 + + elif request.method == "GET": + list_of_videos = [] + for rental in customer.rentals: + video = Video.query.get(rental.video_id) + response_body = { + "release_date": video.release_date, + "title": video.title, + "due_date": rental.due_date, + } + list_of_videos.append(response_body) + + return jsonify(list_of_videos), 200 + + +@videos_bp.route("//rentals", methods=["GET"]) +def get_videos_for_rental(video_id): + video = Video.query.get(video_id) + if video is None: + return jsonify({"message": f"Video {video_id} was not found"}), 404 + elif request.method == "GET": + list_of_customers = [] + for rental in video.rentals: + customer = Customer.query.get(rental.customer_id) + response_body = { + "due_date": rental.due_date, + "name": customer.name, + "phone": customer.phone, + "postal_code": customer.postal_code, + } + list_of_customers.append(response_body) + + return jsonify(list_of_customers), 200 + + +@rentals_bp.route("/check-out", methods=["POST"]) +def get_rental_check_out(): + request_body = request.get_json() + + if "video_id" not in request_body or "customer_id" not in request_body: + return return_none_400() + + video = Video.query.get_or_404(request_body["video_id"]) + customer = Customer.query.get_or_404(request_body["customer_id"]) + + videos_checked_out = Rental.query.filter_by( + video_id=video.id, checked_out=True + ).count() + + available_inventory = video.total_inventory - videos_checked_out + + if available_inventory == 0: + return jsonify({"message": "Could not perform checkout"}), 400 + + new_rental = Rental( + video_id=video.id, + customer_id=customer.id, + due_date=datetime.now() + timedelta(days=7), + checked_out=True + # python - keyword argument passing through vs assignment, keyword argument to instate something or method, python convention + ) + + db.session.add(new_rental) + db.session.commit() + + videos_checked_out_by_customer = Rental.query.filter_by( + customer_id=customer.id, checked_out=True + ).count() + # specific customer and how many videos they have checked, better variable name + # even though we are checking it again, checked out wouldn't be included since the informa, + + if new_rental.checked_out is True: + available_inventory -= 1 + + return ( + jsonify( + { + "customer_id": customer.id, + "video_id": video.id, + "due_date": datetime.now() + timedelta(days=7), + "videos_checked_out_count": videos_checked_out_by_customer, + "available_inventory": available_inventory, + } + ), + 200, + ) + + +@rentals_bp.route("/check-in", methods=["POST"]) +def get_rental_check_in(): + request_body = request.get_json() + + if "video_id" not in request_body or "customer_id" not in request_body: + return return_none_400() + + video = Video.query.get_or_404(request_body["video_id"]) + customer = Customer.query.get_or_404(request_body["customer_id"]) + # queries automatically add to the session/db so redundate to do it again + + number_of_rentals = Rental.query.filter_by( + video_id=video.id, customer_id=customer.id, checked_out=True + ).count() + videos_checked_out = Rental.query.filter_by( + customer_id=customer.id, checked_out=True + ).count() + + if number_of_rentals == 0 or videos_checked_out == 0: + return ( + jsonify( + { + "message": f"No outstanding rentals for customer {customer.id} and video {video.id}" + } + ), + 400, + ) + + rental = Rental.query.filter_by( + video_id=video.id, customer_id=customer.id, checked_out=True + ).one() + rental.checked_out = False + + db.session.commit() + + video_availablity = Rental.query.filter_by( + video_id=video.id, checked_out=True + ).count() + available_inventory = video.total_inventory - video_availablity + videos_checked_out = Rental.query.filter_by( + customer_id=customer.id, checked_out=True + ).count() + + return ( + jsonify( + { + "customer_id": customer.id, + "video_id": video.id, + "videos_checked_out_count": videos_checked_out, + "available_inventory": available_inventory, + } + ), + 200, + ) diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..b8333a47e --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,95 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger("alembic.env") + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + "sqlalchemy.url", + str(current_app.extensions["migrate"].db.engine.url).replace("%", "%%"), +) +target_metadata = current_app.extensions["migrate"].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure(url=url, target_metadata=target_metadata, literal_binds=True) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, "autogenerate", False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info("No changes in schema detected.") + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions["migrate"].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/e147797fa333_.py b/migrations/versions/e147797fa333_.py new file mode 100644 index 000000000..4fa294192 --- /dev/null +++ b/migrations/versions/e147797fa333_.py @@ -0,0 +1,64 @@ +"""empty message + +Revision ID: e147797fa333 +Revises: +Create Date: 2021-11-16 09:09:04.617008 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "e147797fa333" +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "customer", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("name", sa.String(), nullable=True), + sa.Column("postal_code", sa.String(), nullable=True), + sa.Column("phone", sa.String(), nullable=True), + sa.Column("registered_at", sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint("id"), + ) + op.create_table( + "video", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("title", sa.String(), nullable=True), + sa.Column("release_date", sa.DateTime(), nullable=True), + sa.Column("total_inventory", sa.Integer(), nullable=True), + sa.Column("available_inventory", sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint("id"), + ) + op.create_table( + "rental", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("customer_id", sa.Integer(), nullable=True), + sa.Column("video_id", sa.Integer(), nullable=True), + sa.Column("due_date", sa.DateTime(), nullable=True), + sa.Column("checked_out", sa.Boolean(), nullable=True), + sa.ForeignKeyConstraint( + ["customer_id"], + ["customer.id"], + ), + sa.ForeignKeyConstraint( + ["video_id"], + ["video.id"], + ), + sa.PrimaryKeyConstraint("id"), + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table("rental") + op.drop_table("video") + op.drop_table("customer") + # ### end Alembic commands ### diff --git a/tests/conftest.py b/tests/conftest.py index 7e4632860..d19f21494 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,6 +14,7 @@ CUSTOMER_POSTAL_CODE = "12345" CUSTOMER_PHONE = "123-123-1234" + @pytest.fixture def app(): app = create_app({"TESTING": True}) @@ -34,33 +35,27 @@ def expire_session(sender, response, **extra): def client(app): return app.test_client() + @pytest.fixture def one_video(app): new_video = Video( - title=VIDEO_TITLE, + title=VIDEO_TITLE, release_date=VIDEO_RELEASE_DATE, total_inventory=VIDEO_INVENTORY, - ) + ) db.session.add(new_video) db.session.commit() + @pytest.fixture def one_customer(app): new_customer = Customer( - name=CUSTOMER_NAME, - postal_code=CUSTOMER_POSTAL_CODE, - phone=CUSTOMER_PHONE + name=CUSTOMER_NAME, postal_code=CUSTOMER_POSTAL_CODE, phone=CUSTOMER_PHONE ) db.session.add(new_customer) db.session.commit() + @pytest.fixture def one_checked_out_video(app, client, one_customer, one_video): - response = client.post("/rentals/check-out", json={ - "customer_id": 1, - "video_id": 1 - }) - - - - + response = client.post("/rentals/check-out", json={"customer_id": 1, "video_id": 1}) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 8d32038f2..c29be3042 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -26,6 +26,7 @@ def test_get_videos_no_saved_videos(client): assert response.status_code == 200 assert response_body == [] + def test_get_videos_one_saved_video(client, one_video): # Act response = client.get("/videos") @@ -38,6 +39,7 @@ def test_get_videos_one_saved_video(client, one_video): assert response_body[0]["id"] == VIDEO_ID assert response_body[0]["total_inventory"] == VIDEO_INVENTORY + def test_get_video(client, one_video): # Act response = client.get("/videos/1") @@ -49,6 +51,7 @@ def test_get_video(client, one_video): assert response_body["id"] == VIDEO_ID assert response_body["total_inventory"] == VIDEO_INVENTORY + def test_get_video_not_found(client): # Act response = client.get("/videos/1") @@ -58,6 +61,7 @@ def test_get_video_not_found(client): assert response.status_code == 404 assert response_body == {"message": "Video 1 was not found"} + def test_get_invalid_video_id(client, one_video): # Act response = client.get("/videos/hello") @@ -70,11 +74,14 @@ def test_get_invalid_video_id(client, one_video): # CREATE def test_create_video(client): # Act - response = client.post("/videos", json={ - "title": VIDEO_TITLE, - "release_date": VIDEO_RELEASE_DATE, - "total_inventory": VIDEO_INVENTORY - }) + response = client.post( + "/videos", + json={ + "title": VIDEO_TITLE, + "release_date": VIDEO_RELEASE_DATE, + "total_inventory": VIDEO_INVENTORY, + }, + ) response_body = response.get_json() @@ -89,12 +96,13 @@ def test_create_video(client): assert new_video assert new_video.title == VIDEO_TITLE + def test_create_video_must_contain_title(client): # Act - response = client.post("/videos", json={ - "release_date": VIDEO_RELEASE_DATE, - "total_inventory": VIDEO_INVENTORY - }) + response = client.post( + "/videos", + json={"release_date": VIDEO_RELEASE_DATE, "total_inventory": VIDEO_INVENTORY}, + ) response_body = response.get_json() # Assert @@ -103,12 +111,12 @@ def test_create_video_must_contain_title(client): assert response.status_code == 400 assert Video.query.all() == [] + def test_create_video_must_contain_release_date(client): # Act - response = client.post("/videos", json={ - "title": VIDEO_TITLE, - "total_inventory": VIDEO_INVENTORY - }) + response = client.post( + "/videos", json={"title": VIDEO_TITLE, "total_inventory": VIDEO_INVENTORY} + ) response_body = response.get_json() # Assert @@ -117,12 +125,12 @@ def test_create_video_must_contain_release_date(client): assert response.status_code == 400 assert Video.query.all() == [] + def test_create_video_must_contain_inventory(client): # Act - response = client.post("/videos", json={ - "title": VIDEO_TITLE, - "release_date": VIDEO_RELEASE_DATE - }) + response = client.post( + "/videos", json={"title": VIDEO_TITLE, "release_date": VIDEO_RELEASE_DATE} + ) response_body = response.get_json() assert "details" in response_body @@ -130,6 +138,7 @@ def test_create_video_must_contain_inventory(client): assert response.status_code == 400 assert Video.query.all() == [] + # DELETE def test_delete_video(client, one_video): # Act @@ -142,6 +151,7 @@ def test_delete_video(client, one_video): assert response.status_code == 200 assert Video.query.get(1) == None + def test_delete_video_not_found(client): # Act response = client.delete("/videos/1") @@ -152,13 +162,17 @@ def test_delete_video_not_found(client): assert response.status_code == 404 assert Video.query.all() == [] + def test_update_video(client, one_video): # Act - response = client.put("/videos/1", json={ - "title": "Updated Video Title", - "total_inventory": 2, - "release_date": "01-01-2021" - }) + response = client.put( + "/videos/1", + json={ + "title": "Updated Video Title", + "total_inventory": 2, + "release_date": "01-01-2021", + }, + ) response_body = response.get_json() # Assert @@ -171,25 +185,29 @@ def test_update_video(client, one_video): assert video.title == "Updated Video Title" assert video.total_inventory == 2 + def test_update_video_not_found(client): # Act - response = client.put("/videos/1", json={ - "title": "Updated Video Title", - "total_inventory": 2, - "release_date": "01-01-2021" - }) + response = client.put( + "/videos/1", + json={ + "title": "Updated Video Title", + "total_inventory": 2, + "release_date": "01-01-2021", + }, + ) response_body = response.get_json() # Assert assert response.status_code == 404 assert response_body == {"message": "Video 1 was not found"} + def test_update_video_invalid_data(client, one_video): # Act - response = client.put("/videos/1", json={ - "total_inventory": 2, - "release_date": "01-01-2021" - }) + response = client.put( + "/videos/1", json={"total_inventory": 2, "release_date": "01-01-2021"} + ) # Assert assert response.status_code == 400 @@ -209,6 +227,7 @@ def test_get_customers_no_saved_customers(client): assert response.status_code == 200 assert response_body == [] + def test_get_customers_one_saved_customer(client, one_customer): # Act response = client.get("/customers") @@ -222,6 +241,7 @@ def test_get_customers_one_saved_customer(client, one_customer): assert response_body[0]["phone"] == CUSTOMER_PHONE assert response_body[0]["postal_code"] == CUSTOMER_POSTAL_CODE + def test_get_customer(client, one_customer): # Act response = client.get("/customers/1") @@ -234,6 +254,7 @@ def test_get_customer(client, one_customer): assert response_body["phone"] == CUSTOMER_PHONE assert response_body["postal_code"] == CUSTOMER_POSTAL_CODE + def test_get_customer_not_found(client): # Act response = client.get("/customers/1") @@ -243,6 +264,7 @@ def test_get_customer_not_found(client): assert response.status_code == 404 assert response_body == {"message": "Customer 1 was not found"} + def test_get_invalid_customer_id(client, one_customer): # Act response = client.get("/customers/hello") @@ -250,14 +272,18 @@ def test_get_invalid_customer_id(client, one_customer): # Assert assert response.status_code == 400 + # CREATE def test_create_customer(client): # Act - response = client.post("/customers", json={ - "name": CUSTOMER_NAME, - "phone": CUSTOMER_PHONE, - "postal_code": CUSTOMER_POSTAL_CODE - }) + response = client.post( + "/customers", + json={ + "name": CUSTOMER_NAME, + "phone": CUSTOMER_PHONE, + "postal_code": CUSTOMER_POSTAL_CODE, + }, + ) response_body = response.get_json() @@ -272,12 +298,16 @@ def test_create_customer(client): assert new_customer.postal_code == CUSTOMER_POSTAL_CODE assert new_customer.phone == CUSTOMER_PHONE + def test_create_customer_must_contain_postal(client): # Act - response = client.post("/customers", json={ - "name": CUSTOMER_NAME, - "phone": CUSTOMER_PHONE, - }) + response = client.post( + "/customers", + json={ + "name": CUSTOMER_NAME, + "phone": CUSTOMER_PHONE, + }, + ) response_body = response.get_json() # Assert @@ -286,12 +316,13 @@ def test_create_customer_must_contain_postal(client): assert response.status_code == 400 assert Customer.query.all() == [] + def test_create_customer_must_contain_name(client): # Act - response = client.post("/customers", json={ - "phone": CUSTOMER_PHONE, - "postal_code": CUSTOMER_POSTAL_CODE - }) + response = client.post( + "/customers", + json={"phone": CUSTOMER_PHONE, "postal_code": CUSTOMER_POSTAL_CODE}, + ) response_body = response.get_json() # Assert @@ -300,12 +331,12 @@ def test_create_customer_must_contain_name(client): assert response.status_code == 400 assert Customer.query.all() == [] + def test_create_customer_must_contain_phone(client): # Act - response = client.post("/customers", json={ - "name": CUSTOMER_NAME, - "postal_code": CUSTOMER_POSTAL_CODE - }) + response = client.post( + "/customers", json={"name": CUSTOMER_NAME, "postal_code": CUSTOMER_POSTAL_CODE} + ) response_body = response.get_json() assert "details" in response_body @@ -313,6 +344,7 @@ def test_create_customer_must_contain_phone(client): assert response.status_code == 400 assert Customer.query.all() == [] + # DELETE def test_delete_customer(client, one_customer): # Act @@ -324,6 +356,7 @@ def test_delete_customer(client, one_customer): assert response.status_code == 200 assert Customer.query.get(1) == None + def test_delete_customer_not_found(client): # Act response = client.delete("/customers/1") @@ -334,13 +367,17 @@ def test_delete_customer_not_found(client): assert response.status_code == 404 assert Customer.query.all() == [] + def test_update_customer(client, one_customer): # Act - response = client.put("/customers/1", json={ - "name": f"Updated ${CUSTOMER_NAME}", - "phone": f"Updated ${CUSTOMER_PHONE}", - "postal_code": f"Updated ${CUSTOMER_POSTAL_CODE}" - }) + response = client.put( + "/customers/1", + json={ + "name": f"Updated ${CUSTOMER_NAME}", + "phone": f"Updated ${CUSTOMER_PHONE}", + "postal_code": f"Updated ${CUSTOMER_POSTAL_CODE}", + }, + ) response_body = response.get_json() # Assert @@ -353,33 +390,34 @@ def test_update_customer(client, one_customer): assert customer.name == f"Updated ${CUSTOMER_NAME}" assert customer.phone == f"Updated ${CUSTOMER_PHONE}" assert customer.postal_code == f"Updated ${CUSTOMER_POSTAL_CODE}" - + def test_update_customer_not_found(client): # Act - response = client.put("/customers/1", json={ - "name": f"Updated ${CUSTOMER_NAME}", - "phone": f"Updated ${CUSTOMER_PHONE}", - "postal_code": f"Updated ${CUSTOMER_POSTAL_CODE}" - }) + response = client.put( + "/customers/1", + json={ + "name": f"Updated ${CUSTOMER_NAME}", + "phone": f"Updated ${CUSTOMER_PHONE}", + "postal_code": f"Updated ${CUSTOMER_POSTAL_CODE}", + }, + ) response_body = response.get_json() # Assert assert response.status_code == 404 assert response_body == {"message": "Customer 1 was not found"} + def test_update_customer_invalid_data(client, one_customer): # Act - response = client.put("/customers/1", json={ - "phone": f"Updated ${CUSTOMER_PHONE}", - "postal_code": f"Updated ${CUSTOMER_POSTAL_CODE}" - }) + response = client.put( + "/customers/1", + json={ + "phone": f"Updated ${CUSTOMER_PHONE}", + "postal_code": f"Updated ${CUSTOMER_POSTAL_CODE}", + }, + ) # Assert assert response.status_code == 400 - - - - - - diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index b9f65b208..bfb1051c6 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -11,72 +11,69 @@ CUSTOMER_POSTAL_CODE = "12345" CUSTOMER_PHONE = "123-123-1234" + def test_checkout_video(client, one_video, one_customer): - response = client.post("/rentals/check-out", json={ - "customer_id": 1, - "video_id": 1 - }) + response = client.post("/rentals/check-out", json={"customer_id": 1, "video_id": 1}) response_body = response.get_json() - assert response.status_code == 200 assert response_body["video_id"] == 1 assert response_body["customer_id"] == 1 assert response_body["videos_checked_out_count"] == 1 assert response_body["available_inventory"] == 0 + def test_checkout_video_not_found(client, one_video, one_customer): - response = client.post("/rentals/check-out", json={ - "customer_id": 1, - "video_id": 2 - }) + response = client.post("/rentals/check-out", json={"customer_id": 1, "video_id": 2}) assert response.status_code == 404 + def test_checkout_customer_video_not_found(client, one_video, one_customer): - response = client.post("/rentals/check-out", json={ - "customer_id": 2, - "video_id": 1 - }) + response = client.post("/rentals/check-out", json={"customer_id": 2, "video_id": 1}) assert response.status_code == 404 + def test_checkout_video_no_video_id(client, one_video, one_customer): - response = client.post("/rentals/check-out", json={ - "customer_id": 1, - }) + response = client.post( + "/rentals/check-out", + json={ + "customer_id": 1, + }, + ) assert response.status_code == 400 + def test_checkout_video_no_customer_id(client, one_video, one_customer): - response = client.post("/rentals/check-out", json={ - "video_id": 1, - }) + response = client.post( + "/rentals/check-out", + json={ + "video_id": 1, + }, + ) assert response.status_code == 400 + def test_checkout_video_no_inventory(client, one_checked_out_video): - response = client.post("/rentals/check-out", json={ - "customer_id": 1, - "video_id": 1 - }) + response = client.post("/rentals/check-out", json={"customer_id": 1, "video_id": 1}) response_body = response.get_json() assert response.status_code == 400 assert response_body["message"] == "Could not perform checkout" + def test_checkin_video(client, one_checked_out_video): - response = client.post("/rentals/check-in", json={ - "customer_id": 1, - "video_id": 1 - }) + response = client.post("/rentals/check-in", json={"customer_id": 1, "video_id": 1}) response_body = response.get_json() @@ -86,48 +83,42 @@ def test_checkin_video(client, one_checked_out_video): assert response_body["videos_checked_out_count"] == 0 assert response_body["available_inventory"] == 1 + def test_checkin_video_no_customer_id(client, one_checked_out_video): - response = client.post("/rentals/check-in", json={ - "video_id": 1 - }) + response = client.post("/rentals/check-in", json={"video_id": 1}) assert response.status_code == 400 + def test_checkin_video_no_video_id(client, one_checked_out_video): - response = client.post("/rentals/check-in", json={ - "customer_id": 1 - }) + response = client.post("/rentals/check-in", json={"customer_id": 1}) assert response.status_code == 400 + def test_checkin_video_not_found(client, one_checked_out_video): - response = client.post("/rentals/check-in", json={ - "customer_id": 2, - "video_id": 1 - }) + response = client.post("/rentals/check-in", json={"customer_id": 2, "video_id": 1}) assert response.status_code == 404 + def test_checkin_customer_not_found(client, one_checked_out_video): - response = client.post("/rentals/check-in", json={ - "customer_id": 1, - "video_id": 2 - }) + response = client.post("/rentals/check-in", json={"customer_id": 1, "video_id": 2}) assert response.status_code == 404 + def test_checkin_video_not_checked_out(client, one_video, one_customer): - response = client.post("/rentals/check-in", json={ - "customer_id": 1, - "video_id": 1 - }) + response = client.post("/rentals/check-in", json={"customer_id": 1, "video_id": 1}) response_body = response.get_json() assert response.status_code == 400 - assert response_body == {"message": "No outstanding rentals for customer 1 and video 1"} - + assert response_body == { + "message": "No outstanding rentals for customer 1 and video 1" + } + def test_rentals_by_video(client, one_checked_out_video): response = client.get("/videos/1/rentals") @@ -138,6 +129,7 @@ def test_rentals_by_video(client, one_checked_out_video): len(response_body) == 1 response_body[0]["name"] == CUSTOMER_NAME + def test_rentals_by_video_not_found(client): response = client.get("/videos/1/rentals") @@ -146,6 +138,7 @@ def test_rentals_by_video_not_found(client): assert response.status_code == 404 assert response_body["message"] == "Video 1 was not found" + def test_rentals_by_video_no_rentals(client, one_video): response = client.get("/videos/1/rentals") @@ -154,6 +147,7 @@ def test_rentals_by_video_no_rentals(client, one_video): assert response.status_code == 200 assert response_body == [] + def test_rentals_by_customer(client, one_checked_out_video): response = client.get("/customers/1/rentals") @@ -163,6 +157,7 @@ def test_rentals_by_customer(client, one_checked_out_video): len(response_body) == 1 response_body[0]["title"] == VIDEO_TITLE + def test_rentals_by_customer_not_found(client): response = client.get("/customers/1/rentals") @@ -171,6 +166,7 @@ def test_rentals_by_customer_not_found(client): assert response.status_code == 404 assert response_body["message"] == "Customer 1 was not found" + def test_rentals_by_customer_no_rentals(client, one_customer): response = client.get("/customers/1/rentals") @@ -179,18 +175,18 @@ def test_rentals_by_customer_no_rentals(client, one_customer): assert response.status_code == 200 assert response_body == [] + def test_can_delete_customer_with_rental(client, one_checked_out_video): # Act response = client.delete("/customers/1") - #Assert + # Assert assert response.status_code == 200 + def test_can_delete_video_with_rental(client, one_checked_out_video): # Act response = client.delete("/videos/1") - #Assert + # Assert assert response.status_code == 200 - -