diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..0abe0d353 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,34 @@ 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): +def create_app(test_config = None): app = Flask(__name__) + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + + if test_config: + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") + app.config["Testing"] = True + else: + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI") + + from app.models.planet import Planet - return app + db.init_app(app) + migrate.init_app(app, db) + + from app.models.planet import Planet + from app.models.moon import Moon + + from .routes.planet_routes import planets_bp + app.register_blueprint(planets_bp) + + from .routes.moon_routes import moons_bp + app.register_blueprint(moons_bp) + return app \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/moon.py b/app/models/moon.py new file mode 100644 index 000000000..1a610a61f --- /dev/null +++ b/app/models/moon.py @@ -0,0 +1,24 @@ +from app import db + +class Moon(db.Model): + id = db.Column(db.Integer, primary_key = True, autoincrement = True) + name = db.Column(db.String, nullable = False) + size = db.Column(db.Float, nullable = False) + description = db.Column(db.String, nullable = False) + planet_id = db.Column(db.Integer, db.ForeignKey("planet.id")) + planet = db.relationship("Planet", back_populates="moons") + + def to_dict(self): + moon_as_dict = {} + moon_as_dict["id"] = self.id + moon_as_dict["name"] = self.name + moon_as_dict["size"] = self.size + moon_as_dict["description"] = self.description + return moon_as_dict + + @classmethod + def from_dict(cls,moon_data): + new_moon = Moon(name=moon_data["name"], + size=float(moon_data["size"]), + description=moon_data["description"]) + return new_moon \ No newline at end of file diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..bb7b7c0a6 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,28 @@ +from app import db + +class Planet(db.Model): + id = db.Column(db.Integer, primary_key = True, autoincrement = True) + name = db.Column(db.String, nullable = False) + length_of_year = db.Column(db.Integer, nullable = False) + description = db.Column(db.String, nullable = False) + moons = db.relationship("Moon", back_populates="planet") + + def to_dict(self): + planet_as_dict = {} + planet_as_dict["id"] = self.id + planet_as_dict["name"] = self.name + planet_as_dict["length_of_year"] = self.length_of_year + planet_as_dict["description"] = self.description + + moon_names = [] + for moon in self.moons: + moon_names.append(moon.name) + planet_as_dict["moons"] = moon_names + return planet_as_dict + + @classmethod + def from_dict(cls,planet_data): + new_planet = Planet(name=planet_data["name"], + length_of_year=planet_data["length_of_year"], + description=planet_data["description"]) + return new_planet \ No newline at end of file diff --git a/app/routes.py b/app/routes.py deleted file mode 100644 index 8e9dfe684..000000000 --- a/app/routes.py +++ /dev/null @@ -1,2 +0,0 @@ -from flask import Blueprint - diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes/moon_routes.py b/app/routes/moon_routes.py new file mode 100644 index 000000000..530ec2ab6 --- /dev/null +++ b/app/routes/moon_routes.py @@ -0,0 +1,69 @@ +from app import db +from app.models.moon import Moon +from app.models.planet import Planet +from flask import Blueprint, jsonify, abort, make_response, request +from .validate_routes import validate_model, validate_moon_user_input, validate_planet_user_input + +moons_bp = Blueprint("moons_bp", __name__, url_prefix = "/moons") + +# Get all moons info +# /moons +# Return JSON list +@moons_bp.route("", methods = ["GET"]) +def get_all_moons_query(): + moon_query = Moon.query + # Filtering by moon name (return all records which name contains planet_name_query) + moon_name_query = request.args.get("name") + + if moon_name_query: + moon_query = moon_query.filter(Moon.name.ilike(f"%{moon_name_query}%")) + + # Sorting by moon name + sort_by_name_query = request.args.get("sort_by_name") + + if sort_by_name_query == "desc": + moon_query = moon_query.order_by(Moon.name.desc()).all() + elif sort_by_name_query == "asc": + moon_query = moon_query.order_by(Moon.name).all() + + # Sorting by moon size + moon_sort_size_query = request.args.get("sort_by_size") + + if moon_sort_size_query == "desc": + moon_query = moon_query.order_by(Moon.size.desc()).all() + elif sort_by_name_query == "asc": + moon_query = moon_query.order_by(Moon.size).all() + + # Build response + moon_response = [] + for moon in moon_query: + moon_response.append(moon.to_dict()) + + return jsonify(moon_response), 200 + +# Read one moon +# Return one moon info in JSON format +@moons_bp.route("/",methods=["GET"] ) +def get_one_moon(moon_id): + moon = validate_model(Moon, moon_id) + return moon.to_dict() + +# Create one moon +@moons_bp.route("", methods = ["POST"]) +def create_moon(): + moon_value = validate_moon_user_input(request.get_json()) + new_moon = Moon.from_dict(moon_value) + + db.session.add(new_moon) + db.session.commit() + return make_response(jsonify(f"Moon {new_moon.name} successfully created"), 201) + +# Delete moon by id +@moons_bp.route("/",methods=["DELETE"]) +def delete_moon(moon_id): + moon = validate_model(Moon, moon_id) + + db.session.delete(moon) + db.session.commit() + + return make_response(jsonify(f"Moon {moon.id} successfully deleted"), 200) \ No newline at end of file diff --git a/app/routes/planet_routes.py b/app/routes/planet_routes.py new file mode 100644 index 000000000..b3ab7e580 --- /dev/null +++ b/app/routes/planet_routes.py @@ -0,0 +1,150 @@ +from app import db +from app.models.planet import Planet +from app.models.moon import Moon +from .validate_routes import validate_model, validate_moon_user_input, validate_planet_user_input +from flask import Blueprint, jsonify, abort, make_response, request + +planets_bp = Blueprint("planets_bp", __name__, url_prefix = "/planets") + +# Creating new planet +@planets_bp.route("", methods = ["POST"]) +def create_planet(): + planet_value = validate_planet_user_input(request.get_json()) + new_planet = Planet.from_dict(planet_value) + + db.session.add(new_planet) + db.session.commit() + + return make_response(jsonify(f"Planet {new_planet.name} successfully created"), 201) + +# Get all planets info +# Return JSON list +@planets_bp.route("", methods = ["GET"]) +def get_all_planets_query(): + planet_query = Planet.query + + # Filtering by name (return all records which name contains planet_name_query) + planet_name_query = request.args.get("name") + + if planet_name_query: + planet_query = planet_query.filter(Planet.name.ilike(f"%{planet_name_query}%")) + + # Sort + sort_query = request.args.get("sort") + + if sort_query == "name": + planet_query = planet_query.order_by(Planet.name).all() + + if sort_query == "length_of_year": + planet_query = planet_query.order_by(Planet.length_of_year).all() + + planet_response = [] + for planet in planet_query: + planet_response.append(planet.to_dict()) + + return jsonify(planet_response), 200 + +# Read one planet +# Return one planet info in JSON format +@planets_bp.route("/",methods=["GET"] ) +def get_one_planet(planet_id): + planet = validate_model(Planet, planet_id) + return planet.to_dict() + +# Update one planet +@planets_bp.route("/",methods=["PUT"] ) +def update_planet(planet_id): + planet = validate_model(Planet, planet_id) + request_body = validate_planet_user_input(request.get_json()) + + planet.name = request_body["name"] + planet.length_of_year = request_body["length_of_year"] + planet.description = request_body["description"] + + db.session.commit() + message = f"Planet {planet_id} successfully updated" + return make_response(jsonify(message), 200) + +# Delete one planet and all the moons dependent of the planet +@planets_bp.route("/",methods=["DELETE"]) +def delete_planet(planet_id): + planet = validate_model(Planet, planet_id) + + if len(planet.moons)>0: + i = 0 + while i < len(planet.moons): + moon_id = planet.moons[i].id + moon = validate_model(Moon, moon_id) + db.session.delete(moon) + db.session.commit() + i += 1 + + db.session.delete(planet) + db.session.commit() + + return make_response(jsonify(f"Planet {planet.id} successfully deleted"), 200) + +# Add moon info to the planet using planet id +@planets_bp.route("//moons", methods=["POST"]) +def add_new_moon_to_planet(planet_id): + planet = validate_model(Planet, planet_id) + moon_value = validate_moon_user_input(request.get_json()) + + moon = Moon.from_dict(moon_value) + moon.planet_id = planet.id + + db.session.add(moon) + db.session.commit() + + message = f"Moon {moon.name} added to the planet {planet.name}." + return make_response(jsonify(message), 201) + +# Get all moons info for chosen planet (by planet id) +@planets_bp.route("//moons", methods=["GET"]) +def get_all_moons_for_planet(planet_id): + planet = validate_model(Planet, planet_id) + + moons_response = [] + for moon in planet.moons: + moons_response.append(moon.to_dict()) + + return jsonify(moons_response) + +# Get moon by id +# Return one moon info in JSON format +@planets_bp.route("//moons/",methods=["GET"] ) +def get_one_moon_of_planet(planet_id, moon_id): + planet = validate_model(Planet, planet_id) + moon = validate_model(Moon, moon_id) + return moon.to_dict() + +# Update moon info (by moon_id) of the planet using planet_id +@planets_bp.route("//moons/", methods=["POST"]) +def update_moon_of_planet(planet_id, moon_id): + + planet = validate_model(Planet, planet_id) + moon = validate_model(Moon, moon_id) + + request_body = validate_moon_user_input(request.get_json()) + + moon.name = request_body["name"] + moon.size = request_body["size"] + moon.description = request_body["description"] + + db.session.commit() + + message = f"Moon {moon.id} of the planet {planet.name} successfully updated." + return make_response(jsonify(message), 201) + +# Delete moon of the specific planet (using planet_id and moon_id) +@planets_bp.route("//moons/", methods=["DELETE"]) +def delete_moon_of_planet(planet_id, moon_id): + + planet = validate_model(Planet, planet_id) + moon = validate_model(Moon, moon_id) + + db.session.delete(moon) + db.session.commit() + + message = f"Moon {moon.id} of the planet {planet.name} successfully deleted." + return make_response(jsonify(message), 201) \ No newline at end of file diff --git a/app/routes/validate_routes.py b/app/routes/validate_routes.py new file mode 100644 index 000000000..3319ea67a --- /dev/null +++ b/app/routes/validate_routes.py @@ -0,0 +1,56 @@ +from app import db +from app.models.planet import Planet +from app.models.moon import Moon +from flask import Blueprint, jsonify, abort, make_response, request + +# Validating the id of the instance: id needs to be int and exists the instance with the id. +# Returning the valid Class instance if valid id +# Work for Planet and Moon classes +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response(jsonify(f"{cls.__name__} {model_id} invalid"), 400)) + + class_obj = cls.query.get(model_id) + + if not class_obj: + abort(make_response(jsonify(f"{cls.__name__} {model_id} not found"), 404)) + + return class_obj + +# Validating the user input to create or update the table planet +# Returning the valid JSON if valid input +def validate_planet_user_input(planet_value): + + if "name" not in planet_value \ + or not isinstance(planet_value["name"], str) \ + or planet_value["name"] == "" \ + or "length_of_year" not in planet_value \ + or not isinstance(planet_value["length_of_year"], int) \ + or planet_value["length_of_year"] <=0 \ + or "description" not in planet_value \ + or not isinstance(planet_value["description"], str) \ + or planet_value["description"] == "": + + return abort(make_response(jsonify("Invalid request"), 400)) + + return planet_value + +# Validating the user input to create or update the table moon +# Returning the valid JSON if valid input +def validate_moon_user_input(moon_value): + + if "name" not in moon_value \ + or not isinstance(moon_value["name"], str) \ + or moon_value["name"] == "" \ + or "size" not in moon_value \ + or not (isinstance(moon_value["size"], float) or isinstance(moon_value["size"], int)) \ + or moon_value["size"] <=0 \ + or "description" not in moon_value \ + or not isinstance(moon_value["description"], str) \ + or moon_value["description"] == "": + + return abort(make_response(jsonify("Invalid request"), 400)) + + return moon_value \ No newline at end of file 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..fa412e8c3 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,105 @@ +from __future__ import with_statement + +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 + + +# 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(get_engine().url).replace('%', '%%')) +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/migrations/versions/8173d172e151_added_moon_model.py b/migrations/versions/8173d172e151_added_moon_model.py new file mode 100644 index 000000000..e1062d68f --- /dev/null +++ b/migrations/versions/8173d172e151_added_moon_model.py @@ -0,0 +1,44 @@ +"""Added Moon model + +Revision ID: 8173d172e151 +Revises: +Create Date: 2023-01-05 15:31:57.115338 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '8173d172e151' +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=False), + sa.Column('length_of_year', sa.Integer(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('moon', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('size', sa.Float(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('planet_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['planet_id'], ['planet.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('moon') + op.drop_table('planet') + # ### end Alembic commands ### diff --git a/moons_data.csv b/moons_data.csv new file mode 100644 index 000000000..4542ba306 --- /dev/null +++ b/moons_data.csv @@ -0,0 +1,74 @@ +[ + {# Earth Moons + "description": "Earth's Moon is the only place beyond Earth where humans have set foot, so far.", + "size": 1738.1, + "name": "Moon" + }, + {# Mars Moons + "description": "Deimos is the smaller of Mars' two moons.", + "size": 3.9, + "name": "Deimos" + }, + {# Mars Moons + "description": "Phobos was discovered on Aug. 17, 1877 by Asaph Hall.v", + "size": 7.0, + "name": "Phobos" + }, + {# Jupiter Moons + "description": "Io is the most volcanically active world in the solar system.", + "size": 1821.3, + "name": "Io" + }, + {# Jupiter Moons + "description": "Europa is perhaps the most promising place to look for present-day environments suitable for life.", + "size": 1569.0, + "name": "Europa" + }, + {# Jupiter Moons + "description": "Ganymede is the largest moon in our solar system and the only moon known to create its own magnetic field.", + "size": 2634.1, + "name": "Ganymede" + }, + {# Jupiter Moons + "description": "Callisto is among the most heavily cratered objects that orbit the Sun.", + "size": 2410.3, + "name": "Callisto" + }, + {# Saturn Moons + "description": "Enceladus has the whitest, most reflective surface in the solar system.", + "size": 156.65, + "name": "Enceladus" + }, + {# Saturn Moons + "description": "Titan is the only moon in our solar system that has clouds and a dense atmosphere.", + "size": 2575.0, + "name": "Titan" + }, + {# Uranus Moons + "description": "All of Uranus' larger moons, including Ariel, are thought to consist mostly of roughly equal amounts of water ice and silicate rock.", + "size": 359.7, + "name": "Ariel" + }, + {# Uranus Moons + "description": "Oberon is the second largest moon of Uranus.", + "size": 473.1, + "name": "Oberon" + }, + {# Uranus Moons + "description": "Rosalind was discovered by the Voyager 2 science team on 13 January 1986.", + "size": 22.0, + "name": "Rosalind" + } + + #### For Testing + { + "description": "Moon for testing purpose.", + "size": 7000, + "name": "Moon_Test1" + }, + { + "description": "Moon just for testing.", + "size": 6, + "name": "Moon_Test2" + } +] \ No newline at end of file diff --git a/planets_data.csv b/planets_data.csv new file mode 100644 index 000000000..426c31d26 --- /dev/null +++ b/planets_data.csv @@ -0,0 +1,54 @@ +[ + { + "description": "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + "length_of_year": 88, + "name": "Mercury" + }, + { + "description": "Venus spins slowly in the opposite direction from most planets.", + "length_of_year": 225, + "name": "Venus" + }, + { + "description": "Earth — our home planet.", + "length_of_year": 365, + "name": "Earth" + }, + { + "description": "Mars is a dusty, cold, desert world with a very thin atmosphere.", + "length_of_year": 687, + "name": "Mars" + }, + { + "description": "Jupiter is more than twice as massive than the other planets of our solar system combined.", + "length_of_year": 687, + "name": "Jupiter" + }, + { + "description": "Adorned with a dazzling, complex system of icy rings, Saturn is unique in our solar system.", + "length_of_year": 10756, + "name": "Saturn" + }, + { + "description": "Uranus—seventh planet from the Sun—rotates at a nearly 90-degree angle from the plane of its orbit.", + "length_of_year": 30687, + "name": "Uranus" + }, + { + "description": "Neptune—the eighth and most distant major planet orbiting our Sun—is dark, cold and whipped by supersonic winds.", + "length_of_year": 60190, + "name": "Neptune" + } + +#### For Testing + { + "description": "Imaginary planet for testing purpose.", + "length_of_year": 7000, + "name": "Planet_Test1" + }, + { + "description": "Just for testing.", + "length_of_year": 6, + "name": "Planet_Test2" + } +] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index fba2b3e38..b9ada8e61 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,18 +1,26 @@ alembic==1.5.4 +attrs==22.1.0 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 +click==8.1.3 +coverage==6.5.0 +Flask==2.2.2 +Flask-Migrate==4.0.1 +Flask-SQLAlchemy==3.0.2 +greenlet==2.0.1 +gunicorn==20.1.0 idna==2.10 -itsdangerous==1.1.0 -Jinja2==2.11.3 +iniconfig==1.1.1 +itsdangerous==2.1.2 +Jinja2==3.1.2 Mako==1.1.4 -MarkupSafe==1.1.1 +MarkupSafe==2.1.1 +packaging==22.0 +pluggy==1.0.0 psycopg2-binary==2.9.4 +py==1.11.0 pycodestyle==2.6.0 pytest==7.1.1 pytest-cov==2.12.1 @@ -21,7 +29,8 @@ python-dotenv==0.15.0 python-editor==1.0.4 requests==2.25.1 six==1.15.0 -SQLAlchemy==1.3.23 +SQLAlchemy==1.4.46 toml==0.10.2 +tomli==2.0.1 urllib3==1.26.4 -Werkzeug==1.0.1 +Werkzeug==2.2.2 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..aa0dd68d5 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,155 @@ +import pytest +from app import create_app, db +from flask.signals import request_finished +from app.models.planet import Planet +from app.models.moon import Moon + +@pytest.fixture +def app(): + app = create_app(test_config=True) + + @request_finished.connect_via(app) + def expire_session(sender, response, **extra): + db.session.remove() + + with app.app_context(): + db.create_all() + yield app + + with app.app_context(): + db.drop_all() + +@pytest.fixture +def client(app): + return app.test_client() + + +@pytest.fixture +def one_planet(app): + + planet = Planet( + name = "Mercury", + description = "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + length_of_year = 88) + + db.session.add(planet) + db.session.commit() + db.session.refresh(planet, ["id"]) + + return planet + +@pytest.fixture +def one_planet_with_moons(app): + # Moons + moon1 = Moon( + name = "Test1", + description = "Fantasy moon for testing purpose.", + size = 3.5) + moon2 = Moon( + description = "Moon just for testing.", + size = 17.0, + name = "Moon_Test2") + # Planet + planet_mercury = Planet( + name = "Mercury", + description = "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + length_of_year = 88, + moons = [moon1, moon2]) + + db.session.add(planet_mercury) + db.session.commit() + db.session.refresh(planet_mercury, ["id"]) + + return planet_mercury + +@pytest.fixture +def three_planets(app): + planet_mercury = Planet( + name = "Mercury", + description = "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + length_of_year = 88) + planet_venus = Planet( + name = "Venus", + description = "Venus spins slowly in the opposite direction from most planets.", + length_of_year = 225) + planet_earth = Planet( + name = "Earth", + description = "Earth — our home planet.", + length_of_year = 365) + + db.session.add_all([planet_mercury, planet_venus, planet_earth]) + db.session.commit() + +@pytest.fixture +def three_planets_with_moons(app): + # Moons + moon1 = Moon( + description = "Moon1 for testing purpose.", + size = 173.1, + name = "Moon_Test1") + moon2 = Moon( + description = "Moon2 just for testing.", + size = 17, + name = "Moon_Test2") + moon3 = Moon( + description = "Moon3 for testing purpose.", + size = 11, + name = "Moon_Test3") + moon4 = Moon( + description = "Moon4 just for testing.", + size = 19, + name = "Moon_Test4") + # Planets + planet_mercury = Planet( + name = "Mercury", + description = "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + length_of_year = 88, + moons = [moon1, moon2]) + planet_venus = Planet( + name = "Venus", + description = "Venus spins slowly in the opposite direction from most planets.", + length_of_year = 225, + moons = [moon3]) + planet_earth = Planet( + name = "Earth", + description = "Earth — our home planet.", + length_of_year = 365, + moons = [moon4]) + + db.session.add_all([planet_mercury, planet_venus, planet_earth]) + db.session.commit() + +@pytest.fixture +def one_moon(app): + + moon1 = Moon( + name = "Test1", + description = "Fantasy moon for testing purpose.", + size = 3.5) + + db.session.add(moon1) + db.session.commit() + db.session.refresh(moon1, ["id"]) + + return moon1 + +@pytest.fixture +def three_moons(app): + + moon1 = Moon( + name = "Test1", + description = "Fantasy moon for testing purpose.", + size = 3.5) + + moon2 = Moon( + name = "Test2", + description = "Fantasy moon for testing purpose.", + size = 4.0) + + moon3 = Moon( + name = "Test3", + description = "Fantasy moon for testing purpose.", + size = 5.5) + + db.session.add_all([moon1, moon2, moon3]) + db.session.commit() diff --git a/tests/test_moon_routes.py b/tests/test_moon_routes.py new file mode 100644 index 000000000..51daa3535 --- /dev/null +++ b/tests/test_moon_routes.py @@ -0,0 +1,136 @@ +from werkzeug.exceptions import HTTPException +from app.models.moon import Moon +import pytest + +#### POST/ Create moon #### +def test_create_moon_valid_request_return_201(client): + # Act + response = client.post("/moons", json = { + "description": "Fantasy moon for testing purpose.", + "name": "Test1", + "size": 3.6 + }) + response_body = response.get_json() + # Assert + assert response.status_code == 201 + assert response_body == "Moon Test1 successfully created" + +def test_create_moon_invalid_request_empty_name_return_400(client): + # Act + response = client.post("/moons", json = { + "description": "Fantasy moon for testing purpose.", + "size": 3.6 + }) + response_body = response.get_json() + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_create_moon_invalid_request_size_zero_return_400(client): + # Act + response = client.post("/moons", json = { + "description": "Fantasy moon for testing purpose.", + "name": "Test1", + "size": 0 + }) + response_body = response.get_json() + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_create_moon_invalid_request_description_empty_return_400(client): + # Act + response = client.post("/moons", json = { + "name": "Test1", + "size": 3.6 + }) + response_body = response.get_json() + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +#### DELETE/ Delete moon #### +def test_delete_moon_by_id_valid_request_return_success_message(client, one_moon): + # Act + moon_id = one_moon.id + response = client.delete(f"/moons/{moon_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert response_body == f"Moon {moon_id} successfully deleted" + +def test_delete_moon_by_id_invalid_id_return_400(client, one_moon): + # Act + moon_id = "hello" + response = client.delete(f"/moons/{moon_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 400 + assert response_body == f"Moon {moon_id} invalid" + +def test_delete_moon_by_not_existed_id_return_404(client, one_moon): + moon_id = 2 + response = client.delete(f"/moons/{moon_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 404 + assert response_body == f"Moon {moon_id} not found" + +####GET/ Read moon by id#### +def test_get_moon_by_id_return_200(client,one_moon): + # Act + response = client.get("/moons/1") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert response_body == { + "id":1, + "name": "Test1", + "size": 3.5, + "description": "Fantasy moon for testing purpose." + } + +def test_get_moon_by_not_exist_did_return_404(client, one_moon): + # Act + response = client.get("/moons/2") + response_body = response.get_json() + # Assert + assert response.status_code == 404 + assert response_body == "Moon 2 not found" + +def test_get_moon_by_invalid_type_id_return_400(client,one_moon): + # Act + moon_id = "hello" + response = client.get(f"/moons/{moon_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 400 + assert response_body == f"Moon {moon_id} invalid" + +####GET/ Read all moons #### +def test_get_all_moons_return_200(client,three_moons): + # Act + response = client.get("/moons") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert response_body == [ + { + "id":1, + "name": "Test1", + "size": 3.5, + "description": "Fantasy moon for testing purpose." + }, + { + "id":2, + "name": "Test2", + "size": 4.0, + "description": "Fantasy moon for testing purpose." + }, + { + "id":3, + "name": "Test3", + "size": 5.5, + "description": "Fantasy moon for testing purpose." + } + ] diff --git a/tests/test_moons_inside_planet_routes.py b/tests/test_moons_inside_planet_routes.py new file mode 100644 index 000000000..fe1fdc880 --- /dev/null +++ b/tests/test_moons_inside_planet_routes.py @@ -0,0 +1,128 @@ +from werkzeug.exceptions import HTTPException +from app.models.moon import Moon +from app.models.planet import Planet +import pytest + +#### POST/ Create moon for planet #### +def test_create_moon_for_planet_id_valid_request_return_201(client, one_planet): + # Arange + planet_id = one_planet.id + # Act + response = client.post(f"/planets/{planet_id}/moons", json = { + "description": "Fantasy moon for testing purpose.", + "name": "Test1", + "size": 3.6 + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == f"Moon Test1 added to the planet {one_planet.name}." + +def test_create_moon_for_planet_invalid_request_empty_name_return_400(client, one_planet): + # Arange + planet_id = one_planet.id + # Act + response = client.post(f"/planets/{planet_id}/moons", json = { + "description": "Fantasy moon for testing purpose.", + "size": 3.6, + "planet_id": planet_id + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_create_moon_for_planet_invalid_request_size_zero_return_400(client, one_planet): + # Arange + planet_id = one_planet.id + # Act + response = client.post(f"/planets/{planet_id}/moons", json = { + "description": "Fantasy moon for testing purpose.", + "name": "Test1", + "size": 0 + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_create_moon_for_planet_invalid_request_description_empty_return_400(client, one_planet): + # Arange + planet_id = one_planet.id + # Act + response = client.post(f"/planets/{planet_id}/moons", json = { + "name": "Test1", + "size": 3.6 + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +####GET moon inside of planet route#### +def test_get_moon_for_planet_by_id_for_planet_id_return_200(client,three_planets_with_moons): + # Arange + planet_id = 1 + moon_id = 1 + # Act + response = client.get(f"planets/{planet_id}/moons/{moon_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert response_body == { + "id":1, + "name": "Moon_Test1", + "size": 173.1, + "description": "Moon1 for testing purpose." + } + +def test_get_all_moons_for_planet_valid_planet_id_return_200_info_moons(client,three_planets_with_moons): + # Arange + planet_id = 1 + # Act + response = client.get(f"planets/{planet_id}/moons") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert response_body == [ + { + "id":1, + "name": "Moon_Test1", + "size": 173.1, + "description": "Moon1 for testing purpose." + }, + { + "id":2, + "name": "Moon_Test2", + "size": 17.0, + "description": "Moon2 just for testing." + } + ] + +def test_get_all_moons_for_planet_by_not_exist_id_return_404(client, three_planets_with_moons): + # Arange + planet_id = 4 + # Act + response = client.get(f"planets/{planet_id}/moons") + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body == f"Planet {planet_id} not found" + +def test_get_all_moons_for_planet_by_invalid_type_id_return_400(client, three_planets_with_moons): + # Arange + planet_id = "hello" + # Act + response = client.get(f"planets/{planet_id}/moons") + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == f"Planet {planet_id} invalid" + +#### For future can add tests for delete/ update moon_of the planet, add_moon_to_planet_with_moons, etc. \ No newline at end of file diff --git a/tests/test_planet_routes.py b/tests/test_planet_routes.py new file mode 100644 index 000000000..1e4fc7237 --- /dev/null +++ b/tests/test_planet_routes.py @@ -0,0 +1,377 @@ +from werkzeug.exceptions import HTTPException +from app.models.planet import Planet +import pytest + +#### POST/ Create planet #### +def test_create_planet_valid_request_return_201(client): + # Act + response = client.post("/planets", json = { + "description": "Mars is a dusty, cold, desert world with a very thin atmosphere.", + "length_of_year": 687, + "name": "Mars" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == "Planet Mars successfully created" + +def test_create_planet_invalid_request_empty_name_return_400(client): + # Act + response = client.post("/planets", json = { + "name": "", + "description": "This unknown planet is the imaginary planet for purpose of testing.", + "length_of_year": 10}) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_create_planet_invalid_request_lenght_of_year_zero_return_400(client): + # Act + response = client.post("/planets", json = { + "name": "Test", + "description": "This unknown planet is the imaginary planet for purpose of testing.", + "length_of_year": 0}) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_create_planet_invalid_request_lenght_of_year_negative_return_400(client): + # Act + response = client.post("/planets", json = { + 'name': 'Test', + 'description': 'This unknown planet is the imaginary planet for purpose of testing.', + 'length_of_year': -100}) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_create_planet_invalid_request_description_empty_return_400(client): + # Act + response = client.post("/planets", json = { + 'name': 'Test', + 'description': '', + 'length_of_year': 10}) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +#### PUT/ Update planet #### +def test_update_planet_valid_request_return_success_message(client, one_planet): + # Act + planet_id = one_planet.id + response = client.put(f"/planets/{one_planet.id}", json = { + "description": "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + "length_of_year": 88, + "name": "Mercury_updated" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == f"Planet {planet_id} successfully updated" + +def test_update_planet_not_exist_id_return_404(client, one_planet): + # Act + response = client.put("/planets/9", json = { + "description": "Mars is a dusty, cold, desert world with a very thin atmosphere.", + "length_of_year": 687, + "name": "Mars" + }) + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body == f"Planet 9 not found" + +def test_update_planet_invalid_type_id_return_400(client, one_planet): + # Act + planet_id = "hello" + response = client.put(f"/planets/{planet_id}", json = { + "description": "Mars is a dusty, cold, desert world with a very thin atmosphere.", + "length_of_year": 687, + "name": "Mars" + }) + response_body = response.get_json() + # Assert + assert response.status_code == 400 + assert response_body == f"Planet {planet_id} invalid" + +def test_update_planet_invalid_request_empty_name_return_400(client, one_planet): + # Act + response = client.put(f"/planets/{one_planet.id}", json = { + "name": "", + "description": "This unknown planet is the imaginary planet for purpose of testing.", + "length_of_year": 10}) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_update_planet_invalid_request_lenght_of_year_zero_return_400(client, one_planet): + # Act + response = client.put(f"/planets/{one_planet.id}", json = { + "name": "Test", + "description": "This unknown planet is the imaginary planet for purpose of testing.", + "length_of_year": 0}) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_update_planet_invalid_request_lenght_of_year_negative_return_400(client, one_planet): + # Act + response = client.put(f"/planets/{one_planet.id}", json = { + 'name': 'Test', + 'description': 'This unknown planet is the imaginary planet for purpose of testing.', + 'length_of_year': -100}) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +def test_update_planet_invalid_request_description_empty_return_400(client, one_planet): + # Act + response = client.put(f"/planets/{one_planet.id}", json = { + 'name': 'Test', + 'description': '', + 'length_of_year': 10}) + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == "Invalid request" + +#### DELETE/ Delete planet #### +def test_delete_planet_by_id_valid_request_with_zero_moons_return_success_message(client, one_planet): + # Act + planet_id = one_planet.id + response = client.delete(f"/planets/{planet_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert response_body == f"Planet {planet_id} successfully deleted" + +def test_delete_planet_by_id_valid_request_with_two_moons_return_success_message(client, one_planet_with_moons): + # Act + planet_id = one_planet_with_moons.id + response = client.delete(f"/planets/{planet_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 200 + assert response_body == f"Planet {planet_id} successfully deleted" + # Would like to add assert to check that moons deleted too + # dont know how + # will be happy to recieve the feedback :) + +def test_delete_planet_by_invalid_type_id_return_400(client, one_planet): + # Act + planet_id = "hello" + response = client.delete(f"/planets/{planet_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 400 + assert response_body == f"Planet {planet_id} invalid" + +def test_delete_planet_by_not_existed_id_return_404(client, one_planet): + planet_id = 9 + response = client.delete(f"/planets/{planet_id}") + response_body = response.get_json() + # Assert + assert response.status_code == 404 + assert response_body == f"Planet {planet_id} not found" + +#### GET/ Read one planet #### +def test_get_planet_not_exist_id_return_404(client,one_planet): + # Act + response = client.get("/planets/2") + response_body = response.get_json() + + # Assert + assert response.status_code == 404 + assert response_body == f"Planet 2 not found" + +def test_get_planet_invalid_type_id_return_400(client,one_planet): + # Act + planet_id = "hello" + response = client.get(f"/planets/{planet_id}") + response_body = response.get_json() + + # Assert + assert response.status_code == 400 + assert response_body == f"Planet {planet_id} invalid" + +def test_get_planet_without_moons_valid_id_return_planet_info(client,three_planets): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + "id":1, + "name": "Mercury", + "length_of_year": 88, + "description": "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + "moons": [] + } + +def test_get_planet_with_moon_valid_id_return_planet_info(client,one_planet_with_moons): + # Act + planet_id = one_planet_with_moons.id + response = client.get(f"/planets/{planet_id}") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + "id":1, + "name": "Mercury", + "length_of_year": 88, + "description": "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + "moons": ["Test1", "Moon_Test2"] + } + +#### GET/ Read all planets #### +def test_get_all_planets_without_moons_return_planets_info(client,three_planets): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body == [ + { + "id":1, + "name": "Mercury", + "length_of_year": 88, + "description": "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + "moons": [] + }, + { + "id":2, + "name": "Venus", + "length_of_year": 225, + "description": "Venus spins slowly in the opposite direction from most planets.", + "moons": [] + }, + { + "id":3, + "name": "Earth", + "length_of_year": 365, + "description": "Earth — our home planet.", + "moons": [] + } +] + +def test_get_all_planets_with_moons_return_planets_info(client,three_planets_with_moons): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body == [ + { + "id":1, + "name": "Mercury", + "length_of_year": 88, + "description": "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + "moons": ["Moon_Test1", "Moon_Test2"] + }, + { + "id":2, + "name": "Venus", + "length_of_year": 225, + "description": "Venus spins slowly in the opposite direction from most planets.", + "moons": ["Moon_Test3"] + }, + { + "id":3, + "name": "Earth", + "length_of_year": 365, + "description": "Earth — our home planet.", + "moons": ["Moon_Test4"] + } +] + +def test_get_all_planets_with_moons_sorted_by_name_return_planets_info(client,three_planets_with_moons): + # Act + data = {"sort": "name"} + # Act + response = client.get("/planets", query_string = data) + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body == [ + { + "id":3, + "name": "Earth", + "length_of_year": 365, + "description": "Earth — our home planet.", + "moons": ["Moon_Test4"] + }, + { + "id":1, + "name": "Mercury", + "length_of_year": 88, + "description": "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + "moons": ["Moon_Test1", "Moon_Test2"] + }, + { + "id":2, + "name": "Venus", + "length_of_year": 225, + "description": "Venus spins slowly in the opposite direction from most planets.", + "moons": ["Moon_Test3"] + } +] + +def test_get_all_planets_with_moons_sorted_by_length_of_year_return_planets_info(client,three_planets_with_moons): + # Act + data = {"sort": "length_of_year"} + # Act + response = client.get("/planets", query_string = data) + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body == [ + { + "id":1, + "name": "Mercury", + "length_of_year": 88, + "description": "Mercury is the smallest planet in the Solar System and the closest to the Sun.", + "moons": ["Moon_Test1", "Moon_Test2"] + }, + { + "id":2, + "name": "Venus", + "length_of_year": 225, + "description": "Venus spins slowly in the opposite direction from most planets.", + "moons": ["Moon_Test3"] + }, + { + "id":3, + "name": "Earth", + "length_of_year": 365, + "description": "Earth — our home planet.", + "moons": ["Moon_Test4"] + }, +] \ No newline at end of file diff --git a/tests/test_validate_routes.py b/tests/test_validate_routes.py new file mode 100644 index 000000000..ae9252703 --- /dev/null +++ b/tests/test_validate_routes.py @@ -0,0 +1,189 @@ +from app import db +from app.models.planet import Planet +from app.models.moon import Moon +from app.routes.planet_routes import validate_model +from werkzeug.exceptions import HTTPException +import pytest + +def test_to_dict_no_missing_data(): + # Arrange + moon1 = Moon( + description = "Earth's Moon is the only place beyond Earth where humans have set foot, so far.", + size = 1738.1, + name = "Moon" + ) + + test_data = Planet( + name="Test", + moons = [moon1], + description="Imaginary for testing", + length_of_year = 100) + # Act + result = test_data.to_dict() + # Assert + assert len(result) == 5 + assert result["moons"] == ["Moon"] + assert result["name"] == "Test" + assert result["length_of_year"] == 100 + assert result["description"] == "Imaginary for testing" + +def test_to_dict_missing_id(): + # Arrange + moon1 = Moon( + description = "Earth's Moon is the only place beyond Earth where humans have set foot, so far.", + size = 1738.1, + name = "Moon" + ) + test_data = Planet(name="Test", + description="Imaginary for testing", + length_of_year = 100, + moons = [moon1] + ) + # Act + result = test_data.to_dict() + # Assert + assert len(result) == 5 + assert result["name"] == "Test" + assert result["moons"] == ["Moon"] + assert result["length_of_year"] == 100 + assert result["description"] == "Imaginary for testing" + +def test_to_dict_missing_name(): + # Arrange + moon1 = Moon( + description = "Earth's Moon is the only place beyond Earth where humans have set foot, so far.", + size = 1738.1, + name = "Moon" + ) + + test_data = Planet( + moons = [moon1], + description="Imaginary for testing", + length_of_year = 100) + + # Act + result = test_data.to_dict() + # Assert + assert len(result) == 5 + assert result["moons"] == ["Moon"] + assert result["name"] == None + assert result["length_of_year"] == 100 + assert result["description"] == "Imaginary for testing" + +def test_to_dict_missing_description(): + # Arrange + moon1 = Moon( + description = "Earth's Moon is the only place beyond Earth where humans have set foot, so far.", + size = 1738.1, + name = "Moon" + ) + + test_data = Planet( + name="Test", + moons = [moon1], + length_of_year = 100) + + # Act + result = test_data.to_dict() + # Assert + assert len(result) == 5 + assert result["moons"] == ["Moon"] + assert result["name"] == "Test" + assert result["length_of_year"] == 100 + assert result["description"] == None + +def test_to_dict_missing_moon(): + # Arrange + moon1 = Moon( + description = "Earth's Moon is the only place beyond Earth where humans have set foot, so far.", + size = 1738.1, + name = "Moon" + ) + + test_data = Planet( + name="Test", + description="Imaginary for testing", + length_of_year = 100) + + # Act + result = test_data.to_dict() + # Assert + assert len(result) == 5 + assert result["moons"] == [] + assert result["name"] == "Test" + assert result["length_of_year"] == 100 + assert result["description"] == "Imaginary for testing" + +def test_from_dict_returns_planet(): +# Arrange + planet_data = { + "name": "Test", + "length_of_year": 100, + "description": "Imaginary for testing" + } +# Act + new_planet = Planet.from_dict(planet_data) +# Assert + assert new_planet.name == "Test" + assert new_planet.length_of_year == 100 + assert new_planet.description == "Imaginary for testing" + +def test_from_dict_with_no_name(): +# Arrange + planet_data = { + "length_of_year": 100, + "description": "Imaginary for testing" + } +# Act & Assert + with pytest.raises(KeyError, match = 'name'): + new_planet = Planet.from_dict(planet_data) + +def test_from_dict_with_no_description(): +# Arrange + planet_data = { + "name": "Test", + "length_of_year": 100, + } +# Act & Assert + with pytest.raises(KeyError, match = 'description'): + new_planet = Planet.from_dict(planet_data) + +def test_from_dict_with_extra_keys(): +# Arrange + planet_data = { + "name": "Test", + "length_of_year": 100, + "description": "Imaginary for testing" + } +# Act + new_planet = Planet.from_dict(planet_data) +# Assert + assert new_planet.name == "Test" + assert new_planet.length_of_year == 100 + assert new_planet.description == "Imaginary for testing" + +#### tests for validate_model #### +def test_validate_model(three_planets): + # Act + result_planet = validate_model(Planet, 1) + # Assert + assert result_planet.id == 1 + assert result_planet.name == "Mercury" + assert result_planet.length_of_year == 88 + assert result_planet.description == "Mercury is the smallest planet in the Solar System and the closest to the Sun." + +def test_validate_model_missing_record(three_planets): + # Act & Assert + # Calling `validate_book` without being invoked by a route will + # cause an `HTTPException` when an `abort` statement is reached + with pytest.raises(HTTPException): + result_planet = validate_model(Planet, 9) + +def test_validate_model_invalid_id(three_planets): + # Act & Assert + # Calling `validate_book` without being invoked by a route will + # cause an `HTTPException` when an `abort` statement is reached + with pytest.raises(HTTPException): + result_planet = validate_model(Planet, "hello") + +#### tests for validate_input #### \ No newline at end of file