diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..b0b05851e 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,32 @@ 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 + + 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 app.routes import planets_bp + app.register_blueprint(planets_bp) 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..0bfc5cc3e --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,18 @@ +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, nullable=False) + description = db.Column(db.String, nullable=False) + mass = db.Column(db.Numeric(precision=16, scale=3), nullable=False) + + def to_dict(self): + return { + 'id': self.id, + 'name': self.name, + 'description': self.description, + 'mass': self.mass, + } + \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..8329b68d7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,96 @@ -from flask import Blueprint +from flask import Blueprint, jsonify, abort, make_response, request +from app.models.planet import Planet +from app import db + +planets_bp = Blueprint('planets', __name__, url_prefix='/planets') + +@planets_bp.route("", methods=['POST']) +def create_planet(): + request_body = request.get_json() + new_planet = Planet( + name = request_body["name"], + description = request_body["description"], + mass = request_body["mass"], + ) + + db.session.add(new_planet) + db.session.commit() + + message = f"New planet {new_planet.name} successfully created, biatch!" + + return make_response(message, 201) + +@planets_bp.route("", methods=["GET"]) +def get_planets(): + mass = request.args.get("mass") + + planets = Planet.query + + if mass: + planets = planets.filter_by(mass=mass) + + planets = planets.all() + + request_body = [] + for planet in planets: + request_body.append( + dict( + id=planet.id, + name=planet.name, + description=planet.description, + mass=planet.mass + ) + ) + return jsonify(request_body), 200 + +def validate_planet(planet_id): + try: + planet_id = int(planet_id) + except: + abort(make_response({"message": f"Planet {planet_id} is invalid, sucker!"}, 400)) + + planet = Planet.query.get(planet_id) + + if not planet: + abort(make_response({"message": f"Planet {planet_id} was not found, sucker!"}, 404)) + + return planet + +@planets_bp.route("/", methods=['GET']) +def read_one_planet(planet_id): + planet = validate_planet(planet_id) + return { + "id" : planet.id, + "name": planet.name, + "description": planet.description, + "mass": planet.mass + } + +@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.mass = request_body["mass"] + + db.session.commit() + + message = f"Planet {planet} succesfully updated, biatch!" + + return make_response({"message": message}, 200) + +@planets_bp.route("/", methods=['DELETE']) +def delete_planet(planet_id): + planet = validate_planet(planet_id) + + db.session.delete(planet) + db.session.commit() + + message = f"Planet {planet} succesfully deleted, biatch!" + + return make_response({"message": message}, 200) + + diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..0e0484415 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..ec9d45c26 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# 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,flask_migrate + +[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 + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[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..89f80b211 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,110 @@ +import logging +from logging.config import fileConfig + +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') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except TypeError: + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# 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', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# 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 get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +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=get_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 = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_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/project-directions/wave_06.md b/project-directions/wave_06.md index 7d854f465..6a74fea86 100644 --- a/project-directions/wave_06.md +++ b/project-directions/wave_06.md @@ -1,3 +1,24 @@ + + + +## Code Coverage + +Check your code coverage using `pytest-cov`. Review the [code coverage exercise](https://github.com/adaGold/code-coverage-exercise) on how to use `pytest-cov` to generate a code coverage report. We will need to change the directory where the application code is located from `student` to `app`. + +`pytest --cov=app --cov-report html --cov-report term` + +For this project, we will not expect to have high test coverage because we have not tested all of our CRUD routes. Still, it is helpful to practice checking coverage and reading reports of the code which detail the code that is tested, and the code that is not tested. + + + + + + + + + + + # Wave 06: Writing Tests ## Setup diff --git a/requirements.txt b/requirements.txt index ae59e7b55..1bb1716f0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,27 +1,105 @@ -alembic==1.5.4 -autopep8==1.5.5 -blinker==1.4 -certifi==2020.12.5 -chardet==4.0.0 -click==7.1.2 -Flask==1.1.2 -Flask-Migrate==2.6.0 -Flask-SQLAlchemy==2.4.4 -idna==2.10 -itsdangerous==1.1.0 -Jinja2==2.11.3 -Mako==1.1.4 -MarkupSafe==1.1.1 -psycopg2-binary==2.9.5 -pycodestyle==2.6.0 -pytest==7.3.1 -pytest-cov==2.12.1 -python-dateutil==2.8.1 -python-dotenv==0.15.0 -python-editor==1.0.4 -requests==2.25.1 -six==1.15.0 -SQLAlchemy==1.3.23 -toml==0.10.2 -urllib3==1.26.4 -Werkzeug==1.0.1 +alembic==1.10.4 +anyio==3.6.2 +appnope==0.1.3 +argon2-cffi==21.3.0 +argon2-cffi-bindings==21.2.0 +arrow==1.2.3 +asttokens==2.2.1 +attrs==22.2.0 +backcall==0.2.0 +beautifulsoup4==4.12.0 +bleach==6.0.0 +blinker==1.6.2 +certifi==2022.12.7 +cffi==1.15.1 +charset-normalizer==3.0.1 +click==8.1.3 +comm==0.1.3 +debugpy==1.6.6 +decorator==5.1.1 +defusedxml==0.7.1 +executing==1.2.0 +fastjsonschema==2.16.3 +Flask==2.2.3 +Flask-Migrate==4.0.4 +Flask-SQLAlchemy==3.0.3 +fqdn==1.5.1 +idna==3.4 +iniconfig==2.0.0 +ipykernel==6.22.0 +ipython==8.11.0 +ipython-genutils==0.2.0 +ipywidgets==8.0.6 +isoduration==20.11.0 +itsdangerous==2.1.2 +jedi==0.18.2 +Jinja2==3.1.2 +jsonpointer==2.3 +jsonschema==4.17.3 +jupyter==1.0.0 +jupyter-console==6.6.3 +jupyter-events==0.6.3 +jupyter_client==8.1.0 +jupyter_core==5.3.0 +jupyter_server==2.5.0 +jupyter_server_terminals==0.4.4 +jupyterlab-pygments==0.2.2 +jupyterlab-widgets==3.0.7 +Mako==1.2.4 +MarkupSafe==2.1.2 +matplotlib-inline==0.1.6 +mistune==2.0.5 +nbclassic==0.5.3 +nbclient==0.7.2 +nbconvert==7.2.10 +nbformat==5.8.0 +nest-asyncio==1.5.6 +notebook==6.5.3 +notebook_shim==0.2.2 +packaging==23.0 +pandocfilters==1.5.0 +parso==0.8.3 +pexpect==4.8.0 +pickleshare==0.7.5 +platformdirs==3.2.0 +pluggy==1.0.0 +prometheus-client==0.16.0 +prompt-toolkit==3.0.38 +psutil==5.9.4 +psycopg2-binary==2.9.6 +ptyprocess==0.7.0 +pure-eval==0.2.2 +pycparser==2.21 +Pygments==2.14.0 +pyrsistent==0.19.3 +pytest==7.2.2 +python-dateutil==2.8.2 +python-dotenv==1.0.0 +python-json-logger==2.0.7 +PyYAML==6.0 +pyzmq==25.0.2 +qtconsole==5.4.1 +QtPy==2.3.1 +requests==2.28.2 +rfc3339-validator==0.1.4 +rfc3986-validator==0.1.1 +Send2Trash==1.8.0 +six==1.16.0 +sniffio==1.3.0 +soupsieve==2.4 +SQLAlchemy==2.0.11 +stack-data==0.6.2 +terminado==0.17.1 +tinycss2==1.2.1 +tornado==6.2 +traitlets==5.9.0 +typing_extensions==4.5.0 +uri-template==1.2.0 +urllib3==1.26.14 +wcwidth==0.2.6 +webcolors==1.13 +webencodings==0.5.1 +websocket-client==1.5.1 +Werkzeug==2.2.3 +widgetsnbextension==4.0.7 +wonderwords==2.2.0 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..0325fc2a1 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,43 @@ +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({"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 one_planet(app): + return { + "name" : "test_name_1", + "description" : "test_description_1", + "mass" : 1.000} + + +@pytest.fixture +def get_planets(app): + test_planet_2 = Planet(name = "test_name_2", description = "test_description_2", mass = 2.000) + test_planet_3 = Planet(name = "test_name_3", description = "test_description_3", mass = 3.000) + + test_planets = [test_planet_2, test_planet_3] + + db.session.add_all(test_planets) + db.session.commit() + + return test_planets \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..29885cbc5 --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,78 @@ +from app.models.planet import Planet + +def test_get_all_returns_empty_list_when_database_is_empty(client): + response = client.get("/planets") + + assert response.status_code == 200 + assert response.get_json() == [] + + +def test_get_one_planet_returns_planet(client, get_planets): + response = client.get(f"/planets/1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == {"id" : 1, "name" : "test_name_2", "description" : "test_description_2", "mass" : "2.000"} + + +def test_create_planet_happy_path(client): + EXPECTED_PLANET = { + "name": "test_name", + "description": "test_description", + "mass": 1, + } + + response = client.post("/planets", json=EXPECTED_PLANET) + response_body = response.get_data(as_text=True) + + actual_planet = Planet.query.get(1) + assert response.status_code == 201 + assert response_body == f"New planet {EXPECTED_PLANET['name']} successfully created, biatch!" + assert actual_planet.name == EXPECTED_PLANET["name"] + assert actual_planet.description == EXPECTED_PLANET["description"] + assert actual_planet.mass == EXPECTED_PLANET["mass"] + + +def test_get_none_existing_planet_returns_404(client, get_planets): + response = client.get("/planets/404") + + response_body = response.get_json() + + assert response.status_code == 404 + assert response_body == {'message': 'Planet 404 was not found, sucker!'} + +def test_get_invalid_planet_returns_400(client, get_planets): + response = client.get("/planets/noob") + + response_body = response.get_json() + + assert response.status_code == 400 + assert response_body == {'message': 'Planet noob is invalid, sucker!'} + +def test_get_all_planets_returns_array_of_planets_and_200(client, get_planets): + response = client.get("/planets") + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 2 + assert response_body == [{"id" : 1, "name" : "test_name_2", "description" : "test_description_2", "mass" : "2.000"}, + {"id" : 2, "name" : "test_name_3", "description" : "test_description_3", "mass" : "3.000"}] + +def test_delete_one_planet(client, get_planets): + response = client.delete("/planets/1") + response_body = response.get_json() + + assert response.status_code == 200 + assert response_body == {'message': 'Planet succesfully deleted, biatch!'} + +def test_update_one_planet(client, get_planets, one_planet): + response = client.put("/planets/2", json=one_planet) + response_body = response.get_json() + + response_array = client.get("/planets") + updated_array = response_array.get_json() + + assert response.status_code == 200 + assert response_body == {'message': 'Planet succesfully updated, biatch!'} + assert updated_array == [{'id': 1, 'name': 'test_name_2', 'description': 'test_description_2','mass': '2.000'}, + {'id': 2, 'name': 'test_name_1', 'description': 'test_description_1', 'mass': '1.000'}] \ No newline at end of file