diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..066ed31d9 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' diff --git a/app/__init__.py b/app/__init__.py index 70b4cabfe..07840c1aa 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,41 @@ 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__) + + if not test_config: + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( + "SQLALCHEMY_DATABASE_URI") + else: + app.config["TESTING"] = True + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( + "SQLALCHEMY_TEST_DATABASE_URI") + + + db.init_app(app) + migrate.init_app(app,db) + + + from app.models.celestial_body import CelestialBody + from app.models.planet import Planet + from app.models.moon import Moon + + #from app.models.planet import Planet + #from app.models.moon import Moon + from .routes.planet import planets_bp + from .routes.moon import moons_bp + app.register_blueprint(planets_bp) + app.register_blueprint(moons_bp) return app diff --git a/app/filter_attributes.py b/app/filter_attributes.py new file mode 100644 index 000000000..8f61ad60a --- /dev/null +++ b/app/filter_attributes.py @@ -0,0 +1,4 @@ +PLANET_ATTRIBUTES = ["name", "description", "mass", "diameter", "density", "gravity", "escape_velocity", + "rotation_period", "day_length", "distance_from_sun", "orbital_period", "orbital_velocity", "orbital_inclination", "orbital_eccentricity", + "obliquity_to_orbit", "mean_tempurature_c", "surface_pressure", "global_magnetic_feild", "has_rings"] +MOON_ATTRIBUTES = ["name", "description"] diff --git a/app/models/celestial_body.py b/app/models/celestial_body.py new file mode 100644 index 000000000..99d4a79ac --- /dev/null +++ b/app/models/celestial_body.py @@ -0,0 +1,7 @@ +from app import db +class CelestialBody(db.Model): + __tablename__ = 'celestial_bodies' + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name=db.Column(db.String) + description = db.Column(db.String) + image=db.Column(db.String) diff --git a/app/models/moon.py b/app/models/moon.py new file mode 100644 index 000000000..cdaf6c9e1 --- /dev/null +++ b/app/models/moon.py @@ -0,0 +1,60 @@ +from app import db + +class Moon(db.Model): + __tablename__='moons' + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + size = db.Column(db.Float) + description = db.Column(db.String) + image = db.Column(db.String) + planet_id = db.Column(db.Integer, db.ForeignKey('planets.id')) + planet = db.relationship("Planet", back_populates="moons") + + + def to_dict(self): + moons_as_dict = {} + moons_as_dict["id"] = self.id + moons_as_dict["name"] = self.name + moons_as_dict["size"] = self.size + moons_as_dict["description"] = self.description + moons_as_dict["image"] = self.image + + return moons_as_dict + + @classmethod + def from_dict(cls, moon_data): + new_moon = Moon( + name=moon_data["name"],size=moon_data["size"], description=moon_data["description"], image=moon_data["image"]) + return new_moon +# def __init__(self, id, name, description, planet_id): +# self.id=id +# self.name=name +# self.description=description +# self.planet_id = planet_id + + +# def get_siblings_moons(self): +# siblings_moons = [] +# for moon in moons_list: +# if moon.planet_id == self.planet_id: +# siblings_moons.append(moon) +# return siblings_moons + + +# moons_list = [] +# first_mon = Moon(1, "Luna", "Earths Moon", 3) +# moons_list.append(first_mon) +# second_moon = Moon(2,"Phobos", "Moon of mars discovered in 1877", 4) +# third_moon = Moon(3, "Deimos", "Second moon of mars discovered in 1877", 4) +# forth_moon = Moon(4, "Io", "discovered in 1610", 5) +# fifth_moon = Moon(5, "Europa", "discovered 1610", 5) +# sixth_moon = Moon(6, "Ganymede", "discovered 1610", 6) +# seventh_moon = Moon(7, "Callisto", "Discovered 1610", 5) +# eigth_moon = Moon(8, "Amalthea", "Discovered in 1982", 5) +# moons_list.append(second_moon) +# moons_list.append(third_moon) +# moons_list.append(forth_moon) +# moons_list.append(fifth_moon) +# moons_list.append(sixth_moon) +# moons_list.append(seventh_moon) +# moons_list.append(eigth_moon) diff --git a/app/models/planet.py b/app/models/planet.py new file mode 100644 index 000000000..e5b33c9d6 --- /dev/null +++ b/app/models/planet.py @@ -0,0 +1,183 @@ +#from .moon import Moon, moons_list +from app import db +class Planet(db.Model): + __tablename__='planets' + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name=db.Column(db.String) + description=db.Column(db.String) + mass=db.Column(db.Float) + diameter=db.Column(db.Float) + density=db.Column(db.Float) + gravity=db.Column(db.Float) + escape_velocity=db.Column(db.Float) + rotation_period=db.Column(db.Float) + day_length=db.Column(db.Float) + distance_from_sun=db.Column(db.Float) + orbital_period=db.Column(db.Float) + orbital_velocity=db.Column(db.Float) + orbital_inclination=db.Column(db.Float) + orbital_eccentricity=db.Column(db.Float) + obliquity_to_orbit=db.Column(db.Float) + mean_tempurature_c=db.Column(db.Float) + surface_pressure=db.Column(db.Float) + global_magnetic_feild=db.Column(db.Boolean, default=False, server_default="false") + img=db.Column(db.String) + has_rings=db.Column(db.Boolean, default=False, server_default="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["description"] = self.description + planet_as_dict["mass"] = self.mass + planet_as_dict["diameter"]=self.diameter + planet_as_dict["density"] = self.density + planet_as_dict["gravity"] = self.gravity + planet_as_dict["escape_velocity"] = self.escape_velocity + planet_as_dict["rotation_period"] = self.rotation_period + planet_as_dict["day_length"] = self.day_length + planet_as_dict["distance_from_sun"] = self.distance_from_sun + planet_as_dict["orbital_period"] = self.orbital_period + planet_as_dict["orbital_velocity"] = self.orbital_velocity + planet_as_dict["orbital_inclination"] = self.orbital_inclination + planet_as_dict["orbital_eccentricity"] = self.orbital_eccentricity + planet_as_dict["obliquity_to_orbit"] = self.obliquity_to_orbit + planet_as_dict["mean_tempurature_c"] = self.mean_tempurature_c + planet_as_dict["surface_pressure"] = self.surface_pressure + planet_as_dict["global_magnetic_feild"] = self.global_magnetic_feild + planet_as_dict["img"] = self.img + planet_as_dict["has_rings"] = self.has_rings + planet_as_dict["moons"] = list(map(lambda moon: moon.to_dict(), self.moons)) + return planet_as_dict + + @classmethod + def from_dict(cls, planets_data): + # Moons are optional + moons = [] + if "moons" in planets_data: + moons = planets_data["moons"] + + new_planet = Planet( + name=planets_data["name"], + description=planets_data["description"], + mass=planets_data["mass"], + diameter=planets_data["diameter"], + density=planets_data["density"], + gravity=planets_data["gravity"], + escape_velocity=planets_data["escape_velocity"], + rotation_period=planets_data["rotation_period"], + day_length=planets_data["day_length"], + distance_from_sun=planets_data["distance_from_sun"], + orbital_period=planets_data["orbital_period"], + orbital_velocity=planets_data["orbital_velocity"], + orbital_inclination=planets_data["orbital_inclination"], + orbital_eccentricity=planets_data["orbital_eccentricity"], + obliquity_to_orbit=planets_data["obliquity_to_orbit"], + mean_tempurature_c=planets_data["mean_tempurature_c"], + surface_pressure=planets_data["surface_pressure"], + global_magnetic_feild=planets_data["global_magnetic_feild"], + img=planets_data["img"], + has_rings=planets_data["has_rings"], + moons=moons) + return new_planet +# def __init__(self, id, name, description, mass, diameter, density, gravity, escape_velocity, +# rotation_period, day_length, distance_from_sun, orbital_period, orbital_velocity, orbital_inclination, orbital_eccentricity, +# obliquity_to_orbit, mean_tempurature_c, surface_pressure, global_magnetic_feild,img,has_rings=False, moons=None): +# self.id=id +# self.name=name +# self.description=description +# self.mass=mass +# self.diameter=diameter +# self.density=density +# self.gravity=gravity +# self.escape_velocity=escape_velocity +# self.rotation_period=rotation_period +# self.day_length=day_length +# self.distance_from_sun=distance_from_sun +# self.orbital_period=orbital_period +# self.orbital_velocity=orbital_velocity +# self.orbital_inclination=orbital_inclination +# self.orbital_eccentricity=orbital_eccentricity +# self.obliquity_to_orbit=obliquity_to_orbit +# self.mean_tempurature_c=mean_tempurature_c +# self.surface_pressure=surface_pressure +# self.global_magnetic_feild=global_magnetic_feild +# self.img=img +# self.has_rings=has_rings +# self.moons = moons if moons else [] + +# def add_moon(self, moon): +# # validate if is a moon object +# if moon.__class__.__name__ != "Moon": +# raise ValueError(f"{moon} is not a moon.") +# # validate if the planet_id of the moon is the same as self.id +# if moon.planet_id != self.id: +# raise ValueError(f"{moon} is not the moon of {self.name}") +# self.moons.append(moon) + +# def serialize(self): +# filtered_attributes = self.__dict__.copy() +# new_value = [] +# for moon_object in filtered_attributes["moons"]: +# new_value.append(moon_object.name) +# filtered_attributes["moons"] = new_value +# return filtered_attributes + +# solar_system=[]{ + # "name": "Mercury", + # "description": First Planet near the Sun", + # "mass": 0.330, + # "diameter":4878, + # "density": 5429, + # "gravity": 3.7, + # "escape_velocity": 4.3, + # "rotation_period": 1407.6, + # "day_length": 57.9, + # "distance_from_sun":36.04, + # "orbital_period": 88.0, + # "orbital_velocity" : 47.4, + # "orbital_inclination": 7.0, + # "orbital_eccentricity":0.206, + # "obliquity_to_orbit":0.034, + # "mean_tempurature_c":167, + # "surface_pressure":0, + # "global_magnetic_feild":False, + # "img":https://photojournal.jpl.nasa.gov/jpegMod/PIA16853_modest.jpg, + # "has_Rings": False} +# mercurey = +# Planet(1, "Mercury", "First Planet near the Sun", .330, 4878, 5429, 3.7, 4.3, 1407.6, 4222.6, +# 57.9, 88.0, 47.4, 7.0, .206, .034, 167, 0, False, 'https://photojournal.jpl.nasa.gov/jpegMod/PIA16853_modest.jpg') +# solar_system.append(mercurey){ + # "name": "Mercury", + # "description": First Planet near the Sun", + # "mass": 0.330, + # "diameter":4878, + # "density": 5429, + # "gravity": 3.7, + # "escape_velocity": 4.3, + # "rotation_period": 1407.6, + # "day_length": 57.9, + # "distance_from_sun":36.04, + # "orbital_period": 88.0, + # "orbital_velocity" : 47.4, + # "orbital_inclination": 7.0, + # "orbital_eccentricity":0.206, + # "obliquity_to_orbit":0.034, + # "mean_tempurature_c":167, + # "surface_pressure":0, + # "global_magnetic_feild":False, + # "img":https://photojournal.jpl.nasa.gov/jpegMod/PIA16853_modest.jpg, + # "has_Rings": False} +# venus = Planet(2, "Venus", "Second Planet from the sun", 4.87, 12104, 5243, 8.9, 10.4, -5832.5, 2802.0, 108.2, 224.7, 35.0, 3.4, .0007, 177.4, 464, 92, False, 'https://solarsystem.nasa.gov/resources/2524/newly-processed-views-of-venus-from-mariner-10/?category=planets_venus') +# solar_system.append(venus) +# earth = Planet(3, "Earth", "Has Humans", 5.97, 12756, 5514, 9.8, 11.2, 23.9, 24.0, 149.6, 365.2, 29.8, 0.0, .017, 23.4, 15, 1, True, 'https://solarsystem.nasa.gov/resources/786/blue-marble-2002/?category=planets_earth', False, [moons_list[0]]) +# solar_system.append(earth) +# mars= Planet(4, "Mars", "Being explored by robots, considered for space colony", .642, 6792, 3934, 3.7, 5, 24.6, 24.7, 228, 687, 24.1, 1.8, .094, 25.2, -65, .01, False, 'https://solarsystem.nasa.gov/resources/948/hubbles-close-up-view-of-mars-dust-storm/?category=planets_mars') +# solar_system.append(mars) +# jupiter = Planet(5, "Jupiter", "Largest Gas Giant", 1898, 142984, 1326, 23.1, 59.5, 9.9, 9.9, 778.5, 4331,13.1, 1.3, .049, 3.1, -110, None, True, 'https://solarsystem.nasa.gov/resources/2486/hubbles-new-portrait-of-jupiter/?category=planets_jupiter', has_rings=True) +# solar_system.append(jupiter) +# saturn = Planet(6, "Saturn", "Gas Giant", 568, 120536, 687, 9, 35.5, 10.7, 10.7, 1432.0, 10747, 9.7, 2.5, .052, 26.7, -140, None, True, 'https://solarsystem.nasa.gov/resources/2490/saturns-rings-shine-in-hubble-portrait/?category=planets_saturn', has_rings=True) +# solar_system.append(saturn) +# uranus = Planet(7, "Uranus", "Smells bad",86.8, 51118, 1270, 8.7, 21.3, -17.2, 17.2, 2867, 30589, 6.8, .8, .047, 97.8, -195, None, True, 'https://solarsystem.nasa.gov/resources/605/keck-telescope-views-of-uranus/?category=planets_uranus', has_rings=True) +# neptune = Planet(8, "Neptue", "Named for the god of the sea because it is blue", 102, 49528, 1638, 11.0, 23.5, 16.1, 16.1, 4515, 59800, 5.4, 1.8, .010, 28.3, -200, None, True, 'https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune', has_rings=True) \ No newline at end of file diff --git a/app/planets_data.jsonc b/app/planets_data.jsonc new file mode 100644 index 000000000..6bc740f6c --- /dev/null +++ b/app/planets_data.jsonc @@ -0,0 +1,194 @@ +[ + // Mercury + { + "name": "Mercury", + "description": "First Planet near the Sun", + "mass": 0.330, + "diameter": 4878, + "density": 5429, + "gravity": 3.7, + "escape_velocity": 4.3, + "rotation_period": 1407.6, + "day_length": 57.9, + "distance_from_sun": 36.04, + "orbital_period": 88.0, + "orbital_velocity": 47.4, + "orbital_inclination": 7.0, + "orbital_eccentricity": 0.206, + "obliquity_to_orbit": 0.034, + "mean_tempurature_c": 167, + "surface_pressure": 0, + "global_magnetic_feild": false, + "img": "https://photojournal.jpl.nasa.gov/jpegMod/PIA16853_modest.jpg", + "has_rings": false, + "moons": [] + }, + // Venus + { + "name": "Venus", + "description": "Second Planet from the sun", + "mass": 4.87, + "diameter": 12104, + "density": 5243, + "gravity": 8.9, + "escape_velocity": 10.4, + "rotation_period": -5832.5, + "day_length": 2802.0, + "distance_from_sun": 108.2, + "orbital_period": 224.7, + "orbital_velocity": 35.0, + "orbital_inclination": 3.4, + "orbital_eccentricity": 0.0007, + "obliquity_to_orbit": 177.4, + "mean_tempurature_c": 464, + "surface_pressure": 92, + "global_magnetic_feild": false, + "img": "https://solarsystem.nasa.gov/resources/2524/newly-processed-views-of-venus-from-mariner-10/?category=planets_venus", + "has_rings": false, + "moons": [] + }, + // Earth + { + "name": "Earth", + "description": "Has Humans", + "mass": 5.97, + "diameter": 12756, + "density": 5514, + "gravity": 9.8, + "escape_velocity": 11.2, + "rotation_period": 23.9, + "day_length": 24.0, + "distance_from_sun": 149.6, + "orbital_period": 365.2, + "orbital_velocity": 29.8, + "orbital_inclination": 0.0, + "orbital_eccentricity": 0.017, + "obliquity_to_orbit": 23.4, + "mean_tempurature_c": 15, + "surface_pressure": 1, + "global_magnetic_feild": true, + "img": "https://solarsystem.nasa.gov/resources/786/blue-marble-2002/?category=planets_earth", + "has_rings": false, + "moons": [] + }, + // Mars + { + "name": "Mars", + "description": "Being explored by robots, considered for space colony", + "mass": 0.642, + "diameter": 6792, + "density": 3934, + "gravity": 3.7, + "escape_velocity": 5, + "rotation_period": 24.6, + "day_length": 24.7, + "distance_from_sun": 228, + "orbital_period": 687, + "orbital_velocity": 24.1, + "orbital_inclination": 1.8, + "orbital_eccentricity": 0.094, + "obliquity_to_orbit": 25.2, + "mean_tempurature_c": -65, + "surface_pressure": 0.01, + "global_magnetic_feild": false, + "img": "https://solarsystem.nasa.gov/resources/948/hubbles-close-up-view-of-mars-dust-storm/?category=planets_mars", + "has_rings": false, + "moons": [] + }, + // Jupiter + { + "name": "Jupiter", + "description": "Largest Gas Giant", + "mass": 1898, + "diameter": 142984, + "density": 1326, + "gravity": 23.1, + "escape_velocity": 59.5, + "rotation_period": 9.9, + "day_length": 9.9, + "distance_from_sun": 778.5, + "orbital_period": 4331, + "orbital_velocity": 13.1, + "orbital_inclination": 1.3, + "orbital_eccentricity": 0.049, + "obliquity_to_orbit": 3.1, + "mean_tempurature_c": -110, + "surface_pressure": null, + "global_magnetic_feild": true, + "img": "https://solarsystem.nasa.gov/resources/2486/hubbles-new-portrait-of-jupiter/?category=planets_jupiter", + "has_rings": true, + "moons": [] + }, + // Saturn + { + "name": "Saturn", + "description": "Gas Giant", + "mass": 568, + "diameter": 120536, + "density": 687, + "gravity": 9, + "escape_velocity": 35.5, + "rotation_period": 10.7, + "day_length": 10.7, + "distance_from_sun": 1432.0, + "orbital_period": 10747, + "orbital_velocity": 9.7, + "orbital_inclination": 2.5, + "orbital_eccentricity": 0.052, + "obliquity_to_orbit": 26.7, + "mean_tempurature_c": -140, + "surface_pressure": null, + "global_magnetic_feild": true, + "img": "https://solarsystem.nasa.gov/resources/2490/saturns-rings-shine-in-hubble-portrait/?category=planets_saturn", + "has_rings": true, + "moons": [] + }, + // Uranus + { + "name": "Uranus", + "description": "Smells bad", + "mass": 86.8, + "diameter": 51118, + "density": 1270, + "gravity": 8.7, + "escape_velocity": 21.3, + "rotation_period": -17.2, + "day_length": 17.2, + "distance_from_sun": 2867, + "orbital_period": 30589, + "orbital_velocity": 6.8, + "orbital_inclination": 0.8, + "orbital_eccentricity": 0.047, + "obliquity_to_orbit": 97.8, + "mean_tempurature_c": -195, + "surface_pressure": null, + "global_magnetic_feild": true, + "img": "https://solarsystem.nasa.gov/resources/605/keck-telescope-views-of-uranus/?category=planets_uranus", + "has_rings": true, + "moons": [] + }, + // Neptune + { + "name": "Neptune", + "description": "Named for the god of the sea because it is blue", + "mass": 102, + "diameter": 49528, + "density": 1638, + "gravity": 11.0, + "escape_velocity": 23.5, + "rotation_period": 16.1, + "day_length": 16.1, + "distance_from_sun": 4515, + "orbital_period": 59800, + "orbital_velocity": 5.4, + "orbital_inclination": 1.8, + "orbital_eccentricity": 0.01, + "obliquity_to_orbit": 28.3, + "mean_tempurature_c": -200, + "surface_pressure": null, + "global_magnetic_feild": true, + "img": "https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune", + "has_rings": true, + "moons": [] + } +] \ 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/moon.py b/app/routes/moon.py new file mode 100644 index 000000000..58cafdff5 --- /dev/null +++ b/app/routes/moon.py @@ -0,0 +1,84 @@ +from app.models.moon import Moon +from app.models.planet import Planet +from flask import Blueprint, jsonify, abort, make_response, request +from app import db +from app.routes.planet import planets_bp, validate_model +moons_bp = Blueprint("moons", __name__, url_prefix="/moons") + + +@planets_bp.route("//moons", methods=["POST"]) +def create_moon(planet_id): + planet = validate_model(Planet, planet_id) + request_body = request.get_json() + try: + new_moon = Moon( + name=request_body["name"], + size = request_body["size"], + description = request_body["description"], + image = request_body["image"], + planet=planet + ) + except KeyError as key_error: + abort(make_response({"message": f"Bad request: {key_error.args[0]} attribute is missing"}, 400)) + + db.session.add(new_moon) + db.session.commit() + return make_response(jsonify(f"New Moon {new_moon.name} created!"), 201) + +@planets_bp.route("//moons", methods=["GET"]) +def get_all_moons_by_planet(planet_id): + planet = validate_model(Planet, planet_id) + moons_response = [] + for moon in planet.moons: + moons_response.append({ + "id":moon.id, + "name": moon.name, + "size": moon.size, + "description": moon.description, + "image":moon.image, + + }) + return jsonify(moons_response) + +@moons_bp.route("", methods=["GET"]) +def get_all_moons(): + moons = Moon.query.all() + moons_response = [] + for moon in moons: + moons_response.append(moon.to_dict()) + return jsonify(moons_response) + + +@moons_bp.route("/", methods=["GET"]) +def get_moon_by_id(moon_id): + moon=validate_model(Moon, moon_id) + + return jsonify({ + "id": moon.id, + "name": moon.name, + "size": moon.size, + "description": moon.description, + "image": moon.image + }) + +@moons_bp.route("/", methods=["PUT"]) +def update_moon(moon_id): + moon=validate_model(Moon, moon_id) + request_body = request.get_json() + moon.name = request_body["name"] + moon.size = request_body["size"] + moon.description=request_body["description"] + moon.image=request_body["image"] + + db.session.commit() + return make_response(jsonify(f"Moon {moon.name} has been updated")) + +@moons_bp.route("/", methods=["DELETE"]) +def delete_a_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")) + diff --git a/app/routes/planet.py b/app/routes/planet.py new file mode 100644 index 000000000..432f2f319 --- /dev/null +++ b/app/routes/planet.py @@ -0,0 +1,121 @@ +from flask import Blueprint, jsonify, abort, make_response, request +from app.filter_attributes import PLANET_ATTRIBUTES +from app.models.planet import Planet +from app import db +planets_bp = Blueprint("planets", __name__, url_prefix="/planets") + + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + abort(make_response({"message":f"{model_id} invalid"}, 400)) + model = cls.query.get(model_id) + if model: + return model + abort(make_response({"message":f"{cls.__name__} with {model_id} not found"}, 404)) + + + +def apply_filter(planet_query): + FILTERABLE_ATTRIBUTES = ['global_magnetic_feild', 'has_rings'] + required_parameters = {} + for attribute in FILTERABLE_ATTRIBUTES: + value = request.args.get(attribute) + if value is not None: + required_parameters[attribute] = value + if required_parameters: + planet_query = planet_query.filter_by(**required_parameters) + + order_by_asc = request.args.get("order_by_asc") + order_by_desc = request.args.get("order_by_desc") + max_query = request.args.get("max") + min_query = request.args.get("min") + + # Validate that only one option at a time is specified + options = [order_by_asc, order_by_desc, max_query, min_query] + num_options = sum(1 if option is not None else 0 for option in options) + if num_options > 1: + abort(make_response("Bad request: Too many options", 400)) + + #greater_than_ave = request.args.get("greater_than_ave") + if order_by_asc is not None: + planet_query = planet_query.order_by(getattr(Planet, order_by_asc)) + elif order_by_desc is not None: + planet_query = planet_query.order_by(getattr(Planet, order_by_desc).desc()) + elif max_query is not None: + planet_query = planet_query.order_by(getattr(Planet, max_query).desc()).limit(1) + elif min_query is not None: + planet_query = planet_query.order_by(getattr(Planet, min_query)).limit(1) + #elif greater_than_ave is not None: + # planet_query = planet_query.query.filter(getattr(Planet, greater_than_ave).func.avg()) + + return planet_query + +@planets_bp.route("", methods=["GET"]) +def display_planets(): + planets_response = [] + planet_query = Planet.query + planet_query = apply_filter(planet_query).all() + for planet in planet_query: + planets_response.append(planet.to_dict()) + return jsonify(planets_response) + +@planets_bp.route("", methods=["POST"]) +def create_planets(): + request_body=request.get_json() + try: + new_planet = Planet.from_dict(request_body) + except KeyError as key_error: + abort(make_response({"message": f"Bad request: {key_error.args[0]} attribute is missing"}, 400)) + db.session.add(new_planet) + db.session.commit() + return make_response(jsonify(f"New Planet {new_planet.name} created!"), 201) + +@planets_bp.route("/", methods=["GET"]) +def display_planet(planet_id): + planet = validate_model(Planet, planet_id) + return planet.to_dict() + + + + +@planets_bp.route("/", methods=["PUT"]) +def update_a_planet(planet_id): + planet = validate_model(Planet, planet_id) + request_body = request.get_json() + for key in PLANET_ATTRIBUTES: + if not key in request_body: + abort(make_response({"message": f"Bad request: {key} attribute is missing"}, 400)) + planet.name=request_body["name"] + planet.description=request_body["description"] + planet.mass=request_body["mass"] + planet.diameter=request_body["diameter"] + planet.density=request_body["density"] + planet.gravity=request_body["gravity"] + planet.escape_velocity=request_body["escape_velocity"] + planet.rotation_period=request_body["rotation_period"] + planet.day_length=request_body["day_length"] + planet.distance_from_sun=request_body["distance_from_sun"] + planet.orbital_period=request_body["orbital_period"] + planet.orbital_velocity=request_body["orbital_velocity"] + planet.orbital_inclination=request_body["orbital_inclination"] + planet.orbital_eccentricity=request_body["orbital_eccentricity"] + planet.obliquity_to_orbit=request_body["obliquity_to_orbit"] + planet.mean_tempurature_c=request_body["mean_tempurature_c"] + planet.surface_pressure=request_body["surface_pressure"] + planet.global_magnetic_feild=request_body["global_magnetic_feild"] + planet.img=request_body["img"] + planet.has_rings=request_body["has_rings"] + + db.session.commit() + return make_response(jsonify(f"Planet {planet.id} successfully updated")) + +@planets_bp.route("/", methods=["DELETE"]) +def delete_a_planet(planet_id): + planet = validate_model(Planet, planet_id) + + db.session.delete(planet) + db.session.commit() + + return make_response(jsonify(f"Planet {planet.id} successfully deleted")) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/0663be054953_.py b/migrations/versions/0663be054953_.py new file mode 100644 index 000000000..109ddc4ac --- /dev/null +++ b/migrations/versions/0663be054953_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: 0663be054953 +Revises: 6015f9934596 +Create Date: 2022-12-21 11:30:54.155918 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0663be054953' +down_revision = '6015f9934596' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('moons', sa.Column('name', sa.String(), nullable=True)) + op.drop_column('moons', 'title') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('moons', sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=True)) + op.drop_column('moons', 'name') + # ### end Alembic commands ### diff --git a/migrations/versions/6015f9934596_add_moon_planet_and_bodies_models.py b/migrations/versions/6015f9934596_add_moon_planet_and_bodies_models.py new file mode 100644 index 000000000..5e250222a --- /dev/null +++ b/migrations/versions/6015f9934596_add_moon_planet_and_bodies_models.py @@ -0,0 +1,69 @@ +"""add moon, planet and bodies models + +Revision ID: 6015f9934596 +Revises: +Create Date: 2022-12-20 11:05:53.575534 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '6015f9934596' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('celestial_bodies', + 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('image', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('planets', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('mass', sa.Float(), nullable=True), + sa.Column('diameter', sa.Float(), nullable=True), + sa.Column('density', sa.Float(), nullable=True), + sa.Column('gravity', sa.Float(), nullable=True), + sa.Column('escape_velocity', sa.Float(), nullable=True), + sa.Column('rotation_period', sa.Float(), nullable=True), + sa.Column('day_length', sa.Float(), nullable=True), + sa.Column('distance_from_sun', sa.Float(), nullable=True), + sa.Column('orbital_period', sa.Float(), nullable=True), + sa.Column('orbital_velocity', sa.Float(), nullable=True), + sa.Column('orbital_inclination', sa.Float(), nullable=True), + sa.Column('orbital_eccentricity', sa.Float(), nullable=True), + sa.Column('obliquity_to_orbit', sa.Float(), nullable=True), + sa.Column('mean_tempurature_c', sa.Float(), nullable=True), + sa.Column('surface_pressure', sa.Float(), nullable=True), + sa.Column('global_magnetic_feild', sa.Boolean(), nullable=True), + sa.Column('img', sa.String(), nullable=True), + sa.Column('has_rings', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('moons', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('image', sa.String(), nullable=True), + sa.Column('planet_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['planet_id'], ['planets.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('moons') + op.drop_table('planets') + op.drop_table('celestial_bodies') + # ### end Alembic commands ### diff --git a/migrations/versions/d663f3f6838e_.py b/migrations/versions/d663f3f6838e_.py new file mode 100644 index 000000000..076d0f835 --- /dev/null +++ b/migrations/versions/d663f3f6838e_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: d663f3f6838e +Revises: 0663be054953 +Create Date: 2023-01-05 10:33:17.544793 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'd663f3f6838e' +down_revision = '0663be054953' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('moons', sa.Column('size', sa.Float(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('moons', 'size') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index fba2b3e38..f1c31b3f2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,18 +1,25 @@ 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 +coverage==6.5.0 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +gunicorn==20.1.0 idna==2.10 +iniconfig==1.1.1 itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.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 @@ -23,5 +30,6 @@ requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 +tomli==2.0.1 urllib3==1.26.4 Werkzeug==1.0.1 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..a07b36eaa --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,69 @@ +import pytest +from app import create_app +from app import db +from flask.signals import request_finished +from app.models.planet import Planet +from app.models.moon import Moon +from app.routes.planet import validate_model + + +@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): + test_one = Planet( + name="Neptune", + description="Named for the god of the sea because it is blue", + mass=102, + diameter=49528, + density=1638, + gravity=11.0, + escape_velocity=23.5, + rotation_period=16.1, + day_length=16.1, + distance_from_sun=4515, + orbital_period=59800, + orbital_velocity=5.4, + orbital_inclination=1.8, + orbital_eccentricity=0.01, + obliquity_to_orbit=28.3, + mean_tempurature_c=-200, + surface_pressure=None, + global_magnetic_feild=True, + img="https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune", + has_rings=True, + ) + test_two = Planet(name="number two") + + db.session.add_all([test_one, test_two]) + + db.session.commit() + + +@pytest.fixture +def two_saved_moons(app, two_saved_planets): + planet_one = validate_model(Planet ,1) + moon_one=Moon(name="Test Moon", size=200.5, description="First Moon for Neptune", image="pretty_moon.jpg", planet_id=1) + moon_two=Moon(name="2 Test Moon", size=100.6, description="Second Neptune", image="prettiestMoon.jpg", planet_id = 1) + + db.session.add_all([moon_one,moon_two]) + db.session.commit() + diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 000000000..c82ff1208 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,169 @@ +from app.models.planet import Planet +import pytest + +def test_to_dict_no_missing_data(): + #Arrange + test_planet = Planet( + id = 1, + name="Neptune", + description="Named for the god of the sea because it is blue", + mass=102, + diameter=49528, + density=1638, + gravity=11.0, + escape_velocity=23.5, + rotation_period=16.1, + day_length=16.1, + distance_from_sun=4515, + orbital_period=59800, + orbital_velocity=5.4, + orbital_inclination=1.8, + orbital_eccentricity=0.01, + obliquity_to_orbit=28.3, + mean_tempurature_c=-200, + surface_pressure=None, + global_magnetic_feild=True, + img="https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune", + has_rings=True, + moons = [] + ) + #Act + result = test_planet.to_dict() + + #assert + assert result == { + "id":1, + "name": "Neptune", + "description": "Named for the god of the sea because it is blue", + "mass": 102, + "diameter": 49528, + "density": 1638, + "gravity": 11.0, + "escape_velocity": 23.5, + "rotation_period": 16.1, + "day_length": 16.1, + "distance_from_sun": 4515, + "orbital_period": 59800, + "orbital_velocity": 5.4, + "orbital_inclination": 1.8, + "orbital_eccentricity": 0.01, + "obliquity_to_orbit": 28.3, + "mean_tempurature_c": -200, + "surface_pressure": None, + "global_magnetic_feild": True, + "img": "https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune", + "has_rings": True, + "moons": [] + } + +def test_to_dict_missing_attributes(): + #Arrange + complete_attributes = { + "id":1, + "name": "Neptune", + "description": "Named for the god of the sea because it is blue", + "mass": 102, + "diameter": 49528, + "density": 1638, + "gravity": 11.0, + "escape_velocity": 23.5, + "rotation_period": 16.1, + "day_length": 16.1, + "distance_from_sun": 4515, + "orbital_period": 59800, + "orbital_velocity": 5.4, + "orbital_inclination": 1.8, + "orbital_eccentricity": 0.01, + "obliquity_to_orbit": 28.3, + "mean_tempurature_c": -200, + "surface_pressure": None, + "global_magnetic_feild": True, + "img": "https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune", + "has_rings": True, + "moons": [] + } + + for attribute in complete_attributes.keys(): + incomplete_attributes = complete_attributes.copy() + del incomplete_attributes[attribute] + test_planet = Planet(**incomplete_attributes) + + expected = complete_attributes.copy() + if attribute == "moons": + expected[attribute] = [] + else: + expected[attribute] = None + + #Act + result = test_planet.to_dict() + + #Assert + assert result == expected + +def test_from_dict_returns_planet(): + #Arrange + test_planet = { + "name": "Neptune", + "description": "Named for the god of the sea because it is blue", + "mass": 102, + "diameter": 49528, + "density": 1638, + "gravity": 11.0, + "escape_velocity": 23.5, + "rotation_period": 16.1, + "day_length": 16.1, + "distance_from_sun": 4515, + "orbital_period": 59800, + "orbital_velocity": 5.4, + "orbital_inclination": 1.8, + "orbital_eccentricity": 0.01, + "obliquity_to_orbit": 28.3, + "mean_tempurature_c": -200, + "surface_pressure": None, + "global_magnetic_feild": True, + "img": "https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune", + "has_rings": True, + "moons": [] + } + + #Act + new_planet = Planet.from_dict(test_planet) + + #Assert + for key, value in test_planet.items(): + assert getattr(new_planet, key) == value + + + +def test_from_dict_with_missing_attributes(): + #Arrange + complete_attributes = { + "name": "Neptune", + "description": "Named for the god of the sea because it is blue", + "mass": 102, + "diameter": 49528, + "density": 1638, + "gravity": 11.0, + "escape_velocity": 23.5, + "rotation_period": 16.1, + "day_length": 16.1, + "distance_from_sun": 4515, + "orbital_period": 59800, + "orbital_velocity": 5.4, + "orbital_inclination": 1.8, + "orbital_eccentricity": 0.01, + "obliquity_to_orbit": 28.3, + "mean_tempurature_c": -200, + "surface_pressure": None, + "global_magnetic_feild": True, + "img": "https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune", + "has_rings": True + } + + for attribute in complete_attributes.keys(): + incomplete_attributes = complete_attributes.copy() + del incomplete_attributes[attribute] + + #Act/Assert + with pytest.raises(KeyError, match = attribute): + new_planet = Planet.from_dict(incomplete_attributes) \ No newline at end of file diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 000000000..d78b42967 --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,294 @@ +from app.routes.planet import validate_model +from app.models.planet import Planet + +NEPTUNE_PLANET = { + "id":1, + "name": "Neptune", + "description": "Named for the god of the sea because it is blue", + "mass": 102, + "diameter": 49528, + "density": 1638, + "gravity": 11.0, + "escape_velocity": 23.5, + "rotation_period": 16.1, + "day_length": 16.1, + "distance_from_sun": 4515, + "orbital_period": 59800, + "orbital_velocity": 5.4, + "orbital_inclination": 1.8, + "orbital_eccentricity": 0.01, + "obliquity_to_orbit": 28.3, + "mean_tempurature_c": -200, + "surface_pressure": None, + "global_magnetic_feild": True, + "img": "https://solarsystem.nasa.gov/resources/611/neptune-full-disk-view/?category=planets_neptune", + "has_rings": True, + "moons": [] + } + +URANUS_PLANET = { + "name": "Uranus", + "description": "Smells bad", + "mass": 86.8, + "diameter": 51118, + "density": 1270, + "gravity": 8.7, + "escape_velocity": 21.3, + "rotation_period": -17.2, + "day_length": 17.2, + "distance_from_sun": 2867, + "orbital_period": 30589, + "orbital_velocity": 6.8, + "orbital_inclination": 0.8, + "orbital_eccentricity": 0.047, + "obliquity_to_orbit": 97.8, + "mean_tempurature_c": -195, + "surface_pressure": None, + "global_magnetic_feild": True, + "img": "https://solarsystem.nasa.gov/resources/605/keck-telescope-views-of-uranus/?category=planets_uranus", + "has_rings": True, +} + +def test_get_all_planets_with_no_records(client): + # Act + response = client.get("/planets") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [] + +def test_get_all_planets_with_two_records(client, two_saved_planets): + #Act + response = client.get("/planets") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert response_body[0] == NEPTUNE_PLANET + assert response_body[1]["name"] == "number two" + + + +def test_get_one_planet(client, two_saved_planets): + # Act + response = client.get("/planets/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == NEPTUNE_PLANET + +def test_create_one_planet(client): + # Act + response = client.post("/planets", json=URANUS_PLANET) + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == "New Planet Uranus created!" + +def test_update_one_planet(client, two_saved_planets): + # Act + response = client.put("/planets/2", json=URANUS_PLANET) + #Arrange + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == "Planet 2 successfully updated" + +def test_delete_one_planet(client, two_saved_planets): + #Arrange + response = client.delete("/planets/2") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert response_body == "Planet 2 successfully deleted" + +def test_get_one_nonexistent_planet(client, two_saved_planets): + #Arrange + response = client.get("/planets/3") + response_body = response.get_json() + + #Assert + assert response.status_code == 404 + assert response_body == {"message": "Planet with 3 not found"} + +def test_incorrect_id_format(client, two_saved_planets): + #Arrange + response = client.get("/planets/a") + response_body = response.get_json() + + #Assert + assert response.status_code == 400 + assert response_body == {"message": "a invalid"} + +def test_create_incomplete_planet(client): + #Arrange + response = client.post("/planets", json={ + "name": "Uranus", + "mass": 86.8, + "diameter": 51118, + "density": 1270, + "gravity": 8.7, + "escape_velocity": 21.3, + "rotation_period": -17.2, + "day_length": 17.2, + "distance_from_sun": 2867, + "orbital_period": 30589, + "orbital_velocity": 6.8, + "orbital_inclination": 0.8, + "orbital_eccentricity": 0.047, + "obliquity_to_orbit": 97.8, + "mean_tempurature_c": -195, + "surface_pressure": None, + "global_magnetic_feild": True, + "img": "https://solarsystem.nasa.gov/resources/605/keck-telescope-views-of-uranus/?category=planets_uranus", + "has_rings": True + }) + response_body = response.get_json() + + #Assert + assert response.status_code == 400 + assert response_body == {"message": "Bad request: description attribute is missing"} + +def test_update_incomplete_planet(client, two_saved_planets): + #Arrange + response = client.put("/planets/2", json={ + "name": "Uranus"}) + response_body = response.get_json() + + #Assert + assert response.status_code == 400 + assert response_body == {"message": "Bad request: description attribute is missing"} + + +def test_delete_one_nonexistent_planet(client, two_saved_planets): + #Arrange + response = client.get("/planets/3") + response_body = response.get_json() + + #Assert + assert response.status_code == 404 + assert response_body == {"message": "Planet with 3 not found"} + +#tests for moon here to refactor and increase code coverage. + +def test_all_moon_no_records(client): + response = client.get("/moons") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == [] + + + +def test_get_one_moon(client, two_saved_moons): + response=client.get("/moons/1") + response_body=response.get_json() + + assert response_body == { + "id":1, + "name":"Test Moon", + "size": 200.5, + "description":"First Moon for Neptune", + "image":"pretty_moon.jpg" + } + + +def test_get_all_moons_with_two_records(client, two_saved_moons): + #Act + response = client.get("/moons") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert response_body[0] == { + "id":1, + "name": "Test Moon", + "size": 200.5, + "description": "First Moon for Neptune", + "image":"pretty_moon.jpg" + } + assert response_body[1]["name"] == "2 Test Moon" + assert len(response_body) == 2 + + + +def test_get_one_moon(client, two_saved_moons): + # Act + response = client.get("/moons/1") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == { + + "id":1, + "name": "Test Moon", + "size": 200.5, + "description": "First Moon for Neptune", + "image":"pretty_moon.jpg" + } + + + +def test_create_one_moon(client,two_saved_planets, two_saved_moons): + # Act + response = client.post("planets/1/moons", json={ + "name": "three moon", + "size": 200.5, + "description": "for testing", + "image": "best_moon.jpb", +}) + + response_body = response.get_json() + + # Assert + assert response.status_code == 201 + assert response_body == "New Moon three moon created!" + +def test_update_one_moon(client, two_saved_moons): + # Act + response = client.put("/moons/2", json={ + "name": "moon", + "size": 100.6, + "description": "Smells bad", + "image": "images.img" +}) + #Arrange + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body == "Moon moon has been updated" + +def test_delete_one_moon(client, two_saved_moons): + #Arrange + response = client.delete("/moons/2") + response_body = response.get_json() + + #Assert + assert response.status_code == 200 + assert response_body == "Moon 2 successfully deleted" + + + +def test_all_moons_by_planet(client, two_saved_planets, two_saved_moons): + response = client.get("/planets/1/moons") + response_body = response.get_json() + + # Assert + assert len(response_body) == 2 + +def test_validate_planet(two_saved_planets): + #Act + result_planet = validate_model(Planet, 1) + + #Assert + for key, value in NEPTUNE_PLANET.items(): + assert getattr(result_planet, key) == value +