From 7923b144925f3e0f694ef0cffdc6c4dbb5cc36bf Mon Sep 17 00:00:00 2001 From: Tazmeen Date: Fri, 21 Oct 2022 11:56:50 -0400 Subject: [PATCH 01/16] worked on wave 1 --- README.md | 1 - app/__init__.py | 3 ++- app/routes.py | 37 ++++++++++++++++++++++++++++++++++- project-directions/wave_01.md | 2 +- 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f9d17f77c..da2a90c6f 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,6 @@ We will focus on creating RESTful endpoints for CRUD operations. - Take time to make sure you're on the same page ## Project Directions - ### Part 1 1. [Wave 01: Setup and Read](./project-directions/wave_01.md) 1. [Wave 02: Read and 404s](./project-directions/wave_02.md) diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..a1de5be1c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,8 @@ from flask import Flask - +from .routes import planets_bp def create_app(test_config=None): app = Flask(__name__) + app.register_blueprint(planets_bp) return app diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..ae8fc5688 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,37 @@ -from flask import Blueprint +from flask import Blueprint, jsonify + +class Planet: + def __init__(self, id, name, description, num_moons): + self.id = id + self.name = name + self.description = description + self.num_moons = num_moons + + +planets = [ + Planet(1, 'Mercury', {"distance_from_sun": "36.04 million mi"}, 0), + Planet(2, 'Venus', {"distance_from_sun": "67.24 million mi"}, 0), + Planet(3, 'Earth', {"distance_from_sun": "92.96 million mi"}, 1), + Planet(4, 'Mars', {"distance_from_sun": "141.60 million mi"}, 2), + Planet(5, 'Jupiter', {"distance_from_sun": "483.80 million mi"}, 80), + Planet(6, 'Saturn', {"distance_from_sun": "890.8 million mi"}, 83), + Planet(7, 'Uranus', {"distance_from_sun": "1.784 billion mi"}, 27), + Planet(8, 'Neptune', {"distance_from_sun": "2.793 billion mi"}, 14), + Planet(9, 'Pluto', {"distance_from_sun": "3.70 billion mi"}, 5), +] + +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + + +@planets_bp.route("", methods=["GET"]) +def get_all_planets(): + planets_response = [] + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "number of moons": planet.num_moons + }) + return jsonify(planets_response) diff --git a/project-directions/wave_01.md b/project-directions/wave_01.md index a07cc6548..ffd748690 100644 --- a/project-directions/wave_01.md +++ b/project-directions/wave_01.md @@ -13,4 +13,4 @@ Create the following endpoint(s), with similar functionality presented in the He As a client, I want to send a request... -1. ...to get all existing `planets`, so that I can see a list of `planets`, with their `id`, `name`, `description`, and other data of the `planet`. +1. ...to get all existing `planets`, so that I can see a list of `planets`, with their `id`, `name`, `description`, and other data of the `planet`. \ No newline at end of file From 91d4c82ffa3e58182013da0298707e740d36df27 Mon Sep 17 00:00:00 2001 From: Tazmeen Date: Mon, 24 Oct 2022 12:22:32 -0400 Subject: [PATCH 02/16] finished wave 2 --- app/routes.py | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/app/routes.py b/app/routes.py index ae8fc5688..6d0eb2846 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 class Planet: @@ -9,7 +9,7 @@ def __init__(self, id, name, description, num_moons): self.num_moons = num_moons -planets = [ +PLANETS = [ Planet(1, 'Mercury', {"distance_from_sun": "36.04 million mi"}, 0), Planet(2, 'Venus', {"distance_from_sun": "67.24 million mi"}, 0), Planet(3, 'Earth', {"distance_from_sun": "92.96 million mi"}, 1), @@ -26,12 +26,32 @@ def __init__(self, id, name, description, num_moons): @planets_bp.route("", methods=["GET"]) def get_all_planets(): - planets_response = [] - for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "number of moons": planet.num_moons - }) + planets_response = [vars(planet) for planet in PLANETS] + # for planet in PLANETS: + # planets_response.append({ + # "id": planet.id, + # "name": planet.name, + # "description": planet.description, + # "number of moons": planet.num_moons + # }) return jsonify(planets_response) + + +@planets_bp.route("/", methods=["GET"]) +def get_one_planet(id): + planet = validate_planet(id) + return planet + + +def validate_planet(id): + try: + planet_id = int(id) + + except ValueError: + return {"message": "planet does not exist"}, 400 + + for planet in PLANETS: + if planet.id == planet_id: + return vars(planet) + + abort(make_response(jsonify(description="resource not found"), 404)) From 37867e46666d7b7cffa97dd367e5655c8ca7ace2 Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Tue, 1 Nov 2022 10:51:25 -0400 Subject: [PATCH 03/16] adds Planet model --- app/__init__.py | 19 +++- app/models/__init__.py | 0 app/models/planet.py | 7 ++ app/routes.py | 86 ++++++++--------- migrations/README | 1 + migrations/alembic.ini | 45 +++++++++ migrations/env.py | 96 +++++++++++++++++++ migrations/script.py.mako | 24 +++++ .../e5efce9ac694_adds_planet_model.py | 34 +++++++ 9 files changed, 267 insertions(+), 45 deletions(-) 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/e5efce9ac694_adds_planet_model.py diff --git a/app/__init__.py b/app/__init__.py index a1de5be1c..65964692d 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +1,23 @@ from flask import Flask +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate -from .routes import planets_bp -def create_app(test_config=None): +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..1b9c0501a --- /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) + num_moons = db.Column(db.Integer) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 6d0eb2846..b8869f9b4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,57 +1,57 @@ from flask import Blueprint, jsonify, abort, make_response -class Planet: - def __init__(self, id, name, description, num_moons): - self.id = id - self.name = name - self.description = description - self.num_moons = num_moons - - -PLANETS = [ - Planet(1, 'Mercury', {"distance_from_sun": "36.04 million mi"}, 0), - Planet(2, 'Venus', {"distance_from_sun": "67.24 million mi"}, 0), - Planet(3, 'Earth', {"distance_from_sun": "92.96 million mi"}, 1), - Planet(4, 'Mars', {"distance_from_sun": "141.60 million mi"}, 2), - Planet(5, 'Jupiter', {"distance_from_sun": "483.80 million mi"}, 80), - Planet(6, 'Saturn', {"distance_from_sun": "890.8 million mi"}, 83), - Planet(7, 'Uranus', {"distance_from_sun": "1.784 billion mi"}, 27), - Planet(8, 'Neptune', {"distance_from_sun": "2.793 billion mi"}, 14), - Planet(9, 'Pluto', {"distance_from_sun": "3.70 billion mi"}, 5), -] +# class Planet: +# def __init__(self, id, name, description, num_moons): +# self.id = id +# self.name = name +# self.description = description +# self.num_moons = num_moons + + +# PLANETS = [ +# Planet(1, 'Mercury', {"distance_from_sun": "36.04 million mi"}, 0), +# Planet(2, 'Venus', {"distance_from_sun": "67.24 million mi"}, 0), +# Planet(3, 'Earth', {"distance_from_sun": "92.96 million mi"}, 1), +# Planet(4, 'Mars', {"distance_from_sun": "141.60 million mi"}, 2), +# Planet(5, 'Jupiter', {"distance_from_sun": "483.80 million mi"}, 80), +# Planet(6, 'Saturn', {"distance_from_sun": "890.8 million mi"}, 83), +# Planet(7, 'Uranus', {"distance_from_sun": "1.784 billion mi"}, 27), +# Planet(8, 'Neptune', {"distance_from_sun": "2.793 billion mi"}, 14), +# Planet(9, 'Pluto', {"distance_from_sun": "3.70 billion mi"}, 5), +# ] planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -@planets_bp.route("", methods=["GET"]) -def get_all_planets(): - planets_response = [vars(planet) for planet in PLANETS] - # for planet in PLANETS: - # planets_response.append({ - # "id": planet.id, - # "name": planet.name, - # "description": planet.description, - # "number of moons": planet.num_moons - # }) - return jsonify(planets_response) +# @planets_bp.route("", methods=["GET"]) +# def get_all_planets(): +# planets_response = [vars(planet) for planet in PLANETS] +# # for planet in PLANETS: +# # planets_response.append({ +# # "id": planet.id, +# # "name": planet.name, +# # "description": planet.description, +# # "number of moons": planet.num_moons +# # }) +# return jsonify(planets_response) -@planets_bp.route("/", methods=["GET"]) -def get_one_planet(id): - planet = validate_planet(id) - return planet +# @planets_bp.route("/", methods=["GET"]) +# def get_one_planet(id): +# planet = validate_planet(id) +# return planet -def validate_planet(id): - try: - planet_id = int(id) +# def validate_planet(id): +# try: +# planet_id = int(id) - except ValueError: - return {"message": "planet does not exist"}, 400 +# except ValueError: +# return {"message": "planet does not exist"}, 400 - for planet in PLANETS: - if planet.id == planet_id: - return vars(planet) +# for planet in PLANETS: +# if planet.id == planet_id: +# return vars(planet) - abort(make_response(jsonify(description="resource not found"), 404)) +# abort(make_response(jsonify(description="resource not found"), 404)) 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/e5efce9ac694_adds_planet_model.py b/migrations/versions/e5efce9ac694_adds_planet_model.py new file mode 100644 index 000000000..74299ab65 --- /dev/null +++ b/migrations/versions/e5efce9ac694_adds_planet_model.py @@ -0,0 +1,34 @@ +"""adds Planet model + +Revision ID: e5efce9ac694 +Revises: +Create Date: 2022-11-01 10:50:27.983178 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e5efce9ac694' +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('num_moons', 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 558cee640721a35fdd1b9d820b187661e386c8a0 Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Wed, 2 Nov 2022 11:32:20 -0400 Subject: [PATCH 04/16] add get, post, put, and delete methods --- app/routes.py | 98 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 73 insertions(+), 25 deletions(-) diff --git a/app/routes.py b/app/routes.py index b8869f9b4..64dad6d7f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,6 @@ -from flask import Blueprint, jsonify, abort, make_response +from app import db +from app.models.planet import Planet +from flask import Blueprint, jsonify, make_response, request, abort # class Planet: @@ -24,34 +26,80 @@ planets_bp = Blueprint("planets", __name__, url_prefix="/planets") -# @planets_bp.route("", methods=["GET"]) -# def get_all_planets(): -# planets_response = [vars(planet) for planet in PLANETS] -# # for planet in PLANETS: -# # planets_response.append({ -# # "id": planet.id, -# # "name": planet.name, -# # "description": planet.description, -# # "number of moons": planet.num_moons -# # }) -# return jsonify(planets_response) +@planets_bp.route("", methods=["GET"]) +def read_planets(): + planets_response = [] + planets = Planet.query.all() + for planet in planets: + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "number of moons": planet.num_moons + }) + return jsonify(planets_response) -# @planets_bp.route("/", methods=["GET"]) -# def get_one_planet(id): -# planet = validate_planet(id) -# 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"], + num_moons=request_body["num_moons"]) -# def validate_planet(id): -# try: -# planet_id = int(id) + db.session.add(new_planet) + db.session.commit() -# except ValueError: -# return {"message": "planet does not exist"}, 400 + return make_response(f"Planet {new_planet.name} successfully created", 201) -# for planet in PLANETS: -# if planet.id == planet_id: -# return vars(planet) + + +@planets_bp.route("/", methods=["GET"]) +def get_one_planet(planet_id): + planet = validate_planet(planet_id) -# abort(make_response(jsonify(description="resource not found"), 404)) + return { + "id": planet.id, + "name": planet.name, + "description": planet.description, + "number of moons": planet.num_moons + } + + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message":f"planet {planet_id} invalid"}, 400)) + + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response({"message":f"planet {planet_id} not found"}, 404)) + + return planet + + +@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.num_moons = request_body["num_moons"] + + db.session.commit() + + 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 9269b9f2057b19b70feb4874a8fed12b62436b76 Mon Sep 17 00:00:00 2001 From: Sika Sarpong <50897076+sikasarp@users.noreply.github.com> Date: Wed, 2 Nov 2022 11:04:46 -0700 Subject: [PATCH 05/16] added query param --- app/routes.py | 31 +++-- intro-to-sql-problemset.sql | 219 ++++++++++++++++++++++++++++++++++ project-directions/wave_05.md | 2 +- 3 files changed, 241 insertions(+), 11 deletions(-) create mode 100644 intro-to-sql-problemset.sql diff --git a/app/routes.py b/app/routes.py index 64dad6d7f..d0eb0dc05 100644 --- a/app/routes.py +++ b/app/routes.py @@ -28,16 +28,27 @@ @planets_bp.route("", methods=["GET"]) def read_planets(): + planet_query = Planet.query + name_query = request.args.get("name") + + if name_query: + planet_query = planet_query.filter(Planet.name.ilike(f"%{name_query}%")) + + moon_query = request.args.get("num_moons") + if moon_query: + planet_query = planet_query.filter_by(moons=moon_query) planets_response = [] - planets = Planet.query.all() - + planets = Planet.query.all() for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "number of moons": planet.num_moons - }) + planets_response.append({ + "id": planet.id, + "name": planet.name, + "description": planet.description, + "number of moons": planet.num_moons + }) + + if not planets_response: + return make_response(jsonify(f"There are no planets named {name_query} planet")) return jsonify(planets_response) @@ -45,8 +56,8 @@ def read_planets(): def create_planet(): request_body = request.get_json() new_planet = Planet(name=request_body["name"], - description=request_body["description"], - num_moons=request_body["num_moons"]) + description=request_body["description"], + num_moons=request_body["num_moons"]) db.session.add(new_planet) db.session.commit() diff --git a/intro-to-sql-problemset.sql b/intro-to-sql-problemset.sql new file mode 100644 index 000000000..c711e51ed --- /dev/null +++ b/intro-to-sql-problemset.sql @@ -0,0 +1,219 @@ +-- +-- PostgreSQL database dump +-- + +-- Dumped from database version 13.2 +-- Dumped by pg_dump version 13.2 + +-- Started on 2021-03-13 20:00:58 PST + +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +SET default_tablespace = ''; + +SET default_table_access_method = heap; + +-- Exists just to be deleted +CREATE TABLE public.books(); +ALTER TABLE public.books OWNER TO postgres; + +-- +-- TOC entry 200 (class 1259 OID 16663) +-- Name: products; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.products ( + id integer NOT NULL, + name character varying(32), + publisher_id integer, + description text +); + + +ALTER TABLE public.products OWNER TO postgres; + +-- +-- TOC entry 201 (class 1259 OID 16669) +-- Name: products_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres +-- + +ALTER TABLE public.products ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( + SEQUENCE NAME public.products_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- TOC entry 202 (class 1259 OID 16671) +-- Name: publishers; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.publishers ( + id integer NOT NULL, + name character varying(32), + address character varying(64) +); + + +ALTER TABLE public.publishers OWNER TO postgres; + +-- +-- TOC entry 203 (class 1259 OID 16674) +-- Name: publishers_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres +-- + +ALTER TABLE public.publishers ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( + SEQUENCE NAME public.publishers_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- TOC entry 204 (class 1259 OID 16676) +-- Name: users; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.users ( + id integer NOT NULL, + first_name character varying(32), + last_name character varying(32), + email character varying(32) +); + + +ALTER TABLE public.users OWNER TO postgres; + +-- +-- TOC entry 205 (class 1259 OID 16679) +-- Name: users_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres +-- + +ALTER TABLE public.users ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY ( + SEQUENCE NAME public.users_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + + +-- +-- TOC entry 3262 (class 0 OID 16663) +-- Dependencies: 200 +-- Data for Name: products; Type: TABLE DATA; Schema: public; Owner: postgres +-- + +COPY public.products (id, name, publisher_id, description) FROM stdin; +1 Nimona 1 Wonderful comic by Noelle Stevenson +2 Watchmen 2 Dark, very dark +3 Maus: A Survivors Tale 1 Two volume historical memoir. +4 Daytripper 3 Death retroactively imposes a shape on a person’s life. +5 This One Summer 103 Written by Mariko Tamaki and illustrated by Jillian Tamaki. +6 Sweet Tooth 103 Interesting tale. +7 Through The Woods 99 It came from the woods. Most strange things do. +8 Blankets 3 Semiautobiographical story of a young man raised in a strict evangelical tradition. +\. + +-- +-- TOC entry 3264 (class 0 OID 16671) +-- Dependencies: 202 +-- Data for Name: publishers; Type: TABLE DATA; Schema: public; Owner: postgres +-- + +COPY public.publishers (id, name, address) FROM stdin; +1 Blue Gem Publishers 123 Elm Street Tuscon AZ 12837 +2 Ruby Comics P.O. Box Portland, OR 96545 +3 Developers Academy 315 5th Ave S Suite 200, Seattle, WA 98104 +4 Angry Elf Ltd 111 East Down Street London England 11111 +5 Shueishan Comics P.O. Box 11231 New York, NY 01754 +\. + + +-- +-- TOC entry 3266 (class 0 OID 16676) +-- Dependencies: 204 +-- Data for Name: users; Type: TABLE DATA; Schema: public; Owner: postgres +-- + +COPY public.users (id, first_name, last_name, email) FROM stdin; +2 Sujay Rosemary sujay.rosemary@email.com +3 Vittorio Oliver voliver@email.com +4 Sofija Maraĵa smaraja@email.com +5 Bendik Genoveva bendik.genoveva@safemail.com +6 Auster Alexandra auster.alexandra@safemail.com +7 Deepali Efrem deepali.Efrem@email.com +8 Coade OMoore cade.omoore@gmail.com +\. + + +-- +-- TOC entry 3273 (class 0 OID 0) +-- Dependencies: 201 +-- Name: products_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres +-- + +SELECT pg_catalog.setval('public.products_id_seq', 10, true); + + +-- +-- TOC entry 3274 (class 0 OID 0) +-- Dependencies: 203 +-- Name: publishers_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres +-- + +SELECT pg_catalog.setval('public.publishers_id_seq', 5, true); + + +-- +-- TOC entry 3275 (class 0 OID 0) +-- Dependencies: 205 +-- Name: users_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres +-- + +SELECT pg_catalog.setval('public.users_id_seq', 8, true); + +ALTER TABLE ONLY public.products + ADD CONSTRAINT products_pkey PRIMARY KEY (id); + + +-- +-- TOC entry 3129 (class 2606 OID 16682) +-- Name: publishers publishers_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.publishers + ADD CONSTRAINT publishers_pkey PRIMARY KEY (id); + + +-- +-- TOC entry 3131 (class 2606 OID 16684) +-- Name: users users_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_pkey PRIMARY KEY (id); + + +-- Completed on 2021-03-13 20:00:58 PST + +-- +-- PostgreSQL database dump complete +-- diff --git a/project-directions/wave_05.md b/project-directions/wave_05.md index 6fb7bdc98..ceab9fa1f 100644 --- a/project-directions/wave_05.md +++ b/project-directions/wave_05.md @@ -6,4 +6,4 @@ Review the requirements for Wave 01 - 04 * Look for opportunities to refactor As time allows, add custom routes. -* Consider using query params +* Consider using query params \ No newline at end of file From 9a5f3c370b9d0c0302e8cf5b58e694f1ac1910f7 Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Wed, 2 Nov 2022 14:32:21 -0400 Subject: [PATCH 06/16] refactor query params --- app/routes.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index d0eb0dc05..a5c60cc51 100644 --- a/app/routes.py +++ b/app/routes.py @@ -29,16 +29,20 @@ @planets_bp.route("", methods=["GET"]) def read_planets(): planet_query = Planet.query + name_query = request.args.get("name") if name_query: - planet_query = planet_query.filter(Planet.name.ilike(f"%{name_query}%")) + planet_query = planet_query.filter_by(name=name_query) moon_query = request.args.get("num_moons") + if moon_query: - planet_query = planet_query.filter_by(moons=moon_query) + planet_query = planet_query.filter_by(num_moons=moon_query) + planets_response = [] - planets = Planet.query.all() + planets = planet_query.all() + for planet in planets: planets_response.append({ "id": planet.id, @@ -49,6 +53,7 @@ def read_planets(): if not planets_response: return make_response(jsonify(f"There are no planets named {name_query} planet")) + return jsonify(planets_response) From 24186ec9a1186029705cc78478c234a18525d33a Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Thu, 3 Nov 2022 12:05:32 -0400 Subject: [PATCH 07/16] setup tests --- app/__init__.py | 22 +++++++++++++----- app/tests/tests/__init__.py | 0 app/tests/tests/conftest.py | 42 ++++++++++++++++++++++++++++++++++ app/tests/tests/test_routes.py | 9 ++++++++ 4 files changed, 67 insertions(+), 6 deletions(-) create mode 100644 app/tests/tests/__init__.py create mode 100644 app/tests/tests/conftest.py create mode 100644 app/tests/tests/test_routes.py diff --git a/app/__init__.py b/app/__init__.py index 65964692d..9eb29c8e4 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,23 +1,33 @@ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate +from dotenv import load_dotenv +import os + + +load_dotenv() db = SQLAlchemy() migrate = Migrate() - -def create_app(test_config = None): +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_DATABASE_URI'] = os.environ.get( + "SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") db.init_app(app) migrate.init_app(app, db) + from app.models.planet import Planet + from .routes import planets_bp app.register_blueprint(planets_bp) - from app.models.planet import Planet - - return app + return app \ No newline at end of file diff --git a/app/tests/tests/__init__.py b/app/tests/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/tests/tests/conftest.py b/app/tests/tests/conftest.py new file mode 100644 index 000000000..bc7f274d5 --- /dev/null +++ b/app/tests/tests/conftest.py @@ -0,0 +1,42 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished +from app.models.planet import Planet + + +@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() + + +@pytest.fixture +def two_saved_planets(app): + + mercury = Planet( + name="Mercury", + description="distance_from_sun: 36.04 million mi", + num_moons=0) + + venus = Planet(name="Venus", + description="distance_from_sun: 67.24 million mi", + num_moons=0) + db.session.add_all([mercury, venus]) + + db.session.commit() \ No newline at end of file diff --git a/app/tests/tests/test_routes.py b/app/tests/tests/test_routes.py new file mode 100644 index 000000000..7d4c51069 --- /dev/null +++ b/app/tests/tests/test_routes.py @@ -0,0 +1,9 @@ +from app.models.planet import Planet + +def test_get_all_planets_with_empty_db_return_empty_list(client): + response = client.get('/planets') + + response_body = response.get_json() + + assert response_body == [] + assert response.status_code == 200 \ No newline at end of file From 85b6ecc67e3753d8d79abe211349a7bb4ab9183f Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Thu, 3 Nov 2022 22:07:18 -0400 Subject: [PATCH 08/16] moved test files into new test folder --- app/__init__.py | 8 ++++---- {app/tests/tests => new_tests_folder}/__init__.py | 0 {app/tests/tests => new_tests_folder}/conftest.py | 5 +++-- {app/tests/tests => new_tests_folder}/test_routes.py | 0 4 files changed, 7 insertions(+), 6 deletions(-) rename {app/tests/tests => new_tests_folder}/__init__.py (100%) rename {app/tests/tests => new_tests_folder}/conftest.py (95%) rename {app/tests/tests => new_tests_folder}/test_routes.py (100%) diff --git a/app/__init__.py b/app/__init__.py index 9eb29c8e4..a5f1fba79 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,21 +4,21 @@ from dotenv import load_dotenv import os - -load_dotenv() - db = SQLAlchemy() migrate = Migrate() +load_dotenv() + def create_app(test_config=None): app = Flask(__name__) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 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") diff --git a/app/tests/tests/__init__.py b/new_tests_folder/__init__.py similarity index 100% rename from app/tests/tests/__init__.py rename to new_tests_folder/__init__.py diff --git a/app/tests/tests/conftest.py b/new_tests_folder/conftest.py similarity index 95% rename from app/tests/tests/conftest.py rename to new_tests_folder/conftest.py index bc7f274d5..df5f7d4a0 100644 --- a/app/tests/tests/conftest.py +++ b/new_tests_folder/conftest.py @@ -34,9 +34,10 @@ def two_saved_planets(app): description="distance_from_sun: 36.04 million mi", num_moons=0) - venus = Planet(name="Venus", + venus = Planet( + name="Venus", description="distance_from_sun: 67.24 million mi", num_moons=0) + db.session.add_all([mercury, venus]) - db.session.commit() \ No newline at end of file diff --git a/app/tests/tests/test_routes.py b/new_tests_folder/test_routes.py similarity index 100% rename from app/tests/tests/test_routes.py rename to new_tests_folder/test_routes.py From f9482e77d645f36f323eec428e5134ddd734405a Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Thu, 3 Nov 2022 22:08:38 -0400 Subject: [PATCH 09/16] renamed new test folder --- {new_tests_folder => tests}/__init__.py | 0 {new_tests_folder => tests}/conftest.py | 0 {new_tests_folder => tests}/test_routes.py | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {new_tests_folder => tests}/__init__.py (100%) rename {new_tests_folder => tests}/conftest.py (100%) rename {new_tests_folder => tests}/test_routes.py (100%) diff --git a/new_tests_folder/__init__.py b/tests/__init__.py similarity index 100% rename from new_tests_folder/__init__.py rename to tests/__init__.py diff --git a/new_tests_folder/conftest.py b/tests/conftest.py similarity index 100% rename from new_tests_folder/conftest.py rename to tests/conftest.py diff --git a/new_tests_folder/test_routes.py b/tests/test_routes.py similarity index 100% rename from new_tests_folder/test_routes.py rename to tests/test_routes.py From 35839a7e97d2ca08bfd62351b8fb5c000cf08ba2 Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Fri, 4 Nov 2022 16:34:40 -0400 Subject: [PATCH 10/16] modified GET all route to return empty list if no planets. Added test to GET all planets --- app/routes.py | 3 --- tests/conftest.py | 2 ++ tests/test_routes.py | 23 ++++++++++++++++++++++- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index a5c60cc51..d188c9667 100644 --- a/app/routes.py +++ b/app/routes.py @@ -51,9 +51,6 @@ def read_planets(): "number of moons": planet.num_moons }) - if not planets_response: - return make_response(jsonify(f"There are no planets named {name_query} planet")) - return jsonify(planets_response) diff --git a/tests/conftest.py b/tests/conftest.py index df5f7d4a0..4b8d0edc0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -30,11 +30,13 @@ def client(app): def two_saved_planets(app): mercury = Planet( + id=1, name="Mercury", description="distance_from_sun: 36.04 million mi", num_moons=0) venus = Planet( + id=2, name="Venus", description="distance_from_sun: 67.24 million mi", num_moons=0) diff --git a/tests/test_routes.py b/tests/test_routes.py index 7d4c51069..09c250fa2 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -2,8 +2,29 @@ def test_get_all_planets_with_empty_db_return_empty_list(client): response = client.get('/planets') - response_body = response.get_json() assert response_body == [] + assert response.status_code == 200 + + +def test_get_all_planets(client, two_saved_planets): + response = client.get('/planets') + response_body = response.get_json() + + mercury = { + "id": 1, + "name": "Mercury", + "description": "distance_from_sun: 36.04 million mi", + "number of moons": 0 + } + + venus = { + "id": 2, + "name": "Venus", + "description": "distance_from_sun: 67.24 million mi", + "number of moons": 0 + } + + assert response_body == [mercury, venus] assert response.status_code == 200 \ No newline at end of file From 875e44eea1e520fba03358b87ef59490a3fce43c Mon Sep 17 00:00:00 2001 From: Sika Sarpong <50897076+sikasarp@users.noreply.github.com> Date: Sat, 5 Nov 2022 16:40:58 -0700 Subject: [PATCH 11/16] added test_get_one_planet --- tests/test_routes.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/test_routes.py b/tests/test_routes.py index 09c250fa2..a99f6af9e 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -27,4 +27,24 @@ def test_get_all_planets(client, two_saved_planets): } assert response_body == [mercury, venus] - assert response.status_code == 200 \ No newline at end of file + assert response.status_code == 200 + + +def test_get_one_planet(client, two_saved_planets): + # Act + response = client.get("/planets/2") + response_body = response.get_json() + + venus = { + "id": 2, + "name": "Venus", + "description": "distance_from_sun: 67.24 million mi", + "number of moons": 0 + } + + + # Assert + assert response.status_code == 200 + + assert response_body == venus + From e6ac6a416ddda989ae39265297168f37f85b5e2a Mon Sep 17 00:00:00 2001 From: Tazmeen Date: Sun, 6 Nov 2022 15:22:12 -0500 Subject: [PATCH 12/16] finished post and test_get_one_planet_not_in_db tests --- app/__init__.py | 2 +- app/models/planet.py | 3 +- ..._adds_planet_model.py => 9c26f6058a3e_.py} | 8 ++--- tests/test_routes.py | 29 +++++++++++++++++-- 4 files changed, 33 insertions(+), 9 deletions(-) rename migrations/versions/{e5efce9ac694_adds_planet_model.py => 9c26f6058a3e_.py} (86%) diff --git a/app/__init__.py b/app/__init__.py index a5f1fba79..8288e30a4 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -24,7 +24,7 @@ def create_app(test_config=None): db.init_app(app) migrate.init_app(app, db) - + from app.models.planet import Planet from .routes import planets_bp diff --git a/app/models/planet.py b/app/models/planet.py index 1b9c0501a..c0cf2feea 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,7 +1,8 @@ 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) - num_moons = db.Column(db.Integer) \ No newline at end of file + num_moons = db.Column(db.Integer) diff --git a/migrations/versions/e5efce9ac694_adds_planet_model.py b/migrations/versions/9c26f6058a3e_.py similarity index 86% rename from migrations/versions/e5efce9ac694_adds_planet_model.py rename to migrations/versions/9c26f6058a3e_.py index 74299ab65..2f322809d 100644 --- a/migrations/versions/e5efce9ac694_adds_planet_model.py +++ b/migrations/versions/9c26f6058a3e_.py @@ -1,8 +1,8 @@ -"""adds Planet model +"""empty message -Revision ID: e5efce9ac694 +Revision ID: 9c26f6058a3e Revises: -Create Date: 2022-11-01 10:50:27.983178 +Create Date: 2022-11-06 14:47:39.331094 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = 'e5efce9ac694' +revision = '9c26f6058a3e' down_revision = None branch_labels = None depends_on = None diff --git a/tests/test_routes.py b/tests/test_routes.py index a99f6af9e..d4f72917a 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -1,5 +1,6 @@ from app.models.planet import Planet + def test_get_all_planets_with_empty_db_return_empty_list(client): response = client.get('/planets') response_body = response.get_json() @@ -28,8 +29,8 @@ def test_get_all_planets(client, two_saved_planets): assert response_body == [mercury, venus] assert response.status_code == 200 - - + + def test_get_one_planet(client, two_saved_planets): # Act response = client.get("/planets/2") @@ -42,9 +43,31 @@ def test_get_one_planet(client, two_saved_planets): "number of moons": 0 } - # Assert assert response.status_code == 200 assert response_body == venus + +def test_get_one_planet_not_in_db(client): + response = client.get('/planets/3') + response_body = response.get_json() + + assert response_body == {"message": f"planet 3 not found"} + assert response.status_code == 404 + + +def test_post_planet_returns_201(client): + response = client.post("/planets", json={"name": "Pluto", + "description": "distance_from_sun: 3.70 billion mi", + "num_moons": 5}) + response_body = response.get_json() + + assert response.status_code == 201 + #assert response_body == 'Planet Pluto successfully created' + + new_planet = Planet.query.get(1) + assert new_planet + assert new_planet.name == "Pluto" + assert new_planet.description == "distance_from_sun: 3.70 billion mi" + assert new_planet.num_moons == 5 From a08266a51d18e66b35a1c3d5886d39c549c401c8 Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Mon, 7 Nov 2022 12:34:18 -0500 Subject: [PATCH 13/16] added jsonify to post method response body --- app/routes.py | 3 +-- tests/test_routes.py | 10 ++++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index d188c9667..52f7925b6 100644 --- a/app/routes.py +++ b/app/routes.py @@ -64,8 +64,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"]) diff --git a/tests/test_routes.py b/tests/test_routes.py index d4f72917a..52e4e90ff 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -58,13 +58,15 @@ def test_get_one_planet_not_in_db(client): def test_post_planet_returns_201(client): - response = client.post("/planets", json={"name": "Pluto", - "description": "distance_from_sun: 3.70 billion mi", - "num_moons": 5}) + response = client.post("/planets", json= + {"name": "Pluto", + "description": "distance_from_sun: 3.70 billion mi", + "num_moons": 5}) + response_body = response.get_json() assert response.status_code == 201 - #assert response_body == 'Planet Pluto successfully created' + assert response_body == 'Planet Pluto successfully created' new_planet = Planet.query.get(1) assert new_planet From c0966c296176a9b1ac6a92eff8cfc55a05c1767d Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Mon, 7 Nov 2022 12:46:21 -0500 Subject: [PATCH 14/16] removed old comments of hard coded planet objects --- app/routes.py | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/app/routes.py b/app/routes.py index 52f7925b6..5639f89b7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -2,30 +2,8 @@ from app.models.planet import Planet from flask import Blueprint, jsonify, make_response, request, abort - -# class Planet: -# def __init__(self, id, name, description, num_moons): -# self.id = id -# self.name = name -# self.description = description -# self.num_moons = num_moons - - -# PLANETS = [ -# Planet(1, 'Mercury', {"distance_from_sun": "36.04 million mi"}, 0), -# Planet(2, 'Venus', {"distance_from_sun": "67.24 million mi"}, 0), -# Planet(3, 'Earth', {"distance_from_sun": "92.96 million mi"}, 1), -# Planet(4, 'Mars', {"distance_from_sun": "141.60 million mi"}, 2), -# Planet(5, 'Jupiter', {"distance_from_sun": "483.80 million mi"}, 80), -# Planet(6, 'Saturn', {"distance_from_sun": "890.8 million mi"}, 83), -# Planet(7, 'Uranus', {"distance_from_sun": "1.784 billion mi"}, 27), -# Planet(8, 'Neptune', {"distance_from_sun": "2.793 billion mi"}, 14), -# Planet(9, 'Pluto', {"distance_from_sun": "3.70 billion mi"}, 5), -# ] - planets_bp = Blueprint("planets", __name__, url_prefix="/planets") - @planets_bp.route("", methods=["GET"]) def read_planets(): planet_query = Planet.query From 6ff90159552cb33aea51e5883e9e135ff08dc4ac Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Mon, 7 Nov 2022 12:56:07 -0500 Subject: [PATCH 15/16] added tests for to_dict --- tests/test_routes.py | 62 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/tests/test_routes.py b/tests/test_routes.py index 52e4e90ff..ec56820f7 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -73,3 +73,65 @@ def test_post_planet_returns_201(client): assert new_planet.name == "Pluto" assert new_planet.description == "distance_from_sun: 3.70 billion mi" assert new_planet.num_moons == 5 + + +def test_get_all_planets_with_two_records(client, two_saved_planets): + response = client.get("/planets") + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 2 + assert response_body[0] == { + "id": 1, + "name": "Mercury", + "description": "distance_from_sun: 36.04 million mi", + "number of moons": 0 + } + assert response_body[1] == { + "id": 2, + "name": "Venus", + "description": "distance_from_sun: 67.24 million mi", + "number of moons": 0 + } + + +def test_get_all_planets_with_name_query_matching_none(client, two_saved_planets): + data = {'name': 'Anything'} + response = client.get("/planets", query_string = data) + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == [] + + +def test_get_all_planets_with_name_query_matching_one(client, two_saved_planets): + data = {'name': 'Mercury'} + response = client.get("/planets", query_string = data) + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 1 + assert response_body[0] == { + "id": 1, + "name": "Mercury", + "description": "distance_from_sun: 36.04 million mi", + "number of moons": 0 + } + + +def test_get_one_planet_id_not_found(client, two_saved_planets): + # Act + response = client.get("/planets/3") + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body == {"message":"planet 3 not found"} + + +def test_get_one_planet_id_invalid(client, two_saved_planets): + response = client.get("/planets/monkey") + response_body = response.get_json() + + assert response.status_code == 400 + assert response_body == {"message":"planet monkey invalid"} From b18552b09f35d415d94ab55c6159f9938aa35db6 Mon Sep 17 00:00:00 2001 From: Nicole Mejia Date: Mon, 7 Nov 2022 13:13:49 -0500 Subject: [PATCH 16/16] added to_dict to planet.py and refactored routes --- app/models/planet.py | 12 ++++++- app/routes.py | 14 ++------- tests/test_models.py | 75 ++++++++++++++++++++++++++++++++++++++++++++ tests/test_routes.py | 12 +++---- 4 files changed, 94 insertions(+), 19 deletions(-) create mode 100644 tests/test_models.py diff --git a/app/models/planet.py b/app/models/planet.py index c0cf2feea..648008e79 100644 --- a/app/models/planet.py +++ b/app/models/planet.py @@ -1,8 +1,18 @@ 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) num_moons = db.Column(db.Integer) + + + def to_dict(self): + planet_as_dict = {} + planet_as_dict["id"] = self.id + planet_as_dict["name"] = self.name + planet_as_dict["description"] = self.description + planet_as_dict["num_moons"] = self.num_moons + + return planet_as_dict + diff --git a/app/routes.py b/app/routes.py index 5639f89b7..0bb42933f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -22,12 +22,7 @@ def read_planets(): planets = planet_query.all() for planet in planets: - planets_response.append({ - "id": planet.id, - "name": planet.name, - "description": planet.description, - "number of moons": planet.num_moons - }) + planets_response.append(planet.to_dict()) return jsonify(planets_response) @@ -49,12 +44,7 @@ def create_planet(): def get_one_planet(planet_id): planet = validate_planet(planet_id) - return { - "id": planet.id, - "name": planet.name, - "description": planet.description, - "number of moons": planet.num_moons - } + return planet.to_dict() def validate_planet(planet_id): diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 000000000..a05ba89e1 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,75 @@ +from app.models.planet import Planet + +def test_to_dict_no_missing_data(): + test_data = Planet(id = 1, + name="Mercury", + description="distance_from_sun: 36.04 million mi", + num_moons=0) + + result = test_data.to_dict() + + assert len(result) == 4 + assert result["id"] == 1 + assert result["name"] == "Mercury" + assert result["description"] == "distance_from_sun: 36.04 million mi" + assert result["num_moons"] == 0 + + +def test_to_dict_missing_id(): + test_data = Planet( + name="Mercury", + description="distance_from_sun: 36.04 million mi", + num_moons=0) + + result = test_data.to_dict() + + assert len(result) == 4 + assert result["id"] is None + assert result["name"] == "Mercury" + assert result["description"] == "distance_from_sun: 36.04 million mi" + assert result["num_moons"] == 0 + + +def test_to_dict_missing_title(): + test_data = Planet( + id=1, + description="distance_from_sun: 36.04 million mi", + num_moons=0) + + # Act + result = test_data.to_dict() + + # Assert + assert len(result) == 4 + assert result["id"] == 1 + assert result["name"] is None + assert result["description"] == "distance_from_sun: 36.04 million mi" + assert result["num_moons"] == 0 + + +def test_to_dict_missing_description(): + test_data = Planet(id = 1, + name="Mercury", + num_moons=0) + + result = test_data.to_dict() + + assert len(result) == 4 + assert result["id"] == 1 + assert result["name"] == "Mercury" + assert result["description"] is None + assert result["num_moons"] == 0 + + +def test_to_dict_missing_num_moons(): + test_data = Planet(id = 1, + name="Mercury", + description="distance_from_sun: 36.04 million mi") + + result = test_data.to_dict() + + assert len(result) == 4 + assert result["id"] == 1 + assert result["name"] == "Mercury" + assert result["description"] == "distance_from_sun: 36.04 million mi" + assert result["num_moons"] is None \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py index ec56820f7..32ed7f12b 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -17,14 +17,14 @@ def test_get_all_planets(client, two_saved_planets): "id": 1, "name": "Mercury", "description": "distance_from_sun: 36.04 million mi", - "number of moons": 0 + "num_moons": 0 } venus = { "id": 2, "name": "Venus", "description": "distance_from_sun: 67.24 million mi", - "number of moons": 0 + "num_moons": 0 } assert response_body == [mercury, venus] @@ -40,7 +40,7 @@ def test_get_one_planet(client, two_saved_planets): "id": 2, "name": "Venus", "description": "distance_from_sun: 67.24 million mi", - "number of moons": 0 + "num_moons": 0 } # Assert @@ -85,13 +85,13 @@ def test_get_all_planets_with_two_records(client, two_saved_planets): "id": 1, "name": "Mercury", "description": "distance_from_sun: 36.04 million mi", - "number of moons": 0 + "num_moons": 0 } assert response_body[1] == { "id": 2, "name": "Venus", "description": "distance_from_sun: 67.24 million mi", - "number of moons": 0 + "num_moons": 0 } @@ -115,7 +115,7 @@ def test_get_all_planets_with_name_query_matching_one(client, two_saved_planets) "id": 1, "name": "Mercury", "description": "distance_from_sun: 36.04 million mi", - "number of moons": 0 + "num_moons": 0 }