From 86950605619592c55357396dcf0e1ec67307f4af Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Wed, 14 Dec 2022 11:57:47 -0700 Subject: [PATCH 01/23] wave_01 Planet Class created --- app/model/planet.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 app/model/planet.py diff --git a/app/model/planet.py b/app/model/planet.py new file mode 100644 index 000000000..e69de29bb From 5fa6a0f720a9a487edbbb0cfd70463645df4d8b8 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Wed, 14 Dec 2022 13:02:37 -0700 Subject: [PATCH 02/23] wave_01 completed --- app/__init__.py | 2 ++ app/model/planet.py | 11 +++++++++++ app/routes.py | 18 +++++++++++++++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..6596942bd 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,5 +3,7 @@ def create_app(test_config=None): app = Flask(__name__) + from .routes import planets_bp + app.register_blueprint(planets_bp) return app diff --git a/app/model/planet.py b/app/model/planet.py index e69de29bb..aea188f33 100644 --- a/app/model/planet.py +++ b/app/model/planet.py @@ -0,0 +1,11 @@ +class Planet: + def __init__(self, id, name, description, mass): + self.id = id + self.name = name + self.description = description + self.mass = mass + +planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), + Planet(2, "Mars", "dusty, cold desert",6.39e23), + Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) + ] \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..9d12d9e54 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,18 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +from .model.planet import planets + +planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") + +@planets_bp.route("",methods= ["GET"]) +def display_planets(): + response_planets = [] + for planet in planets: + response_planets.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "mass": planet.mass + }) + + return jsonify(response_planets) \ No newline at end of file From 3fb0a615c4fc448a422987eb932b848cba5f6fc4 Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 15 Dec 2022 10:47:20 -0800 Subject: [PATCH 03/23] Added single planet endpoint and handled invalid planet id type and nonexistent planet id --- app/routes.py | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index 9d12d9e54..63b705bc6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,4 @@ -from flask import Blueprint, jsonify +from flask import Blueprint, jsonify, abort, make_response from .model.planet import planets @@ -15,4 +15,35 @@ def display_planets(): "mass": planet.mass }) - return jsonify(response_planets) \ No newline at end of file + return jsonify(response_planets) + +# ~~~~~~ Handle planet id errors ~~~~~ +def validate_id(planet_id): + """ + - check for valid id type and if exists + - return planet object if valid planet id + """ + try: + planet_id_int = int(planet_id) + except: + # handling invalid planet id type + abort(make_response({"message": f"{planet_id} is an invalid planet id"}, 400)) + + # collect the planet data if valid id type + for planet in planets: + if planet.id == planet_id_int: + return planet + # handle nonexistant planet id + abort(make_response({"message": f"{planet_id} not found"}, 404)) + + +# ~~~~~~ Single planet endpoint ~~~~~~ +@planets_bp.route("/",methods= ["GET"]) +def display_planet(planet_id): + valid_planet = validate_id(planet_id) + return { + "id": valid_planet.id, + "name": valid_planet.name, + "description": valid_planet.description, + "mass": valid_planet.mass, + } From 978e24707e362b8b31a95e3189ce5d2a5a9f382e Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Tue, 20 Dec 2022 19:31:04 -0800 Subject: [PATCH 04/23] connected the app to a db. created GET /planets, GET /planets/ and POST /planets routes. refactored the planet_id validation function. --- app/__init__.py | 13 +++ app/model/planet.py | 11 --- app/models/__init__.py | 0 app/models/planet.py | 20 ++++ app/routes.py | 77 ++++++++++----- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../versions/f86f3dc07f4c_add_planet_model.py | 34 +++++++ 10 files changed, 285 insertions(+), 36 deletions(-) delete mode 100644 app/model/planet.py create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/f86f3dc07f4c_add_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index 6596942bd..e2d158696 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +1,21 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate +db = SQLAlchemy() +migrate = Migrate() def create_app(test_config=None): app = Flask(__name__) + + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system' + + from app.models.planet import Planet + + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) diff --git a/app/model/planet.py b/app/model/planet.py deleted file mode 100644 index aea188f33..000000000 --- a/app/model/planet.py +++ /dev/null @@ -1,11 +0,0 @@ -class Planet: - def __init__(self, id, name, description, mass): - self.id = id - self.name = name - self.description = description - self.mass = mass - -planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), - Planet(2, "Mars", "dusty, cold desert",6.39e23), - Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) - ] \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..1ef792171 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,20 @@ +# class Planet: +# def __init__(self, id, name, description, mass): +# self.id = id +# self.name = name +# self.description = description +# self.mass = mass + +# planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), +# Planet(2, "Mars", "dusty, cold desert",6.39e23), +# Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) +# ] + +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + description = db.Column(db.String) + mass = db.Column(db.String) + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 63b705bc6..c4e9bbc80 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,22 +1,10 @@ -from flask import Blueprint, jsonify, abort, make_response -from .model.planet import planets +from app import db +from flask import Blueprint, jsonify, abort, make_response, request +from .models.planet import Planet planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") -@planets_bp.route("",methods= ["GET"]) -def display_planets(): - response_planets = [] - for planet in planets: - response_planets.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "mass": planet.mass - }) - - return jsonify(response_planets) - # ~~~~~~ Handle planet id errors ~~~~~ def validate_id(planet_id): """ @@ -29,21 +17,60 @@ def validate_id(planet_id): # handling invalid planet id type abort(make_response({"message": f"{planet_id} is an invalid planet id"}, 400)) - # collect the planet data if valid id type - for planet in planets: - if planet.id == planet_id_int: - return planet + # return planet data if id in db + planet = Planet.query.get(planet_id) + # handle nonexistant planet id - abort(make_response({"message": f"{planet_id} not found"}, 404)) + if not planet: + abort(make_response({"message": f"{planet_id} not found"}, 404)) + + return planet + + + +@planets_bp.route("",methods= ["GET"]) +def display_all_planets(): + response_planets = [] + planets = Planet.query.all() + for planet in planets: + response_planets.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "mass": planet.mass + }) + + return jsonify(response_planets) # ~~~~~~ Single planet endpoint ~~~~~~ -@planets_bp.route("/",methods= ["GET"]) +@planets_bp.route("/",methods=["GET"]) def display_planet(planet_id): valid_planet = validate_id(planet_id) return { - "id": valid_planet.id, - "name": valid_planet.name, - "description": valid_planet.description, - "mass": valid_planet.mass, + "id": valid_planet.id, + "name": valid_planet.name, + "description": valid_planet.description, + "mass": valid_planet.mass, } + + +@planets_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + + if "name" not in request_body or "description" not in request_body \ + or "mass" not in request_body: + abort(make_response({"message" : \ + "Failed to create a planet because the name and/or description \ + and/or mass are missing"}, 400)) + + new_planet = Planet( + name=request_body["name"], + description=request_body["description"], + mass=request_body["mass"]) + + db.session.add(new_planet) + db.session.commit() + + return make_response({"message":"planet has been created successfully"}, 200) \ No newline at end of file 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/f86f3dc07f4c_add_planet_model.py b/migrations/versions/f86f3dc07f4c_add_planet_model.py new file mode 100644 index 000000000..13d735b23 --- /dev/null +++ b/migrations/versions/f86f3dc07f4c_add_planet_model.py @@ -0,0 +1,34 @@ +"""add Planet model + +Revision ID: f86f3dc07f4c +Revises: +Create Date: 2022-12-20 11:18:49.218372 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f86f3dc07f4c' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('mass', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('planet') + # ### end Alembic commands ### From 578b1822a59e71911c848347942dc1378be3c868 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 11:09:41 -0800 Subject: [PATCH 05/23] Added update_planet functionality for /planets/ endpoint --- app/routes.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index c4e9bbc80..b7f1173df 100644 --- a/app/routes.py +++ b/app/routes.py @@ -6,6 +6,7 @@ planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") # ~~~~~~ Handle planet id errors ~~~~~ +# FUTURE IDEAS: Create separate helper function module or add as class method def validate_id(planet_id): """ - check for valid id type and if exists @@ -73,4 +74,17 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return make_response({"message":"planet has been created successfully"}, 200) \ No newline at end of file + return make_response({"message":"planet has been created successfully"}, 201) + +@planets_bp.route("/", methods=["PUT"]) +def update_planet(planet_id): + request_body = request.get_json() + planet = validate_id(planet_id) + planet.name = request_body["name"] if "name" in request_body else planet.name + planet.description = request_body["description"] if "description" in request_body else planet.description + planet.mass = request_body["mass"] if "mass" in request_body else planet.mass + db.session.commit() + return make_response( + {"message": f"planet #{planet_id} Updated Successfully"}, 200 + ) + From 33981b512941860cc6ba3167a59d2bd31d354722 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 11:43:23 -0800 Subject: [PATCH 06/23] Added delete_planet functionality for /planets/ endpoint --- app/routes.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/app/routes.py b/app/routes.py index b7f1173df..6b749b4bf 100644 --- a/app/routes.py +++ b/app/routes.py @@ -88,3 +88,11 @@ def update_planet(planet_id): {"message": f"planet #{planet_id} Updated Successfully"}, 200 ) +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_id(planet_id) + db.session.delete(planet) + db.session.commit() + return make_response( + {"message": f"planet #{planet_id} has been deleted successfully"}, 200 + ) From bfd24a2e47295421f1c0e42ec280114a0d1cb2e8 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 12:02:54 -0800 Subject: [PATCH 07/23] Refactored parts of update_planet() commented, issue with getting it to commit update to db --- app/routes.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/routes.py b/app/routes.py index 6b749b4bf..8c4b2c4d2 100644 --- a/app/routes.py +++ b/app/routes.py @@ -80,6 +80,9 @@ def create_planet(): def update_planet(planet_id): request_body = request.get_json() planet = validate_id(planet_id) + # ~~~ REFACTOR ISSUE ~~~ This line runs but a problem with updating the db + # for attr in request_body: + # planet.attr = request_body[attr] planet.name = request_body["name"] if "name" in request_body else planet.name planet.description = request_body["description"] if "description" in request_body else planet.description planet.mass = request_body["mass"] if "mass" in request_body else planet.mass From 80f74a3017ce001db47a43dbfc1fa5ebc5cf7df4 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 14:52:27 -0800 Subject: [PATCH 08/23] Updated model - plural table name and float dtype for mass attribute --- app/models/planet.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 1ef792171..7cfccb58b 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,10 +1,3 @@ -# class Planet: -# def __init__(self, id, name, description, mass): -# self.id = id -# self.name = name -# self.description = description -# self.mass = mass - # planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), # Planet(2, "Mars", "dusty, cold desert",6.39e23), # Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) @@ -16,5 +9,5 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String) description = db.Column(db.String) - mass = db.Column(db.String) - \ No newline at end of file + mass = db.Column(db.Float) + __tablename__ = "planets" From 74f7424a6ea9a4d8a33211454be8c244535b7780 Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 21 Dec 2022 14:53:01 -0800 Subject: [PATCH 09/23] New migration for model updated with plural table name and float dtype for mass --- ...hanged_mass_to_string_datatype_to_float.py | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py diff --git a/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py b/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py new file mode 100644 index 000000000..b3e1bb15b --- /dev/null +++ b/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py @@ -0,0 +1,42 @@ +"""changed mass to string datatype to Float + +Revision ID: 7fa857cd0ba2 +Revises: f86f3dc07f4c +Create Date: 2022-12-21 14:37:43.515533 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7fa857cd0ba2' +down_revision = 'f86f3dc07f4c' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planets', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('mass', sa.Float(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.drop_table('planet') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('planet', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('mass', sa.INTEGER(), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('id', name='planet_pkey') + ) + op.drop_table('planets') + # ### end Alembic commands ### From b91ca43c2e93203a2ac47371077dcee6d3a8c737 Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Wed, 21 Dec 2022 17:46:47 -0800 Subject: [PATCH 10/23] changed migrate instance to allow detecting changes in data types. created a migration file for changing the mass datatype to string --- app/__init__.py | 4 +-- app/models/planet.py | 17 +++++----- app/routes.py | 6 ++-- .../68e11332dba2_changed_mass_datatype.py | 34 +++++++++++++++++++ 4 files changed, 47 insertions(+), 14 deletions(-) create mode 100644 migrations/versions/68e11332dba2_changed_mass_datatype.py diff --git a/app/__init__.py b/app/__init__.py index e2d158696..e0dbc77fb 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -3,7 +3,7 @@ from flask_migrate import Migrate db = SQLAlchemy() -migrate = Migrate() +migrate = Migrate(compare_type=True) def create_app(test_config=None): app = Flask(__name__) @@ -12,7 +12,7 @@ def create_app(test_config=None): app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system' from app.models.planet import Planet - + db.init_app(app) migrate.init_app(app, db) diff --git a/app/models/planet.py b/app/models/planet.py index 1ef792171..ea0c3733e 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,3 +1,11 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + description = db.Column(db.String) + mass = db.Column(db.String) + # class Planet: # def __init__(self, id, name, description, mass): # self.id = id @@ -9,12 +17,3 @@ # Planet(2, "Mars", "dusty, cold desert",6.39e23), # Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) # ] - -from app import db - -class Planet(db.Model): - id = db.Column(db.Integer, primary_key=True, autoincrement=True) - name = db.Column(db.String) - description = db.Column(db.String) - mass = db.Column(db.String) - \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8c4b2c4d2..d9d6aee9d 100644 --- a/app/routes.py +++ b/app/routes.py @@ -61,10 +61,10 @@ def create_planet(): request_body = request.get_json() if "name" not in request_body or "description" not in request_body \ - or "mass" not in request_body: + or "mass" not in request_body: abort(make_response({"message" : \ - "Failed to create a planet because the name and/or description \ - and/or mass are missing"}, 400)) + "Failed to create a planet because the name and/or description \ + and/or mass are missing"}, 400)) new_planet = Planet( name=request_body["name"], diff --git a/migrations/versions/68e11332dba2_changed_mass_datatype.py b/migrations/versions/68e11332dba2_changed_mass_datatype.py new file mode 100644 index 000000000..25d38db9c --- /dev/null +++ b/migrations/versions/68e11332dba2_changed_mass_datatype.py @@ -0,0 +1,34 @@ +"""changed mass datatype + +Revision ID: 68e11332dba2 +Revises: f86f3dc07f4c +Create Date: 2022-12-21 17:22:10.875924 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '68e11332dba2' +down_revision = 'f86f3dc07f4c' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('planet', 'mass', + existing_type=sa.INTEGER(), + type_=sa.String(), + existing_nullable=True) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('planet', 'mass', + existing_type=sa.String(), + type_=sa.INTEGER(), + existing_nullable=True) + # ### end Alembic commands ### From e5b67aea47e2ef3ec5771b8700dd9d2b2265674b Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Wed, 21 Dec 2022 19:01:23 -0800 Subject: [PATCH 11/23] changed tale name to planets. all columns are not allowed to be null. mass data type is float. --- app/models/planet.py | 7 ++-- ...c_add_planet_model.py => 040c4f56aefe_.py} | 18 ++++---- .../68e11332dba2_changed_mass_datatype.py | 34 --------------- ...hanged_mass_to_string_datatype_to_float.py | 42 ------------------- 4 files changed, 13 insertions(+), 88 deletions(-) rename migrations/versions/{f86f3dc07f4c_add_planet_model.py => 040c4f56aefe_.py} (60%) delete mode 100644 migrations/versions/68e11332dba2_changed_mass_datatype.py delete mode 100644 migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py diff --git a/app/models/planet.py b/app/models/planet.py index 206ab85b4..180170130 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,10 +1,11 @@ from app import db class Planet(db.Model): + __tablename__ = 'planets' id = db.Column(db.Integer, primary_key=True, autoincrement=True) - name = db.Column(db.String) - description = db.Column(db.String) - mass = db.Column(db.String) + name = db.Column(db.String, nullable=False) + description = db.Column(db.String, nullable=False) + mass = db.Column(db.Float, nullable=False) # planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), # Planet(2, "Mars", "dusty, cold desert",6.39e23), diff --git a/migrations/versions/f86f3dc07f4c_add_planet_model.py b/migrations/versions/040c4f56aefe_.py similarity index 60% rename from migrations/versions/f86f3dc07f4c_add_planet_model.py rename to migrations/versions/040c4f56aefe_.py index 13d735b23..048f67d14 100644 --- a/migrations/versions/f86f3dc07f4c_add_planet_model.py +++ b/migrations/versions/040c4f56aefe_.py @@ -1,8 +1,8 @@ -"""add Planet model +"""empty message -Revision ID: f86f3dc07f4c +Revision ID: 040c4f56aefe Revises: -Create Date: 2022-12-20 11:18:49.218372 +Create Date: 2022-12-21 18:58:13.305413 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = 'f86f3dc07f4c' +revision = '040c4f56aefe' down_revision = None branch_labels = None depends_on = None @@ -18,11 +18,11 @@ def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('planet', + op.create_table('planets', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('name', sa.String(), nullable=True), - sa.Column('description', sa.String(), nullable=True), - sa.Column('mass', sa.Integer(), nullable=True), + sa.Column('name', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('mass', sa.Float(), nullable=False), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### @@ -30,5 +30,5 @@ def upgrade(): def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('planet') + op.drop_table('planets') # ### end Alembic commands ### diff --git a/migrations/versions/68e11332dba2_changed_mass_datatype.py b/migrations/versions/68e11332dba2_changed_mass_datatype.py deleted file mode 100644 index 25d38db9c..000000000 --- a/migrations/versions/68e11332dba2_changed_mass_datatype.py +++ /dev/null @@ -1,34 +0,0 @@ -"""changed mass datatype - -Revision ID: 68e11332dba2 -Revises: f86f3dc07f4c -Create Date: 2022-12-21 17:22:10.875924 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '68e11332dba2' -down_revision = 'f86f3dc07f4c' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('planet', 'mass', - existing_type=sa.INTEGER(), - type_=sa.String(), - existing_nullable=True) - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column('planet', 'mass', - existing_type=sa.String(), - type_=sa.INTEGER(), - existing_nullable=True) - # ### end Alembic commands ### diff --git a/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py b/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py deleted file mode 100644 index b3e1bb15b..000000000 --- a/migrations/versions/7fa857cd0ba2_changed_mass_to_string_datatype_to_float.py +++ /dev/null @@ -1,42 +0,0 @@ -"""changed mass to string datatype to Float - -Revision ID: 7fa857cd0ba2 -Revises: f86f3dc07f4c -Create Date: 2022-12-21 14:37:43.515533 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '7fa857cd0ba2' -down_revision = 'f86f3dc07f4c' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('planets', - sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), - sa.Column('name', sa.String(), nullable=True), - sa.Column('description', sa.String(), nullable=True), - sa.Column('mass', sa.Float(), nullable=True), - sa.PrimaryKeyConstraint('id') - ) - op.drop_table('planet') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.create_table('planet', - sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), - sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True), - sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True), - sa.Column('mass', sa.INTEGER(), autoincrement=False, nullable=True), - sa.PrimaryKeyConstraint('id', name='planet_pkey') - ) - op.drop_table('planets') - # ### end Alembic commands ### From 3cb1e0670689c1e885c5f0564f5eb8009b3ea9cd Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 22 Dec 2022 11:01:47 -0800 Subject: [PATCH 12/23] Updated display_all_planets to include query param for planet name --- app/routes.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index d9d6aee9d..8ae75643c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -28,11 +28,14 @@ def validate_id(planet_id): return planet - @planets_bp.route("",methods= ["GET"]) def display_all_planets(): + planet_name_query = request.args.get("name") + if planet_name_query: + planets = Planet.query.filter_by(name=planet_name_query) + else: + planets = Planet.query.all() response_planets = [] - planets = Planet.query.all() for planet in planets: response_planets.append({ "id": planet.id, @@ -80,9 +83,6 @@ def create_planet(): def update_planet(planet_id): request_body = request.get_json() planet = validate_id(planet_id) - # ~~~ REFACTOR ISSUE ~~~ This line runs but a problem with updating the db - # for attr in request_body: - # planet.attr = request_body[attr] planet.name = request_body["name"] if "name" in request_body else planet.name planet.description = request_body["description"] if "description" in request_body else planet.description planet.mass = request_body["mass"] if "mass" in request_body else planet.mass @@ -91,6 +91,7 @@ def update_planet(planet_id): {"message": f"planet #{planet_id} Updated Successfully"}, 200 ) + @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): planet = validate_id(planet_id) From ad4545482c73830ea747f0bfd640381448376265 Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 22 Dec 2022 16:20:34 -0800 Subject: [PATCH 13/23] Refactored query params in display_all_planets and added a helper function to separate param kwargs for SQLAlchemy query function --- app/routes.py | 62 ++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 11 deletions(-) diff --git a/app/routes.py b/app/routes.py index 8ae75643c..f0fc78c65 100644 --- a/app/routes.py +++ b/app/routes.py @@ -5,36 +5,76 @@ planets_bp = Blueprint("planets", __name__, url_prefix = "/planets") -# ~~~~~~ Handle planet id errors ~~~~~ -# FUTURE IDEAS: Create separate helper function module or add as class method + +# ~~~~~~ Helper functions ~~~~~ +# TO DO: Create separate helper function module or add as class method # def validate_id(planet_id): """ - - check for valid id type and if exists - - return planet object if valid planet id + Checks if planet id is valid and returns error messages for invalid inputs + :params: + - planet_id (int) + :returns: + - planet (object) if valid planet id valid """ try: planet_id_int = int(planet_id) except: # handling invalid planet id type abort(make_response({"message": f"{planet_id} is an invalid planet id"}, 400)) - + # return planet data if id in db planet = Planet.query.get(planet_id) # handle nonexistant planet id if not planet: abort(make_response({"message": f"{planet_id} not found"}, 404)) - return planet +def process_args(queries): + """ + Separate kwargs from HTTP request into separate dicts based on SQLAlchemy query method + :params: + - queries (dict) + :returns: + - attrs (dict): planet class attributes kwargs for filter_by + ** name, description, mass + - orderby (dict): method kwargs for order_by + ** sort_mass, sort_name + - sels (dict): selected number of results for limit + """ + # turn line 45 into a Planet class method + planet_attrs = [attr for attr in dir(Planet) if not attr.startswith('__')] + order_methods = ["sort"] + attrs = {} + orderby = {} + sels = {} + for kwarg in queries: + if kwarg in planet_attrs: + attrs[kwarg] = queries[kwarg] + elif kwarg in order_methods: + orderby[kwarg] = queries[kwarg] + elif kwarg == "limit": + sels[kwarg] = queries[kwarg] + else: + abort(make_response( + {"message" : f"{kwarg} is an invalid query"}, 400 + )) + return attrs, orderby, sels + @planets_bp.route("",methods= ["GET"]) def display_all_planets(): - planet_name_query = request.args.get("name") - if planet_name_query: - planets = Planet.query.filter_by(name=planet_name_query) - else: - planets = Planet.query.all() + planet_query = Planet.query + attrs, orderby, sels = process_args(request.args.to_dict()) + if attrs: + planet_query = planet_query.filter_by(**attrs) + # TO DO: works but only sorts by name currently ascending - need to add modularity + if orderby: + planet_query = planet_query.order_by(Planet.name.asc()) + if sels: + planet_query = planet_query.limit(**sels) + planets = planet_query.all() + # fill response response_planets = [] for planet in planets: response_planets.append({ From 847b34c4825e117b56cba68f6c8aa21eebe6f958 Mon Sep 17 00:00:00 2001 From: larissa Date: Thu, 22 Dec 2022 16:26:13 -0800 Subject: [PATCH 14/23] Switched function name from process_args() to process_kwargs since more accurate --- app/routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index f0fc78c65..6374e5971 100644 --- a/app/routes.py +++ b/app/routes.py @@ -30,7 +30,7 @@ def validate_id(planet_id): abort(make_response({"message": f"{planet_id} not found"}, 404)) return planet -def process_args(queries): +def process_kwargs(queries): """ Separate kwargs from HTTP request into separate dicts based on SQLAlchemy query method :params: @@ -65,7 +65,7 @@ def process_args(queries): @planets_bp.route("",methods= ["GET"]) def display_all_planets(): planet_query = Planet.query - attrs, orderby, sels = process_args(request.args.to_dict()) + attrs, orderby, sels = process_kwargs(request.args.to_dict()) if attrs: planet_query = planet_query.filter_by(**attrs) # TO DO: works but only sorts by name currently ascending - need to add modularity From 268d98136d3ae6941e3a7e5f22e3b652a6620c01 Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Tue, 3 Jan 2023 13:00:05 -0700 Subject: [PATCH 15/23] Create .env file, and tests folder with files --- tests/__init__.py | 0 tests/conftest.py | 0 tests/test_routes.py | 0 3 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_routes.py diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..e69de29bb From 3177d396816d8d6b7feecbde9de6f91b22ad292b Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Tue, 3 Jan 2023 14:40:00 -0800 Subject: [PATCH 16/23] created 3 fixtures:app, client, two_saved_planets.updated app/__init__.py to accept dev and test db. added test_get_all_planets_with_empty_db_returns_empty_list --- app/__init__.py | 10 +++++++++- tests/conftest.py | 33 +++++++++++++++++++++++++++++++++ tests/test_routes.py | 5 +++++ 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index e0dbc77fb..1350259a3 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,15 +1,23 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from dotenv import load_dotenv +import os db = SQLAlchemy() migrate = Migrate(compare_type=True) +load_dotenv() def create_app(test_config=None): app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/solar_system' + + if test_config: + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") + app.config['TESTING'] = True + else: + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("SQLALCHEMY_DATABASE_URI") from app.models.planet import Planet diff --git a/tests/conftest.py b/tests/conftest.py index e69de29bb..81c694a92 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -0,0 +1,33 @@ +import pytest +from app import create_app, db +from flask.signals import request_finished +from app.models.planet import Planet + +@pytest.fixture +def app(): + app = create_app(test_config=True) + + @request_finished.connect_via(app) + def expire_session(sender, response, **extra): + db.session.remove() + + with app.app_context(): + db.create_all() + yield app + + with app.app_context(): + db.drop_all() + + +@pytest.fixture +def client(app): + return app.test_client() + +@pytest.fixture +def two_saved_planets(app): + earth = Planet(name="Earth", \ + description="rocky, terrestrial, full of life", mass=5.972e24) + mars = Planet(name="Mars", description="dusty, cold desert", \ + mass=6.39e23) + db.session.add_all([earth, mars]) + db.session.commit() \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index e69de29bb..b08a9e903 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -0,0 +1,5 @@ +def test_get_all_planets_with_empty_db_returns_empty_list(client): + response = client.get("/planets") + + assert response.status_code == 200 + assert response.get_json() == [] \ No newline at end of file From 732b3c095356245458f9dfd7e13fe0dd4be46c61 Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Tue, 3 Jan 2023 14:54:35 -0800 Subject: [PATCH 17/23] added db.session.refresh in conftest.py --- tests/conftest.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/conftest.py b/tests/conftest.py index 81c694a92..e5c1f1bd2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -30,4 +30,6 @@ def two_saved_planets(app): mars = Planet(name="Mars", description="dusty, cold desert", \ mass=6.39e23) db.session.add_all([earth, mars]) - db.session.commit() \ No newline at end of file + db.session.commit() + for planet in [earth, mars]: + db.session.refresh(planet, ["id"]) \ No newline at end of file From 39e731f636699d77e2ba38bb58dda3732c303cd2 Mon Sep 17 00:00:00 2001 From: larissa Date: Tue, 3 Jan 2023 16:46:19 -0800 Subject: [PATCH 18/23] Planets for database --- planets.csv | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 planets.csv diff --git a/planets.csv b/planets.csv new file mode 100644 index 000000000..ad6c2ef2c --- /dev/null +++ b/planets.csv @@ -0,0 +1,8 @@ +1 Neptune thick, windy 1.0239999999999999e+26 +2 Earth rocky, terrestrial, full of life 5.972e+24 +3 Mars dusty, cold desert 6.39e+23 +6 Mercury small, solid & covered with craters 3.285e+23 +7 Venus Bright and solid surface with dome-like volcanoes, rifts, and mountains 4.867e+24 +8 Jupiter Cold, windy clouds of ammonia and water 1.89813e+27 +9 Saturn Massive ball made mostly of hydrogen and helium 5.683e+26 +10 Uranus Hot dense fluid of 'icy' materials - water, methane, and ammonia 8.681e+25 From a8ee6e487e2608c3ad5d6302c58d72bcf520965e Mon Sep 17 00:00:00 2001 From: larissa Date: Tue, 3 Jan 2023 16:47:27 -0800 Subject: [PATCH 19/23] Added get_all_attrs() method to Planet class --- app/models/planet.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index 180170130..26bc5261b 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,13 +1,25 @@ from app import db +# planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), +# Planet(2, "Mars", "dusty, cold desert",6.39e23), +# Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) +# ] + class Planet(db.Model): __tablename__ = 'planets' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False) description = db.Column(db.String, nullable=False) mass = db.Column(db.Float, nullable=False) - -# planets = [Planet(1, "Neptune", "thick, windy", 1.024e26 ), -# Planet(2, "Mars", "dusty, cold desert",6.39e23), -# Planet(3, "Earth", "rocky, terrestrial, full of life",5.972e24) -# ] + # gravity = db.Column(db.Float, nullable=False) + # dist_sun = db.Column(db.Float, nullable=False) + # n_moons = db.Column(db.Integer, nullable=False) + # water + # temperature + # atmosphere + + def get_all_attrs(): + """ + Returns all existing attributes (list) in Planet class + """ + return [attr for attr in dir(Planet) if not attr.startswith('__')] \ No newline at end of file From b06da98c4e0d2ef692a7251fb0759af7f77c2d32 Mon Sep 17 00:00:00 2001 From: larissa Date: Tue, 3 Jan 2023 16:48:44 -0800 Subject: [PATCH 20/23] Updated sort by attribute feature in display_all_planets() and process_kwargs() --- app/routes.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index 6374e5971..33838b3e0 100644 --- a/app/routes.py +++ b/app/routes.py @@ -42,9 +42,8 @@ def process_kwargs(queries): ** sort_mass, sort_name - sels (dict): selected number of results for limit """ - # turn line 45 into a Planet class method - planet_attrs = [attr for attr in dir(Planet) if not attr.startswith('__')] - order_methods = ["sort"] + planet_attrs = Planet.get_all_attrs() + order_methods = ["sort", "desc"] attrs = {} orderby = {} sels = {} @@ -64,17 +63,27 @@ def process_kwargs(queries): @planets_bp.route("",methods= ["GET"]) def display_all_planets(): + # collect query & parse kwargs planet_query = Planet.query attrs, orderby, sels = process_kwargs(request.args.to_dict()) if attrs: + # filter by attribute kwargs e.g name=Earth planet_query = planet_query.filter_by(**attrs) - # TO DO: works but only sorts by name currently ascending - need to add modularity - if orderby: - planet_query = planet_query.order_by(Planet.name.asc()) + if "sort" in orderby: + # sort by given attribute e.g.sort=mass + clause = getattr(Planet, orderby["sort"]) + if "desc" in orderby: + # sort in descending order e.g.desc=True + planet_query = planet_query.order_by(clause.desc()) + else: + # default is asc=True + planet_query = planet_query.order_by(clause.asc()) if sels: + # limit selection of planets to view planet_query = planet_query.limit(**sels) + # perform query planets = planet_query.all() - # fill response + # fill http response response_planets = [] for planet in planets: response_planets.append({ @@ -82,8 +91,7 @@ def display_all_planets(): "name": planet.name, "description": planet.description, "mass": planet.mass - }) - + }) return jsonify(response_planets) From 4226c76ac52fc4fa794556bcececa16771522f8a Mon Sep 17 00:00:00 2001 From: "echo '# Set PATH, MANPATH, etc., for Homebrew.' /Users/daliaali/.zprofile" Date: Tue, 3 Jan 2023 21:39:06 -0800 Subject: [PATCH 21/23] added tests for get /planet/ with an empty db, update planet successfully, get planet/ with an invalid id --- tests/conftest.py | 10 +++++++--- tests/test_routes.py | 26 +++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index e5c1f1bd2..01be5b83e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -29,7 +29,11 @@ def two_saved_planets(app): description="rocky, terrestrial, full of life", mass=5.972e24) mars = Planet(name="Mars", description="dusty, cold desert", \ mass=6.39e23) - db.session.add_all([earth, mars]) + planets = [earth, mars] + db.session.add_all(planets) db.session.commit() - for planet in [earth, mars]: - db.session.refresh(planet, ["id"]) \ No newline at end of file + + for planet in planets: + db.session.refresh(planet, ["id"]) + + return planets \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index b08a9e903..60d66ba60 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -2,4 +2,28 @@ def test_get_all_planets_with_empty_db_returns_empty_list(client): response = client.get("/planets") assert response.status_code == 200 - assert response.get_json() == [] \ No newline at end of file + assert response.get_json() == [] + + +def test_get_planet_by_id_with_empty_db_returns_404(client): + response = client.get("/planets/1") + + assert response.status_code == 404 + assert response.get_json() == {"message" : "1 not found"} + + +def test_update_planet_successfully(client, two_saved_planets): + test_data = {"name" : "earth", + "description" : "terrestrial, full of life", + "mass" : 5.97e24} + response = client.put("planets/1", json=test_data) + + assert response.status_code == 200 + assert response.get_json() == {"message": "planet #1 Updated Successfully"} + + +def test_get_planet_by_invalid_id_returns_400(client, two_saved_planets): + response = client.get("/planets/earth") + + assert response.status_code == 400 + assert response.get_json() == {"message": "earth is an invalid planet id"} \ No newline at end of file From aa928ce4662218b6d7462c7b07af1ceedd3c3aad Mon Sep 17 00:00:00 2001 From: Sheung Wan Wong Date: Tue, 3 Jan 2023 23:47:14 -0700 Subject: [PATCH 22/23] test: Create test_get_one_planet, test_create_one_planet and test_create_one_planet --- tests/conftest.py | 8 +++++--- tests/test_routes.py | 42 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index e5c1f1bd2..8d89fec3f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -29,7 +29,9 @@ def two_saved_planets(app): description="rocky, terrestrial, full of life", mass=5.972e24) mars = Planet(name="Mars", description="dusty, cold desert", \ mass=6.39e23) - db.session.add_all([earth, mars]) + planets = [earth, mars] + db.session.add_all(planets) db.session.commit() - for planet in [earth, mars]: - db.session.refresh(planet, ["id"]) \ No newline at end of file + for planet in planets: + db.session.refresh(planet, ["id"]) + return planets \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index b08a9e903..7f43aab6a 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -2,4 +2,44 @@ def test_get_all_planets_with_empty_db_returns_empty_list(client): response = client.get("/planets") assert response.status_code == 200 - assert response.get_json() == [] \ No newline at end of file + assert response.get_json() == [] + +def test_get_one_planet(client, two_saved_planets): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + "id" : 1, + "name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24 + } + +def test_create_one_planet(client): + #Act + response = client.post("/planets", json = { + "name": "Neptune", + "description": "thick, windy", + "mass":1.024e26 + }) + response_body = response.get_json() + + #Assert + assert response.status_code == 201 + assert response_body == {"message":"planet has been created successfully"} + +def test_create_one_planet_missing_mass_return_400(client): + #Act + response = client.post("/planets", json = { + "name": "Neptune", + "description": "thick, windy" + }) + response_body = response.get_json() + #Assert + assert response.status_code == 400 + assert response_body == {"message" : \ + "Failed to create a planet because the name and/or description \ + and/or mass are missing"} \ No newline at end of file From 6b26ea91a8c2ccdb3e1f81688b72f8706dee9a8b Mon Sep 17 00:00:00 2001 From: larissa Date: Wed, 4 Jan 2023 00:38:45 -0800 Subject: [PATCH 23/23] Added unit tests 3, 6, and 3 edge cases for get method with query kwargs in endpoint --- tests/test_routes.py | 61 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 60d66ba60..14040d4db 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -26,4 +26,63 @@ def test_get_planet_by_invalid_id_returns_400(client, two_saved_planets): response = client.get("/planets/earth") assert response.status_code == 400 - assert response.get_json() == {"message": "earth is an invalid planet id"} \ No newline at end of file + assert response.get_json() == {"message": "earth is an invalid planet id"} + +def test_get_planet_by_valid_data_returns_data_and_200(client, two_saved_planets): + response = client.get("/planets") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [ + {"name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24, + "id": 1}, + {"name": "Mars", + "description": "dusty, cold desert", + "mass": 6.39e23, + "id": 2} + ] + +def test_delete_planet_1_with_json_request_body_returns_200(client, two_saved_planets): + response = client.delete("/planets/1", json={ + "name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24, + "id": 1 + }) + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == {"message": f"planet #1 has been deleted successfully"}, 200 + +def test_get_mass_desc_and_limit_1_returns_data_and_200(client, two_saved_planets): + response = client.get("/planets?sort=mass&desc=True&limit=1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [{ + "name": "Earth", + "description": "rocky, terrestrial, full of life", + "mass": 5.972e24, + "id": 1 + }] + +def test_get_name_desc_and_limit_1_returns_data_and_200(client, two_saved_planets): + response = client.get("/planets?sort=name&desc=True&limit=1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [{ + "name": "Mars", + "description": "dusty, cold desert", + "mass": 6.39e23, + "id": 2 + }] + +def test_get_by_invalid_query_returns_error_message_and_400(client, two_saved_planets): + response = client.get("/planets?hamster=True") + response_body = response.get_json() + + assert response.status_code == 400 + assert response_body == {"message": "hamster is an invalid query"} \ No newline at end of file