From 3cc577458d5ebe172601c47e0ad8415b6faf4425 Mon Sep 17 00:00:00 2001 From: Morgan Buntin Date: Fri, 22 Apr 2022 15:19:39 -0400 Subject: [PATCH 01/11] defined planets blueprint, class, and route --- app/__init__.py | 3 +++ app/routes.py | 29 ++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..ab9eee40e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,4 +4,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/routes.py b/app/routes.py index 8e9dfe684..bb7fa2053 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,29 @@ -from flask import Blueprint +from flask import Blueprint, jsonify +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + +class Planet: + def __init__ (self, id, name, description, moon_count): + self.id = id + self.name = name + self.description = description + self.moon_count = moon_count + +planets = [ + Planet(1, "Mercury", "red planet", 1), + Planet(2, "Venus", "blue planet", 3), + Planet(1, "Earth", "water planet", 1) +] + +@planets_bp.route("", methods=["GET"]) +def get_planets(): + planet_response_body = [] + for planet in planets: + planet_response_body.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "moon_count": planet.moon_count + }) + + return jsonify(planet_response_body) \ No newline at end of file From 5f18e479674c2305c4228c28cbba6532686e935f Mon Sep 17 00:00:00 2001 From: Huma Hameed Date: Mon, 25 Apr 2022 23:08:07 -0400 Subject: [PATCH 02/11] completed wave2:single planet/exception handling --- app/routes.py | 37 +++++++++++++++++++++++++++++-------- requirements.txt | 2 +- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/app/routes.py b/app/routes.py index bb7fa2053..80c2dbd14 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 planets_bp = Blueprint("planets", __name__, url_prefix="/planets") @@ -8,6 +8,14 @@ def __init__ (self, id, name, description, moon_count): self.name = name self.description = description self.moon_count = moon_count + + def to_json(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "moon_count": self.moon_count + } planets = [ Planet(1, "Mercury", "red planet", 1), @@ -15,15 +23,28 @@ def __init__ (self, id, name, description, moon_count): Planet(1, "Earth", "water planet", 1) ] +def validate_planet(id): + try: + id = int(id) + except: + abort(make_response({"message": f"Planet {id} is not valid"}, 400)) + + for planet in planets: + if planet.id == id: + return planet + + return abort(make_response({"message": f"Planet {id} not found"}, 404)) + @planets_bp.route("", methods=["GET"]) def get_planets(): planet_response_body = [] for planet in planets: - planet_response_body.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "moon_count": planet.moon_count - }) + planet_response_body.append(planet.to_json()) - return jsonify(planet_response_body) \ No newline at end of file + return jsonify(planet_response_body) + +@planets_bp.route("/", methods=["GET"]) +def read_one_planet(planet_id): + planet = validate_planet(planet_id) + + return jsonify(planet.to_json()) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index a506b4d12..aa3718365 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,7 +12,7 @@ itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 -psycopg2-binary==2.8.6 +psycopg2-binary==2.9.3 pycodestyle==2.6.0 pytest==6.2.3 pytest-cov==2.12.1 From 1ae480366ab64cd5a11ee3148bc4ac661d5893b0 Mon Sep 17 00:00:00 2001 From: Huma Hameed Date: Sat, 30 Apr 2022 12:42:40 -0400 Subject: [PATCH 03/11] Co-authored-by: Morgan --- app/__init__.py | 12 ++++++++++++ app/models/__init__.py | 0 app/models/planet.py | 7 +++++++ 3 files changed, 19 insertions(+) create mode 100644 app/models/__init__.py create mode 100644 app/models/planet.py diff --git a/app/__init__.py b/app/__init__.py index ab9eee40e..440d92159 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,10 +1,22 @@ 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_development' + + db.init_app(app) + migrate.init_app(app, db) + from .routes import planets_bp app.register_blueprint(planets_bp) + from app.models.planet import Planet + return app 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..f463f3f4c --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,7 @@ +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) + moon_count = db.Column(db.Integer) \ No newline at end of file From f962a3348cc9b2075a04577e23211d140a555978 Mon Sep 17 00:00:00 2001 From: Morgan Buntin Date: Sat, 30 Apr 2022 13:02:12 -0400 Subject: [PATCH 04/11] created migration, planet post route --- app/routes.py | 66 ++++++------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../f1b1ac33653b_adds_planet_model.py | 34 +++++++ 6 files changed, 234 insertions(+), 32 deletions(-) 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/f1b1ac33653b_adds_planet_model.py diff --git a/app/routes.py b/app/routes.py index 80c2dbd14..7bb3a600b 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,39 +1,41 @@ -from flask import Blueprint, jsonify, abort, make_response +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, abort, make_response, request planets_bp = Blueprint("planets", __name__, url_prefix="/planets") - -class Planet: - def __init__ (self, id, name, description, moon_count): - self.id = id - self.name = name - self.description = description - self.moon_count = moon_count - def to_json(self): - return { - "id": self.id, - "name": self.name, - "description": self.description, - "moon_count": self.moon_count - } - -planets = [ - Planet(1, "Mercury", "red planet", 1), - Planet(2, "Venus", "blue planet", 3), - Planet(1, "Earth", "water planet", 1) -] - -def validate_planet(id): - try: - id = int(id) - except: - abort(make_response({"message": f"Planet {id} is not valid"}, 400)) - - for planet in planets: - if planet.id == id: - return planet + # def to_json(self): + # return { + # "id": self.id, + # "name": self.name, + # "description": self.description, + # "moon_count": self.moon_count + # } + +# def validate_planet(id): +# try: +# id = int(id) +# except: +# abort(make_response({"message": f"Planet {id} is not valid"}, 400)) + +# for planet in planets: +# if planet.id == id: +# return planet - return abort(make_response({"message": f"Planet {id} not found"}, 404)) +# return abort(make_response({"message": f"Planet {id} not found"}, 404)) + + +@planets_bp.route("", methods=["POST"]) +def create_planet(): + request_body = request.get_json() + new_planet = Planet(name=request_body["name"], + description=request_body["description"], + moon_count=request_body["moon_count"]) + + db.session.add(new_planet) + db.session.commit() + + return make_response(f"Planet {new_planet.name} successfully created", 201) @planets_bp.route("", methods=["GET"]) def get_planets(): 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/f1b1ac33653b_adds_planet_model.py b/migrations/versions/f1b1ac33653b_adds_planet_model.py new file mode 100644 index 000000000..f05d1adbf --- /dev/null +++ b/migrations/versions/f1b1ac33653b_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: f1b1ac33653b +Revises: +Create Date: 2022-04-30 12:46:47.395099 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'f1b1ac33653b' +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('moon_count', 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 a968b9ebf8b92a029f8b77f1b72c594dfa74355d Mon Sep 17 00:00:00 2001 From: Huma Hameed Date: Sat, 30 Apr 2022 13:21:46 -0400 Subject: [PATCH 05/11] finished wave3 --- app/models/planet.py | 10 +++++++++- app/routes.py | 3 ++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/app/models/planet.py b/app/models/planet.py index f463f3f4c..91e6833d7 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -4,4 +4,12 @@ class Planet(db.Model): id = db.Column(db.Integer, primary_key = True, autoincrement = True) name = db.Column(db.String) description = db.Column(db.String) - moon_count = db.Column(db.Integer) \ No newline at end of file + moon_count = db.Column(db.Integer) + + def to_json(self): + return { + "id": self.id, + "name": self.name, + "description": self.description, + "moon_count": self.moon_count + } \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 7bb3a600b..860d75c18 100644 --- a/app/routes.py +++ b/app/routes.py @@ -39,11 +39,12 @@ def create_planet(): @planets_bp.route("", methods=["GET"]) def get_planets(): + planets = Planet.query.all() planet_response_body = [] for planet in planets: planet_response_body.append(planet.to_json()) - return jsonify(planet_response_body) + return jsonify(planet_response_body), 200 @planets_bp.route("/", methods=["GET"]) def read_one_planet(planet_id): From 2f43a2dd40b2573ca5c70d756587022deacacbd8 Mon Sep 17 00:00:00 2001 From: Huma Hameed Date: Tue, 3 May 2022 13:48:20 -0400 Subject: [PATCH 06/11] wave4:Read one planet and update --- app/routes.py | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/app/routes.py b/app/routes.py index 860d75c18..855010fca 100644 --- a/app/routes.py +++ b/app/routes.py @@ -12,18 +12,15 @@ # "moon_count": self.moon_count # } -# def validate_planet(id): -# try: -# id = int(id) -# except: -# abort(make_response({"message": f"Planet {id} is not valid"}, 400)) - -# for planet in planets: -# if planet.id == id: -# return planet - -# return abort(make_response({"message": f"Planet {id} not found"}, 404)) - +def validate_planet(id): + try: + id = int(id) + except: + abort(make_response({"message": f"Planet {id} is not valid"}, 400)) + planet = Planet.query.get(id) + if not planet: + abort(make_response({"message": f"Planet {id} not found"}, 404)) + return planet @planets_bp.route("", methods=["POST"]) def create_planet(): @@ -50,4 +47,18 @@ def get_planets(): def read_one_planet(planet_id): planet = validate_planet(planet_id) - return jsonify(planet.to_json()) \ No newline at end of file + return jsonify(planet.to_json()) + +@planets_bp.route("/", methods=["PUT"]) +def update_planet(planet_id): + planet = validate_planet(planet_id) + + request_body = request.get_json() + + planet.name = request_body["name"] + planet.description = request_body["description"] + planet.moon_count = request_body["moon_count"] + + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully updated") \ No newline at end of file From 59e6abc9ae3922e5d31748fa4fae69289871c443 Mon Sep 17 00:00:00 2001 From: Morgan Buntin Date: Tue, 3 May 2022 13:55:12 -0400 Subject: [PATCH 07/11] completed wave 4, added delete --- app/routes.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/app/routes.py b/app/routes.py index 855010fca..5da4a22a5 100644 --- a/app/routes.py +++ b/app/routes.py @@ -61,4 +61,13 @@ def update_planet(planet_id): db.session.commit() - return make_response(f"Planet #{planet.id} successfully updated") \ No newline at end of file + return make_response(f"Planet #{planet.id} successfully updated") + +@planets_bp.route("/", methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_planet(planet_id) + + db.session.delete(planet) + db.session.commit() + + return make_response(f"Planet #{planet.id} successfully deleted") From a9ca58598f8c8ee296141a876e7e0357f2b3254a Mon Sep 17 00:00:00 2001 From: Morgan Buntin Date: Wed, 4 May 2022 14:14:38 -0400 Subject: [PATCH 08/11] added query param and refactoring --- app/helpers.py | 12 ++++++++++++ app/models/planet.py | 16 +++++++++++++++- app/routes.py | 37 +++++++++++-------------------------- 3 files changed, 38 insertions(+), 27 deletions(-) create mode 100644 app/helpers.py diff --git a/app/helpers.py b/app/helpers.py new file mode 100644 index 000000000..5a66b86e3 --- /dev/null +++ b/app/helpers.py @@ -0,0 +1,12 @@ +from flask import abort, make_response +from .models.planet import Planet + +def validate_planet(id): + try: + id = int(id) + except: + abort(make_response({"message": f"Planet {id} is not valid"}, 400)) + planet = Planet.query.get(id) + if not planet: + abort(make_response({"message": f"Planet {id} not found"}, 404)) + return planet \ No newline at end of file diff --git a/app/models/planet.py b/app/models/planet.py index 91e6833d7..51456d1fe 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -12,4 +12,18 @@ def to_json(self): "name": self.name, "description": self.description, "moon_count": self.moon_count - } \ No newline at end of file + } + + def update(self, req_body): + self.name = req_body["name"] + self.description = req_body["description"] + self.moon_count = req_body["moon_count"] + + @classmethod + def create(cls, req_body): + new_planet = cls( + name=req_body["name"], + description=req_body["description"], + moon_count=req_body["moon_count"] + ) + return new_planet \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 5da4a22a5..39c816fea 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,33 +1,14 @@ from app import db from app.models.planet import Planet -from flask import Blueprint, jsonify, abort, make_response, request +from flask import Blueprint, jsonify, make_response, request +from .helpers import validate_planet planets_bp = Blueprint("planets", __name__, url_prefix="/planets") - - # def to_json(self): - # return { - # "id": self.id, - # "name": self.name, - # "description": self.description, - # "moon_count": self.moon_count - # } - -def validate_planet(id): - try: - id = int(id) - except: - abort(make_response({"message": f"Planet {id} is not valid"}, 400)) - planet = Planet.query.get(id) - if not planet: - abort(make_response({"message": f"Planet {id} not found"}, 404)) - return planet @planets_bp.route("", methods=["POST"]) def create_planet(): request_body = request.get_json() - new_planet = Planet(name=request_body["name"], - description=request_body["description"], - moon_count=request_body["moon_count"]) + new_planet = Planet.create(request_body) db.session.add(new_planet) db.session.commit() @@ -36,7 +17,13 @@ def create_planet(): @planets_bp.route("", methods=["GET"]) def get_planets(): - planets = Planet.query.all() + name_query = request.args.get("name") + + if name_query: + planets = Planet.query.filter_by(name=name_query) + else: + planets = Planet.query.all() + planet_response_body = [] for planet in planets: planet_response_body.append(planet.to_json()) @@ -55,9 +42,7 @@ def update_planet(planet_id): request_body = request.get_json() - planet.name = request_body["name"] - planet.description = request_body["description"] - planet.moon_count = request_body["moon_count"] + planet.update(request_body) db.session.commit() From bcf5ceb399b15c3af2c864afb03bc80f31449d32 Mon Sep 17 00:00:00 2001 From: Morgan Buntin Date: Thu, 5 May 2022 08:45:36 -0400 Subject: [PATCH 09/11] formatting and explicit 200 status --- app/helpers.py | 3 +++ app/routes.py | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/app/helpers.py b/app/helpers.py index 5a66b86e3..804cb4577 100644 --- a/app/helpers.py +++ b/app/helpers.py @@ -6,7 +6,10 @@ def validate_planet(id): id = int(id) except: abort(make_response({"message": f"Planet {id} is not valid"}, 400)) + planet = Planet.query.get(id) + if not planet: abort(make_response({"message": f"Planet {id} not found"}, 404)) + return planet \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 39c816fea..4555a7411 100644 --- a/app/routes.py +++ b/app/routes.py @@ -34,7 +34,7 @@ def get_planets(): def read_one_planet(planet_id): planet = validate_planet(planet_id) - return jsonify(planet.to_json()) + return jsonify(planet.to_json()), 200 @planets_bp.route("/", methods=["PUT"]) def update_planet(planet_id): @@ -46,7 +46,7 @@ def update_planet(planet_id): db.session.commit() - return make_response(f"Planet #{planet.id} successfully updated") + return make_response(f"Planet #{planet.id} successfully updated", 200) @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): @@ -55,4 +55,4 @@ def delete_planet(planet_id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet #{planet.id} successfully deleted") + return make_response(f"Planet #{planet.id} successfully deleted", 200) From c66c7a5ddd5f6f13c77528b48e07f4d25a01f59e Mon Sep 17 00:00:00 2001 From: Huma Hameed Date: Fri, 6 May 2022 08:39:33 -0400 Subject: [PATCH 10/11] wave6:.env/test1 --- app/__init__.py | 14 ++++++++++++-- app/tests/__init__.py | 0 app/tests/conftest.py | 25 +++++++++++++++++++++++++ app/tests/test_routes.py | 8 ++++++++ 4 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 app/tests/__init__.py create mode 100644 app/tests/conftest.py create mode 100644 app/tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index 440d92159..d86c6f0cd 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,15 +1,25 @@ 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() +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_development' + if not test_config: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + "SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) diff --git a/app/tests/__init__.py b/app/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/tests/conftest.py b/app/tests/conftest.py new file mode 100644 index 000000000..ac8a4193b --- /dev/null +++ b/app/tests/conftest.py @@ -0,0 +1,25 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished + + +@pytest.fixture +def app(): + app = create_app({"TESTING": 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() \ No newline at end of file diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py new file mode 100644 index 000000000..1124a9765 --- /dev/null +++ b/app/tests/test_routes.py @@ -0,0 +1,8 @@ +def test_get_all_planets_with_no_records(client): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [] \ No newline at end of file From 43cdbc4b06e1e2b58c30d0deb757eb4a7e4093b3 Mon Sep 17 00:00:00 2001 From: Morgan Buntin Date: Fri, 6 May 2022 09:15:24 -0400 Subject: [PATCH 11/11] completed testing wave --- app/routes.py | 6 ++-- app/tests/conftest.py | 16 ++++++++++- app/tests/test_routes.py | 59 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 76 insertions(+), 5 deletions(-) diff --git a/app/routes.py b/app/routes.py index 4555a7411..8cea26c1c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -13,7 +13,7 @@ def create_planet(): db.session.add(new_planet) db.session.commit() - return make_response(f"Planet {new_planet.name} successfully created", 201) + return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) @planets_bp.route("", methods=["GET"]) def get_planets(): @@ -46,7 +46,7 @@ def update_planet(planet_id): db.session.commit() - return make_response(f"Planet #{planet.id} successfully updated", 200) + return make_response(jsonify(f"Planet #{planet.id} successfully updated"), 200) @planets_bp.route("/", methods=["DELETE"]) def delete_planet(planet_id): @@ -55,4 +55,4 @@ def delete_planet(planet_id): db.session.delete(planet) db.session.commit() - return make_response(f"Planet #{planet.id} successfully deleted", 200) + return make_response(jsonify(f"Planet #{planet.id} successfully deleted"), 200) diff --git a/app/tests/conftest.py b/app/tests/conftest.py index ac8a4193b..db17dfc5d 100644 --- a/app/tests/conftest.py +++ b/app/tests/conftest.py @@ -2,6 +2,7 @@ from app import create_app from app import db from flask.signals import request_finished +from app.models.planet import Planet @pytest.fixture @@ -22,4 +23,17 @@ def expire_session(sender, response, **extra): @pytest.fixture def client(app): - return app.test_client() \ No newline at end of file + return app.test_client() + +@pytest.fixture +def two_saved_planets(app): + + ocean_planet = Planet(name="Caladan", + description="OG home of House Atreides", + moon_count=4) + spice_planet = Planet(name="Arrakis", + description="Control Arrakis, control the universe", + moon_count=2) + + db.session.add_all([ocean_planet, spice_planet]) + db.session.commit() \ No newline at end of file diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py index 1124a9765..761ba3ef4 100644 --- a/app/tests/test_routes.py +++ b/app/tests/test_routes.py @@ -1,3 +1,6 @@ +from urllib import response + + def test_get_all_planets_with_no_records(client): # Act response = client.get("/planets") @@ -5,4 +8,58 @@ def test_get_all_planets_with_no_records(client): # Assert assert response.status_code == 200 - assert response_body == [] \ No newline at end of file + assert response_body == [] + +def test_get_all_planets_with_saved_records(client, two_saved_planets): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [{ + "id": 1, + "name": "Caladan", + "description": "OG home of House Atreides", + "moon_count": 4 + }, + { + "id": 2, + "name": "Arrakis", + "description": "Control Arrakis, control the universe", + "moon_count": 2 + }] + +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": "Caladan", + "description": "OG home of House Atreides", + "moon_count": 4 + } + +def test_get_one_missing_planet(client): + response = client.get("/planets/1") + response_body = response.get_json() + + assert response.status_code == 404 + assert response_body == {"message": "Planet 1 not found"} + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json={ + "name": "Giedi Prime", + "description": "Not a great planet", + "moon_count": 1 + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == "Planet Giedi Prime successfully created" \ No newline at end of file