diff --git a/ada-project-docs/wave_03.md b/ada-project-docs/wave_03.md index 5873f12c4..c381a4b53 100644 --- a/ada-project-docs/wave_03.md +++ b/ada-project-docs/wave_03.md @@ -25,7 +25,6 @@ Things to note: - Customers can be sorted by `name`, `registered_at` and `postal_code` - Videos can be sorted by `title` and `release_date` - If the client requests both sorting and pagination, pagination should be relative to the sorted order -- Check out the [paginate method](https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.BaseQuery.paginate) - The paginate method reteurns a [Pagination object](https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#flask_sqlalchemy.Pagination) - To access records from a Pagination object, consider using the `items` attribute - See [this article from DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-query-tables-and-paginate-data-in-flask-sqlalchemy) for a more detailed look at paginating data using SQLAlchemy diff --git a/app/__init__.py b/app/__init__.py index 4ab3975b8..fe8b90e5e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -31,6 +31,16 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - #Register Blueprints Here + #Register Blueprints Here + from app.routes.video_routes import videos_bp + app.register_blueprint(videos_bp) + + from app.routes.customer_routes import customers_bp + app.register_blueprint(customers_bp) + + from app.routes.rental_routes import rentals_bp + app.register_blueprint(rentals_bp) + + return app \ No newline at end of file diff --git a/app/models/customer.py b/app/models/customer.py index 54d10b49a..5bfdfc939 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -1,4 +1,31 @@ from app import db +import datetime class Customer(db.Model): - id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + postal_code = db.Column(db.String) + phone = db.Column(db.String) + registered_at = db.Column(db.DateTime, default=datetime.datetime.now()) + videos_checked_out_count = db.Column(db.Integer, default=0) + videos = db.relationship("Video", secondary="rentals", back_populates="customers") + + def to_dict(self): + customer_dict = {} + customer_dict["id"] = self.id + customer_dict["name"] = self.name + customer_dict["registered_at"]: self.registered_at + customer_dict["postal_code"]=self.postal_code + customer_dict["phone"] = self.phone + + return customer_dict + + + @classmethod + def from_dict(cls,customer_data): + new_customer = Customer( + name=customer_data["name"], + postal_code=customer_data["postal_code"], + phone=customer_data["phone"], + ) + return new_customer \ No newline at end of file diff --git a/app/models/rental.py b/app/models/rental.py index 11009e593..2f585c8bb 100644 --- a/app/models/rental.py +++ b/app/models/rental.py @@ -1,4 +1,40 @@ from app import db +import datetime +import enum +from sqlalchemy import Enum + class Rental(db.Model): - id = db.Column(db.Integer, primary_key=True) \ No newline at end of file + + class RentalStatus(enum.Enum): + CHECKIN="checked_in" + CHECKOUT="checked_out" + + + __tablename__ = "rentals" + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + video_id = db.Column(db.Integer, db.ForeignKey('video.id'), primary_key=True,nullable=False) + customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), primary_key=True,nullable=False) + status = db.Column(db.Enum(RentalStatus), default=RentalStatus.CHECKOUT) + checkout_date = db.Column(db.DateTime, default=datetime.datetime.now()) + due_date = db.Column(db.DateTime, default=(datetime.date.today()+datetime.timedelta(days=7))) + + def to_dict(self): + rental_dict = {} + rental_dict["id"] = self.id + rental_dict["customer_id"] = self.customer_id + rental_dict["video_id"] = self.video_id + rental_dict["checkout_date"] = self.checkout_date + rental_dict["status"] = self.status + rental_dict["due_date"] = self.due_date + + return rental_dict + + @classmethod + def from_dict(cls, rental_data): + new_rental = Rental( + customer_id=rental_data["customer_id"], + video_id=rental_data["video_id"] + ) + + return new_rental diff --git a/app/models/video.py b/app/models/video.py index db3bf3aeb..9122720cf 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -1,4 +1,28 @@ from app import db class Video(db.Model): - id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title=db.Column(db.String) + release_date = db.Column(db.Date) + total_inventory = db.Column(db.Integer) + customers = db.relationship("Customer", secondary="rentals", back_populates="videos") + + + def to_dict(self): + video_dict = {} + video_dict["id"] = self.id + video_dict["title"] = self.title + video_dict["release_date"] = self.release_date + video_dict["total_inventory"] = self.total_inventory + + return video_dict + + @classmethod + def from_dict(cls, video_data): + new_video = Video( + title=video_data["title"], + release_date=video_data["release_date"], + total_inventory=video_data["total_inventory"] + ) + + return new_video \ No newline at end of file diff --git a/app/routes.py b/app/routes.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/app/routes/customer_routes.py b/app/routes/customer_routes.py new file mode 100644 index 000000000..b47813f3d --- /dev/null +++ b/app/routes/customer_routes.py @@ -0,0 +1,95 @@ +from app import db +from app.models.customer import Customer +from app.models.video import Video +from app.models.rental import Rental +from app.routes.rental_routes import query_rentals +from flask import Blueprint, jsonify, abort, make_response, request +from app.routes.helper_functions import validate_model, custom_query + +customers_bp = Blueprint("customers_bp", __name__, url_prefix="/customers") + +@customers_bp.route("", methods=["POST"]) +def create_customer(): + request_body = request.get_json() + try: + + new_customer = Customer.from_dict(request_body) + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + + db.session.add(new_customer) + db.session.commit() + return make_response(new_customer.to_dict(), 201) + +#queries customers appends dictionaries, jysonifys list. + +@customers_bp.route('', methods=["GET"]) +def get_all_customer(): + customers=custom_query(Customer,['id','name','registered_at','postal_code']) + customer_response = [] + for customer in customers: + customer_response.append(customer.to_dict()) + return jsonify(customer_response) + +#get customer by id +@customers_bp.route("/", methods=["GET"]) +def get_one_customer(customer_id): + customer = validate_model(Customer, customer_id) + return customer.to_dict() + +#route to delete +@customers_bp.route("/", methods=["DELETE"]) +def delete_customer(customer_id): + customer = validate_model(Customer, customer_id) + + db.session.delete(customer) + db.session.commit() + + return make_response(jsonify(customer.to_dict()), 200) + +#update route +@customers_bp.route("/", methods=["PUT"]) +def update_customer(customer_id): + customer=validate_model(Customer, customer_id) + + request_body = request.get_json() + try: + + customer.name=request_body["name"] + customer.phone=request_body["phone"] + customer.postal_code=request_body["postal_code"] + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + + db.session.add(customer) + db.session.commit() + + return make_response(customer.to_dict(), 200) + +@customers_bp.route("//rentals", methods=["GET"]) +def get_rentals_by_customer(customer_id): + customer = validate_model(Customer, customer_id) + query = custom_query(Rental,['id','title','release_date'],{"customer_id":customer.id, "status": Rental.RentalStatus.CHECKOUT}) + + response=[] + for rental in query: + video = validate_model(Video, rental.video_id) + rental_info = video.to_dict() + rental_info["due_date"] = rental.due_date + response.append(rental_info) + return jsonify(response) + +@customers_bp.route("//history", methods=["GET"]) +def get_video_had_been_checked_out(customer_id): + customer = validate_model(Customer, customer_id) + videos = custom_query(Rental,['id','title','release_date'],{"customer_id":customer.id, "status": Rental.RentalStatus.CHECKIN}) + response = [] + rental_info = {} + for rental in videos: + video = validate_model(Video, rental.video_id) + rental_info["title"] = video.title + rental_info["checkout_date"] = rental.checkout_date + rental_info["due_date"] = rental.due_date + response.append(rental_info) + return jsonify(response) + diff --git a/app/routes/helper_functions.py b/app/routes/helper_functions.py new file mode 100644 index 000000000..b482973a3 --- /dev/null +++ b/app/routes/helper_functions.py @@ -0,0 +1,63 @@ +from flask import Blueprint, jsonify, abort, make_response, request +from app.models.rental import Rental +from app.models.customer import Customer +from app.models.video import Video + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} was not found"}, 404)) + + return model + +def custom_query(cls, approvedsortinig, filters={}): + #list of accepted sort paramas + valid_sort=(approvedsortinig) + custom_querys=None + + #getting sort and pagnation args, with defults and types + sort=request.args.get('sort', 'id') + page = None + count=None + + if request.args.get('page_num'): + page=request.args.get('page_num', 1, type=int) + else: page=1 + + if request.args.get("count"): + count=request.args.get("count", 100, type=int) + else: count=100 + + #making id if not valid. + if sort not in valid_sort: sort= 'id' + #checking to see if class is the orderby attricute + order_cls=cls + + if cls is Rental: + join_class=None + if filters.get("customer_id"): + join_class=Video + else: + join_class=Customer + + if not hasattr(cls,sort): + find_att=[Customer,Video,Rental] + for object in find_att: + if hasattr(object,sort): + order_cls=object + break + + custom_querys=cls.query.filter_by(**filters).join(join_class).order_by( + getattr(order_cls,sort)).paginate(page=page,per_page=count,error_out=False) + else: + custom_querys=cls.query.order_by(getattr( + order_cls,sort)).paginate(page,count,False) + + query=custom_querys.items + return query \ No newline at end of file diff --git a/app/routes/rental_routes.py b/app/routes/rental_routes.py new file mode 100644 index 000000000..7b5abb2de --- /dev/null +++ b/app/routes/rental_routes.py @@ -0,0 +1,92 @@ +from app import db +from app.models.rental import Rental +from app.models.video import Video +from app.models.customer import Customer +from flask import Blueprint, jsonify, abort, make_response, request + +rentals_bp = Blueprint("rentals_bp", __name__, url_prefix="/rentals") + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message":f"{cls.__name__} {model_id} invalid"}, 400)) + + model = cls.query.get(model_id) + + if not model: + abort(make_response({"message":f"{cls.__name__} {model_id} was not found"}, 404)) + + return model + +#helper query function: +def query_rentals(filters): + query_results = db.session.query(Rental).filter_by(**filters).all() + return query_results + +#extract results +def extract_query(query_results): + response = [] + for object in query_results: + response.append(object.to_dict()) + return response + +#calculate avail inventory +def availabl_inventory(video): + vids_out = query_rentals({"video_id":video.id, "status":Rental.RentalStatus.CHECKOUT}) + return video.total_inventory-len(vids_out) + +#response helper function +def rental_response(rental,customer,video): + rental_response={} + rental_response["video_id"]=video.id + rental_response["customer_id"]=customer.id + rental_response["videos_checked_out_count"]=customer.videos_checked_out_count + rental_response["available_inventory"] = availabl_inventory(video) #here we need to subtract all rentals associated with video + return rental_response + +#should make a query method that can take in video_id,customer_id and status + +@rentals_bp.route("/check-out", methods=["POST"]) +def video_checkout(): + request_body=request.get_json() + #put into rental model as to_dictionary + try: + customer = validate_model(Customer, request_body["customer_id"]) + video = validate_model(Video, request_body["video_id"]) + if availabl_inventory(video)==0: + abort(make_response({"message":"Could not perform checkout"}, 400)) + new_rental=Rental.from_dict(request_body) + customer.videos_checked_out_count +=1 + + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + + db.session.add_all([new_rental, customer]) + + db.session.commit() + + return make_response(rental_response(new_rental,customer,video), 200) + +@rentals_bp.route("/check-in", methods=["POST"]) +def checkin_video(): + request_body = request.get_json() + + try: + customer = validate_model(Customer, request_body["customer_id"]) + video = validate_model(Video, request_body["video_id"]) + rental_query = query_rentals({"video_id": video.id, "customer_id":customer.id, "status": Rental.RentalStatus.CHECKOUT}) + if not rental_query: + abort(make_response({"message":"No outstanding rentals for customer 1 and video 1"}, 400)) + rental=rental_query[0] + rental.status=Rental.RentalStatus.CHECKIN + customer.videos_checked_out_count -=1 + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + + db.session.add_all([rental, customer]) + + db.session.commit() + + return make_response(rental_response(rental,customer,video), 200) + diff --git a/app/routes/video_routes.py b/app/routes/video_routes.py new file mode 100644 index 000000000..c8a09a463 --- /dev/null +++ b/app/routes/video_routes.py @@ -0,0 +1,88 @@ +from app import db +from app.models.video import Video +from app.models.rental import Rental +from app.models.customer import Customer +from app.routes.rental_routes import query_rentals +from flask import Blueprint, jsonify, abort, make_response, request +from app.routes.helper_functions import validate_model, custom_query + +videos_bp = Blueprint("videos_bp", __name__, url_prefix="/videos") + +@videos_bp.route("", methods=["GET"]) +def get_all_video(): + videos = custom_query(Video, ['id','title','release_date']) + videos_response = [] + for video in videos: + videos_response.append(video.to_dict()) + return jsonify(videos_response) + +@videos_bp.route("/", methods=["GET"]) +def get_one_video_by_id(video_id): + video = validate_model(Video, video_id) + return video.to_dict() + +@videos_bp.route("", methods=["POST"]) +def create_a_video(): + request_body = request.get_json() + try: + new_video = Video.from_dict(request_body) + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + db.session.add(new_video) + db.session.commit() + + return make_response(new_video.to_dict(), 201) + +@videos_bp.route("/", methods=["PUT"]) +def update_a_video(video_id): + video = validate_model(Video, video_id) + request_body = request.get_json() + try: + video.title = request_body["title"] + video.release_date = request_body["release_date"] + video.total_inventory = request_body["total_inventory"] + except KeyError as key_error: + abort(make_response({"details":f"Request body must include {key_error.args[0]}."}, 400)) + + db.session.add(video) + db.session.commit() + + return make_response(video.to_dict(), 200) + +@videos_bp.route("/", methods=["DELETE"]) +def delete_a_video(video_id): + video = validate_model(Video, video_id) + + db.session.delete(video) + db.session.commit() + + return make_response(jsonify(video.to_dict()), 200) + +@videos_bp.route("//rentals", methods=["GET"]) +def get_rentals_by_video(video_id): + video = validate_model(Video, video_id) + query = custom_query(Rental,['id','name','postal_code'],{"video_id":video.id, "status": Rental.RentalStatus.CHECKOUT}) + + response = [] + for rental in query: + customer = validate_model(Customer, rental.customer_id) + rental_info = customer.to_dict() + rental_info["due_date"] = rental.due_date + response.append(rental_info) + return jsonify(response) + + +@videos_bp.route("//history", methods=["GET"]) +def get_customer_had_been_checked_out_video(video_id): + video = validate_model(Video, video_id) + query = custom_query(Rental,['id','name','postal_code'],{"video_id":video.id, "status": Rental.RentalStatus.CHECKIN}) + + response = [] + for rental in query: + customer = validate_model(Customer, rental.customer_id) + rental_info = customer.to_dict() + rental_info["checkout_date"] = rental.checkout_date + rental_info["due_date"] = rental.due_date + response.append(rental_info) + return jsonify(response) + 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..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +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/7860939254e9_.py b/migrations/versions/7860939254e9_.py new file mode 100644 index 000000000..7f5e8cfab --- /dev/null +++ b/migrations/versions/7860939254e9_.py @@ -0,0 +1,49 @@ +"""empty message + +Revision ID: 7860939254e9 +Revises: +Create Date: 2023-01-03 17:47:24.091085 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7860939254e9' +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(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('postal_code', sa.String(), nullable=True), + sa.Column('phone_number', sa.String(), nullable=True), + sa.Column('register_at', sa.DateTime(), nullable=True), + sa.Column('videos_checked_out_count', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('rental', + sa.Column('id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('video', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('release_date', sa.Date(), nullable=True), + sa.Column('total_inventory', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('video') + op.drop_table('rental') + op.drop_table('customer') + # ### end Alembic commands ### diff --git a/migrations/versions/d54be5047f73_.py b/migrations/versions/d54be5047f73_.py new file mode 100644 index 000000000..cbb5a86bb --- /dev/null +++ b/migrations/versions/d54be5047f73_.py @@ -0,0 +1,51 @@ +"""empty message + +Revision ID: d54be5047f73 +Revises: 7860939254e9 +Create Date: 2023-01-04 18:02:03.656443 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = 'd54be5047f73' +down_revision = '7860939254e9' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('rentals', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('video_id', sa.Integer(), nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=False), + sa.Column('status', sa.Enum('IN', 'OUT', name='rentalstatus'), nullable=True), + sa.Column('checkout_date', sa.DateTime(), nullable=True), + sa.Column('due_date', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['customer_id'], ['customer.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['video.id'], ), + sa.PrimaryKeyConstraint('id', 'video_id', 'customer_id') + ) + op.drop_table('rental') + op.add_column('customer', sa.Column('phone', sa.String(), nullable=True)) + op.add_column('customer', sa.Column('registered_at', sa.DateTime(), nullable=True)) + op.drop_column('customer', 'register_at') + op.drop_column('customer', 'phone_number') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('customer', sa.Column('phone_number', sa.VARCHAR(), autoincrement=False, nullable=True)) + op.add_column('customer', sa.Column('register_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True)) + op.drop_column('customer', 'registered_at') + op.drop_column('customer', 'phone') + op.create_table('rental', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('id', name='rental_pkey') + ) + op.drop_table('rentals') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index 89e00b497..971fcb7d7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,6 +8,7 @@ click==7.1.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 iniconfig==1.1.1 itsdangerous==1.1.0 @@ -28,5 +29,6 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 +tomli==2.0.1 urllib3==1.26.5 Werkzeug==1.0.1 diff --git a/tests/conftest.py b/tests/conftest.py index 1b985181c..a3f43ee9f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -138,24 +138,22 @@ def one_returned_video(app, client, one_customer, second_video): }) @pytest.fixture -def customer_one_video_three(app, client, one_customer, three_copies_video): +def customer_one_video_three(app, client, one_customer, five_copies_video): response = client.post("/rentals/check-out", json={ "customer_id": 1, "video_id": 1 }) @pytest.fixture -def customer_two_video_three(app, client, second_customer, three_copies_video): +def customer_two_video_three(app, client, second_customer, five_copies_video): response = client.post("/rentals/check-out", json={ "customer_id": 2, "video_id": 1 }) @pytest.fixture -def customer_three_video_three(app, client, third_customer, three_copies_video): +def customer_three_video_three(app, client, third_customer, five_copies_video): response = client.post("/rentals/check-out", json={ "customer_id": 3, "video_id": 1 - }) - - + }) \ No newline at end of file diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index e26ec450c..e5b99174d 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -1,5 +1,6 @@ from app.models.video import Video from app.models.customer import Customer +import pytest VIDEO_1_TITLE = "A Brand New Video" VIDEO_1_ID = 1 @@ -107,7 +108,7 @@ def test_get_customers_sorted_by_postal_code(client, one_customer, second_custom assert response_body[2]["phone"] == CUSTOMER_2_PHONE assert response_body[2]["postal_code"] == CUSTOMER_2_POSTAL_CODE -def test_paginate_per_page_greater_than_num_customers(client, one_customer): +def test_paginate_count_greater_than_num_customers(client, one_customer): # Arrange data = {"count": 5, "page_num": 1} @@ -333,7 +334,7 @@ def test_get_rentals_sorted_by_title(client, one_checked_out_video, second_check def test_get_paginate_n_greater_than_rentals(client, one_checked_out_video): # Arrange - data = {"per_page": 5, "page": 1} + data = {"count": 5,"page_num": 1} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -349,7 +350,7 @@ def test_get_paginate_n_greater_than_rentals(client, one_checked_out_video): def test_get_second_page_of_rentals(client, one_checked_out_video, second_checked_out_video): # Arrange - data = {"per_page": 1, "page": 2} + data = {"count": 1, "page_num": 2} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -365,7 +366,7 @@ def test_get_second_page_of_rentals(client, one_checked_out_video, second_checke def test_get_first_page_of_rentals_grouped_by_two(client, one_checked_out_video, second_checked_out_video, third_checked_out_video): # Arrange - data = {"per_page": 2, "page": 1} + data = {"count": 2, "page_num": 1} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -384,7 +385,7 @@ def test_get_first_page_of_rentals_grouped_by_two(client, one_checked_out_video, def test_get_second_page_of_rentals_grouped_by_two(client, one_checked_out_video, second_checked_out_video, third_checked_out_video): # Arrange - data = {"per_page": 2, "page": 2} + data = {"count": 2, "page_num": 2} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -399,7 +400,7 @@ def test_get_second_page_of_rentals_grouped_by_two(client, one_checked_out_video def test_get_rentals_no_page(client, one_checked_out_video, second_checked_out_video, third_checked_out_video): # Arrange - data = {"per_page": 2} + data = {"count": 2} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -418,7 +419,7 @@ def test_get_rentals_no_page(client, one_checked_out_video, second_checked_out_v def test_get_rentals_sorted_and_paginated(client, one_checked_out_video, second_checked_out_video, third_checked_out_video): # Arrange - data = {"per_page": 2, "sort": "title", "page": 2} + data = {"count": 2, "sort": "title", "page_num": 2} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -452,7 +453,7 @@ def test_get_rentals_invalid_sort_param(client, one_checked_out_video, second_ch def test_get_rentals_invalid_n_param(client, one_checked_out_video, second_checked_out_video): # Arrange - data = {"per_page": "invalid"} + data = {"count": "invalid"} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -471,7 +472,7 @@ def test_get_rentals_invalid_n_param(client, one_checked_out_video, second_check def test_get_rentals_invalid_p_param(client, one_checked_out_video, second_checked_out_video): # Arrange - data = {"page": "invalid"} + data = {"page_num": "invalid"} # Act response = client.get("/customers/1/rentals", query_string = data) @@ -566,9 +567,9 @@ def test_get_renters_sorted_by_postal_code(client, customer_one_video_three, cus assert response_body[2]["postal_code"] == CUSTOMER_2_POSTAL_CODE -def test_paginate_per_page_greater_than_num_renters(client, customer_one_video_three): +def test_paginate_count_greater_than_num_renters(client, customer_one_video_three): # Arrange - data = {"per_page": 5, "page": 1} + data = {"count": 5, "page_num": 1} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -585,7 +586,7 @@ def test_paginate_per_page_greater_than_num_renters(client, customer_one_video_t def test_get_second_page_of_renters(client, customer_one_video_three, customer_two_video_three): # Arrange - data = {"per_page": 1, "page": 2} + data = {"count": 1, "page_num": 2} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -602,7 +603,7 @@ def test_get_second_page_of_renters(client, customer_one_video_three, customer_t def test_get_first_page_of_renters_grouped_by_two(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): # Arrange - data = {"per_page": 2, "page": 1} + data = {"count": 2, "page_num": 1} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -623,7 +624,7 @@ def test_get_first_page_of_renters_grouped_by_two(client, customer_one_video_thr def test_get_second_page_of_renters_grouped_by_two(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): # Arrange - data = {"per_page": 2, "page": 2} + data = {"count": 2, "page_num": 2} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -638,9 +639,9 @@ def test_get_second_page_of_renters_grouped_by_two(client, customer_one_video_th assert response_body[0]["postal_code"] == CUSTOMER_3_POSTAL_CODE -def test_get_customers_no_page(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): +def test_get_renters_no_page(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): # Arrange - data = {"per_page": 2} + data = {"count": 2} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -661,7 +662,7 @@ def test_get_customers_no_page(client, customer_one_video_three, customer_two_vi def test_get_renters_sorted_and_paginated(client, customer_one_video_three, customer_two_video_three, customer_three_video_three): # Arrange - data = {"per_page": 2, "sort": "name", "page": 1} + data = {"count": 2, "sort": "name", "page_num": 1} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -704,7 +705,7 @@ def test_get_renters_invalid_sort_param(client, customer_one_video_three, custom def test_get_renters_invalid_n_param(client, customer_one_video_three, customer_two_video_three): # Arrange - data = {"per_page": "invalid"} + data = {"count": "invalid"} # Act response = client.get("/videos/1/rentals", query_string = data) @@ -725,7 +726,7 @@ def test_get_renters_invalid_n_param(client, customer_one_video_three, customer_ def test_get_renters_invalid_p_param(client, customer_one_video_three, customer_two_video_three): # Arrange - data = {"page": "invalid"} + data = {"page_num": "invalid"} # Act response = client.get("/customers", query_string = data) @@ -746,33 +747,3 @@ def test_get_renters_invalid_p_param(client, customer_one_video_three, customer_ - -def test_get_customers_rental_history(client, one_checked_out_video, one_returned_video): - # Act - response = client.get("/customers/1/history") - response_body = response.get_json() - - #Assert - assert response.status_code == 200 - assert len(response_body) == 1 - assert response_body[0]["title"] == VIDEO_2_TITLE - -def test_get_customer_not_found_rental_history(client, one_checked_out_video, one_returned_video): - # Act - response = client.get("/customers/2/history") - response_body = response.get_json() - - #Assert - assert response.status_code == 404 - assert response_body == {"message": "Customer 2 was not found"} - - -def test_get_customer_no_rental_history(client, one_checked_out_video): - # Act - response = client.get("/customers/1/history") - response_body = response.get_json() - - #Assert - assert response.status_code == 200 - assert len(response_body) == 0 - assert response_body == [] \ No newline at end of file diff --git a/tests/test_wave_04.py b/tests/test_wave_04.py new file mode 100644 index 000000000..9b74666a6 --- /dev/null +++ b/tests/test_wave_04.py @@ -0,0 +1,51 @@ +VIDEO_2_TITLE = "Video Two" +VIDEO_2_ID = 2 +VIDEO_2_INVENTORY = 1 +VIDEO_2_RELEASE_DATE = "12-31-2000" + +CUSTOMER_1_NAME = "A Brand New Customer" +CUSTOMER_1_ID = 1 +CUSTOMER_1_POSTAL_CODE = "12345" +CUSTOMER_1_PHONE = "123-123-1234" + +#@pytest.mark.skip() +def test_get_customers_rental_history(client, one_checked_out_video, one_returned_video): + # Act + response = client.get("/customers/1/history") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert len(response_body) == 1 + assert response_body[0]["title"] == VIDEO_2_TITLE + +#@pytest.mark.skip() +def test_get_customer_not_found_rental_history(client, one_checked_out_video, one_returned_video): + # Act + response = client.get("/customers/2/history") + response_body = response.get_json() + + #Assert + assert response.status_code == 404 + assert response_body == {"message": "Customer 2 was not found"} + +#@pytest.mark.skip() +def test_get_customer_no_rental_history(client, one_checked_out_video): + # Act + response = client.get("/customers/1/history") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert len(response_body) == 0 + assert response_body == [] + +def test_get_videos_rental_history(client, one_checked_out_video, one_returned_video): + # Act + response = client.get("/videos/2/history") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert len(response_body) == 1 + assert response_body[0]["name"] == CUSTOMER_1_NAME \ No newline at end of file