Exemplo n.º 1
0
 def test_new(self):
     """
     new method
     """
     storage.reload()
     self.dummy.new(BaseModel())
     self.assertTrue(self.dummy.all())
Exemplo n.º 2
0
    def do_all(self, args):
        ''' prints all string representation of instances created
        '''

        arg_list = list(args.split())
        results = []

        if len(args) == 0:
            storage.reload()
            all_obj = storage.all()
            for obj in all_obj:
                results += [str(all_obj[obj])]
                storage.save()
            print(results)
            return

        if arg_list[0] in self.classes:
            storage.reload()
            all_obj = storage.all()
            for obj in all_obj:
                results += [str(all_obj[obj])]
                storage.save()
            print(results)
        else:
            print("** class doesn't exist **")
Exemplo n.º 3
0
 def do_destroy(self, args):
     '''
         Deletes an instance based on the class name and id.
     '''
     args = shlex.split(args)
     if len(args) == 0:
         print("** class name missing **")
         return
     elif len(args) == 1:
         print("** instance id missing **")
         return
     class_name = args[0]
     class_id = args[1]
     storage.reload()
     obj_dict = storage.all()
     try:
         eval(class_name)
     except NameError:
         print("** class doesn't exist **")
         return
     key = class_name + "." + class_id
     try:
         del obj_dict[key]
     except KeyError:
         print("** no instance found **")
     storage.save()
Exemplo n.º 4
0
    def test_State(self):
        """Task 9
        Tests `State` class.
        """
        # Normal use: no args
        s1 = State()
        self.assertIsInstance(s1, State)

        # attr `name` defaults to empty string
        self.assertIsInstance(s1.name, str)
        self.assertEqual(s1.name, '')

        # State can be serialized to JSON by FileStorage
        s1.name = 'test'
        self.assertIn(s1, storage._FileStorage__objects.values())
        s1.save()
        with open(storage._FileStorage__file_path, encoding='utf-8') as file:
            content = file.read()
        key = s1.__class__.__name__ + '.' + s1.id
        self.assertIn(key, json.loads(content))

        # State can be deserialized from JSON by FileStorage
        self.assertIn(key, storage._FileStorage__objects.keys())
        storage._FileStorage__objects = dict()
        storage.reload()
        self.assertIn(key, storage._FileStorage__objects.keys())
Exemplo n.º 5
0
 def do_show(self, args):
     '''
         Print the string representation of an instance baed on
         the class name and id given as args.
     '''
     args = shlex.split(args)
     if len(args) == 0:
         print("** class name missing **")
         return
     if len(args) == 1:
         print("** instance id missing **")
         return
     storage.reload()
     obj_dict = storage.all()
     try:
         eval(args[0])
     except NameError:
         print("** class doesn't exist **")
         return
     key = args[0] + "." + args[1]
     key = args[0] + "." + args[1]
     try:
         value = obj_dict[key]
         print(value)
     except KeyError:
         print("** no instance found **")
Exemplo n.º 6
0
def places(city_id):
    """Retrieves the list of all places objects
    """
    placesget = storage.get("City", city_id)

    if placesget is None:
        abort(404)

    if request.method == 'GET':
        listplaces = []
        for place in placesget.places:
            listplaces.append(place.to_dict())
        return jsonify(listplaces)

    if request.method == 'POST':
        json_place = request.get_json()
        if json_place is None:
            abort(400, "Not a JSON")
        if not json_place.get('name'):
            abort(400, "Missing name")
        if not json_place.get('user_id'):
            abort(400, "Missing user_id")
        userget = storage.get("User", json_place.get("user_id"))
        if userget is None:
            abort(404)
        json_place["city_id"] = city_id
        json_place["user_id"] = json_place.get("user_id")
        place = Place(**json_place)
        storage.new(place)
        storage.save()
        storage.reload()
        return jsonify(place.to_dict()), 201
Exemplo n.º 7
0
 def do_update(self, args):
     '''Update an instance based on the class name and id sent as args'''
     storage.reload()
     args = shlex.split(args)
     if len(args) == 0:
         print("** class name missing **")
         return
     elif len(args) == 1:
         print("** instance id missing **")
         return
     elif len(args) == 2:
         print("** attribute name missing **")
         return
     elif len(args) == 3:
         print("** value missing **")
         return
     try:
         eval(args[0])
     except NameError:
         print("** class doesn't exist **")
         return
     key = args[0] + "." + args[1]
     obj_dict = storage.all()
     try:
         obj_value = obj_dict[key]
     except KeyError:
         print("** no instance found **")
         return
     try:
         attr_type = type(getattr(obj_value, args[2]))
         args[3] = attr_type(args[3])
     except AttributeError:
         pass
     setattr(obj_value, args[2], args[3])
     obj_value.save()
Exemplo n.º 8
0
def cities(state_id):
    """methods GET and POST of the cities by states (state_ID)
    """
    cities_st = storage.get("State", state_id)

    if cities_st is None:
        abort(404)

    if request.method == 'GET':
        cities_list = []
        for city in cities_st.cities:
            cities_list.append(city.to_dict())
        return jsonify(cities_list)

    if request.method == 'POST':
        json_city = request.get_json()
        if json_city is None:
            abort(400, "Not a JSON")
        if not json_city.get("name"):
            abort(400, "Missing name")
        json_city["state_id"] = state_id
        city = City(**json_city)
        storage.new(city)
        storage.save()
        storage.reload()
        return jsonify(city.to_dict()), 201
Exemplo n.º 9
0
def new_review(place_id):
    """Creates a Review
    """
    place = storage.get(Place, place_id)
    if place is None:
        abort(404)

    new_obj = request.get_json()
    if new_obj is None:
        abort(400, "Not a JSON")

    if "user_id" not in new_obj.keys():
        abort(400, "Missing user_id")

    user = storage.get(User, new_obj["user_id"])
    if user is None:
        abort(404)

    if "text" not in new_obj.keys():
        abort(400, "Missing text")

    new_obj["place_id"] = place_id
    new_review = Review(**new_obj)
    new_review.save()
    storage.reload()
    return jsonify(new_review.to_dict()), 201
Exemplo n.º 10
0
 def test_09(self):
     """Checks correct implementation of reload() method"""
     obj_dict = storage.all()
     storage.reload()
     bm = BaseModel()
     us = User()
     st = State()
     pl = Place()
     cy = City()
     am = Amenity()
     rv = Review()
     storage.new(bm)
     storage.new(us)
     storage.new(st)
     storage.new(pl)
     storage.new(cy)
     storage.new(am)
     storage.new(rv)
     storage.save()
     storage.reload()
     self.assertIn("BaseModel." + bm.id, obj_dict.keys())
     self.assertIn("User." + us.id, obj_dict.keys())
     self.assertIn("State." + st.id, obj_dict.keys())
     self.assertIn("Place." + pl.id, obj_dict.keys())
     self.assertIn("City." + cy.id, obj_dict.keys())
     self.assertIn("Amenity." + am.id, obj_dict.keys())
     self.assertIn("Review." + rv.id, obj_dict.keys())
Exemplo n.º 11
0
def import_image(user_id):
    """import image"""
    if 'image' not in rq.files:
        print('No file part')
    if rq.method == "POST":
        if rq.files:

            image = rq.files["image"]
            if "." in image.filename:
                ext = image.filename.split(".")[-1]
                if ext.upper() not in scrap_app.config["ALLOWED_IMAGE_EXTENSIONS"]:
                    redirect('https://0.0.0.0:5000/error_photo')
            else:
                redirect('https://0.0.0.0:5000/error_photo')
            new_filename = 'cm_' + user_id + '.' + ext

            if os.path.exists(scrap_app.config["IMAGE_UPLOADS"] + new_filename):
                os.remove(scrap_app.config["IMAGE_UPLOADS"] + new_filename)
                print ("deleted")

            final_filename = secure_filename(new_filename)
            image.save(os.path.join(scrap_app.config["IMAGE_UPLOADS"], final_filename))
            final_path = '/static/images/' + final_filename

            my_user = storage.get(User, user_id)
            my_user.update_attr("user_avatar", final_path)
            storage.reload()


            return redirect('https://0.0.0.0:5000/login')
    return redirect('https://0.0.0.0:5000/login')
Exemplo n.º 12
0
 def do_destroy(self, line):
     ''' do_destroy'''
     if len(line) is 0:
         print("** class name missing **")
     else:
         line = line.replace('"', '')
         line = line.replace("'", "")
         list_key = line.split()
         if len(list_key) < 2:
             if list_key[0] not in self.classes:
                 print("** class doesn't exist **")
             else:
                 print("** instance id missing **")
         else:
             storage.reload()
             if list_key[0] in self.classes:
                 key = list_key[0] + "." + list_key[1]
                 new_object = storage.all()
                 if key in new_object:
                     del new_object[key]
                     storage.save()
                 else:
                     print("** no instance found **")
             else:
                 print("** class doesn't exist **")
def reviews(place_id):
    """methods GET and POST of the reviews by places (place_ID)
    """
    reviews_pl = storage.get("Place", place_id)

    if reviews_pl is None:
        abort(404)

    if request.method == 'GET':
        reviews_list = []
        for review in reviews_pl.reviews:
            reviews_list.append(review.to_dict())
        return jsonify(reviews_list)

    if request.method == 'POST':
        json_review = request.get_json()
        if json_review is None:
            abort(400, "Not a JSON")
        if not json_review.get("user_id"):
            abort(400, "Missing user_id")
        user_json = storage.get("User", json_review.get("user_id"))
        if user_json is None:
            abort(404)
        if not json_review.get("text"):
            abort(400, "Missing text")
        json_review["city_id"] = json_review.get("city_id")
        json_review["user_id"] = json_review.get("user_id")
        review = Place(**json_review)
        storage.new(review)
        storage.save()
        storage.reload()
        return jsonify(review.to_dict()), 201
Exemplo n.º 14
0
 def do_update(self, arg):
     """
         Updates an instance based on the class name and id by adding
         or updating attribute (save the change into the JSON file).Ex:
         $ update BaseModel 1234-1234-1234 email "*****@*****.**".
     """
     arg = arg.split()
     if len(arg) == 0:
         print("** class name missing **")
     elif arg[0] in self.list_of_classes:
         if len(arg) < 2:
             print("** instance id missing **")
         else:
             n = arg[0] + "." + arg[1]
             if n in objs:
                 if len(arg) < 3:
                     print("** attribute name missing **")
                 elif len(arg) < 4:
                     print("** value missing **")
                 else:
                     objs[n].__dict__[arg[2]] = arg[3]
                     '''print("SDAS;LDFNASDFLKASD;FLKAJSDF;LKASJDF;LKASJDF;LKASJ")
                     print(objs[n])'''
                     objs[n].save()
                     pineapple.reload()
             else:
                 print("** no instance found **")
     else:
         print("** class doesn't exist **")
Exemplo n.º 15
0
 def test_engine_010(self):
     """Tests reloading with all classes"""
     cwd = os.getcwd()
     filename = "file.json"
     baseobj = BaseModel()
     userobj = User()
     cityobj = City()
     ameobj = Amenity()
     placeobj = Place()
     reviewobj = Review()
     stateobj = State()
     id1 = baseobj.__class__.__name__ + '.' + baseobj.id
     id2 = userobj.__class__.__name__ + '.' + userobj.id
     id3 = cityobj.__class__.__name__ + '.' + cityobj.id
     id4 = ameobj.__class__.__name__ + '.' + ameobj.id
     id5 = placeobj.__class__.__name__ + '.' + placeobj.id
     id6 = reviewobj.__class__.__name__ + '.' + reviewobj.id
     id7 = stateobj.__class__.__name__ + '.' + stateobj.id
     # self.assertFalse(os.path.exists(filename))
     storage.save()
     self.assertTrue(os.path.exists(filename))
     self.assertTrue(len(storage.all()) > 0)
     storage._FileStorage__objects = {}
     self.assertEqual(storage.all(), {})
     storage.reload()
     alldic = storage.all()
     clist = [baseobj, userobj, cityobj,
              ameobj, placeobj, reviewobj, stateobj]
     for i, j in zip(clist, range(1, 7)):
         ids = "id" + str(j)
         self.assertFalse(i == alldic[eval(ids)])
         self.assertEqual(i.id, alldic[eval(ids)].id)
         self.assertEqual(i.__class__, alldic[eval(ids)].__class__)
Exemplo n.º 16
0
 def do_update(self, argv):
     """ updating an object"""
     check = 0
     argv = argv.split()
     if not argv:
         print("** class name missing **")
     elif argv[0] not in HBNBCommand.__allclasses:
         print("** class doesn't exist **")
     elif len(argv) < 2:
         print("** instance id missing **")
     elif argv[1] is not None:
         storage.reload()
         for k, v in storage.all().items():
             if v.id == argv[1]:
                 check = 1
         if check == 0:
             print("** no instance found **")
             return
         elif len(argv) == 2:
             print("** attribute name missing **")
             return
         elif len(argv) == 3:
             print("** value missing **")
             return
         else:
             new = argv[3]
             if hasattr(v, str(argv[2])):
                 new = type(getattr(v, argv[2]))(argv[3])
             v.__dict__[argv[2]] = new
             storage.save()
             return
Exemplo n.º 17
0
def reviews(place_id):
    """Retrieves the list of all reviews objects
    """
    reviewget = storage.get("Place", place_id)

    if reviewget is None:
        abort(404)

    if request.method == 'GET':
        listreviews = []
        for review in reviewget.reviews:
            listreviews.append(review.to_dict())
        return jsonify(listreviews)

    if request.method == 'POST':
        json_review = request.get_json()
        if json_review is None:
            abort(400, "Not a JSON")
        if not json_review.get('user_id'):
            abort(400, "Missing user_id")
        userget = storage.get("User", json_review.get("user_id"))
        if userget is None:
            abort(404)
        if not json_review.get("text"):
            abort(400, "Missing text")
        json_review["city_id"] = json_review.get(" city_id")
        json_review["user_id"] = json_review.get("user_id")
        review = Place(**json_review)
        storage.new(review)
        storage.save()
        storage.reload()
        return jsonify(review.to_dict()), 201
Exemplo n.º 18
0
 def do_update(self, line):
     """
     Updates an instance based on the class name and
     id by adding or updating attribute
     """
     args = line.split()
     if len(args) < 4:
         if len(args) == 0:
             print("** class name missing **")
         elif len(args) == 1:
             print("** instance id missing **")
         elif len(args) == 2:
             print("** value missing **")
         elif len(args) == 3:
             print("** value missing **")
     else:
         argCls = args[0]
         argId = args[1]
         argId = argCls + '.' + argId
         attrName = args[2]
         if self.is_number(args[3]):
             attrValue = int(args[3].replace('\"', ''))
         else:
             attrValue = args[3].replace('\"', '')
         storage.reload()
         myDict = storage.all()
         if argCls in self.cls:
             if argId in myDict:
                 myNewObj = myDict[argId]
                 setattr(myNewObj, attrName, attrValue)
                 myNewObj.save()
             else:
                 print("** no instance found **")
         else:
             print("** class doesn't exist **")
Exemplo n.º 19
0
 def do_update(self, arg):
     """ Update an instance baed on the class name
     and id by adding or updating attribute
     """
     args = split(arg)
     inst_list = storage.all()
     if args == []:
         print("** class name missing **")
     elif args[0] not in classes:
         print("** class doesn't exist **")
     elif len(args) == 1:
         print("** instance id missing **")
     elif len(args) == 2:
         print("** attribute name missing **")
     elif len(args) == 3:
         print("** value missing **")
     else:
         key_object = args[0] + "." + args[1]
         if key_object in inst_list:
             object = inst_list[key_object]
             setattr(object, args[2], args[3])
             storage.save()
             storage.reload()
         else:
             print("** no instance found **")
Exemplo n.º 20
0
 def test_reload(self):
     """ tests reload method of file_storage """
     myobj = BaseModel()
     __objects = storage.all()
     storage.reload()
     __objects_reloaded = storage.all()
     self.assertEqual(__objects, __objects_reloaded)
Exemplo n.º 21
0
    def do_destroy(self, *args):
        """deletes an instance based on the class name and id, must save the
        change in the JSON file)"""
        args = [ele for ele in args[0].split(' ')]
        if args[0] == '':
            print("** class name missing **")
            return
        if args[0] not in self.list_classes:
            print("** class doesn't exist **")
            return
        if len(args) != 2:
            print("** instance id missing **")
            return

        storage.reload()
        dict_objs = storage.all()
        if dict_objs is None or dict_objs == []:
            print("** no instance found **")
            return

        key = "{}.{}".format(args[0], args[1])
        if key in dict_objs.keys():
            del dict_objs[key]
            storage.save()
        else:
            print("** no instance found **")
Exemplo n.º 22
0
 def test_get_db_storage(self):
     """This test the get method in db_storage"""
     storage.reload()
     new_state = State(name="NewYork")
     storage.new(new_state)
     first_state_id = list(storage.all("State").values())[0].id
     self.assertEqual(type(storage.get("State", first_state_id)), State)
Exemplo n.º 23
0
 def do_update(self, args):
     """Returns the reference of the object updated"""
     v1 = args.split()
     if len(v1) == 0:
         print("** class name missing **")
     else:
         if v1[0] not in self.__valid_classes.keys():
             print("** class doesn't exist **")
         else:
             try:
                 cl_id = v1[1]
                 storage.reload()
                 objs = storage.all()
                 cl_id = "{:s}.{:s}".format(v1[0], cl_id)
                 if cl_id not in objs.keys():
                     print("** no instance found **")
                 else:
                     if len(v1) == 2:
                         print("** attribute name missing **")
                     elif len(v1) == 3:
                         print("** value missing **")
                     elif len(v1) >= 4:
                         attr = v1[2]
                         if attr not in self.__blacklist:
                             valid = ""
                             val = v1[3]
                             for c in val:
                                 if c in self.__whitelist:
                                     valid += c
                             if valid.isnumeric():
                                 valid = int(valid)
                             setattr(objs[cl_id], attr, valid)
                             storage.save()
             except IndexError:
                 print("** instance id missing **")
Exemplo n.º 24
0
def delnotif(notif_id):
    """
    delete a notification
    """
    response_dict = {}
    response_dict["error"] = "invalid parameter"
    response_dict["usage"] = "/notif/<user_id>"
    response_dict["error_code"] = "8"
    try:
        uuid_obj = UUID(notif_id, version=4)
    except ValueError:
        return make_response(jsonify(response_dict), 202)

    notif = storage.get(Notification, notif_id)
    if not notif:
        return make_response(jsonify(response_dict), 202)
    else:
        storage.delete(notif)
        storage.save()
        storage.reload()
        return make_response(jsonify({}), 200)

    unknown_dict = {}
    unknown_dict["error"] = "unknown error"
    unknown_dict["error_code"] = "0"
    return make_response(jsonify(unknown_dict), 404)
Exemplo n.º 25
0
def places(city_id):
    """methods GET and POST of the places by cities (city_ID)
    """
    places_ct = storage.get("City", city_id)

    if places_ct is None:
        abort(404)

    if request.method == 'GET':
        places_list = []
        for place in places_ct.places:
            places_list.append(place.to_dict())
        return jsonify(places_list)

    if request.method == 'POST':
        json_place = request.get_json()
        if json_place is None:
            abort(400, "Not a JSON")
        if not json_place.get("name"):
            abort(400, "Missing name")
        if not json_place.get("user_id"):
            abort(400, "Missing user_id")
        user_json = storage.get("User", json_place.get("user_id"))
        if user_json is None:
            abort(404)
        json_place["city_id"] = city_id
        json_place["user_id"] = json_place.get("user_id")
        place = Place(**json_place)
        storage.new(place)
        storage.save()
        storage.reload()
        return jsonify(place.to_dict()), 201
Exemplo n.º 26
0
    def test_City(self):
        """Task 9
        Tests `City` class.
        """
        # Normal use: no args
        c1 = City()
        self.assertIsInstance(c1, City)

        # attr `name` defaults to empty string
        self.assertIsInstance(c1.name, str)
        self.assertEqual(c1.name, '')

        # attr `state_id` defaults to empty string
        self.assertIsInstance(c1.state_id, str)
        self.assertEqual(c1.state_id, '')

        # City can be serialized to JSON by FileStorage
        c1.name = 'test'
        c1.state_id = 'test'
        self.assertIn(c1, storage._FileStorage__objects.values())
        c1.save()
        with open(storage._FileStorage__file_path, encoding='utf-8') as file:
            content = file.read()
        key = c1.__class__.__name__ + '.' + c1.id
        self.assertIn(key, json.loads(content))

        # City can be deserialized from JSON by FileStorage
        self.assertIn(key, storage._FileStorage__objects.keys())
        storage._FileStorage__objects = dict()
        storage.reload()
        self.assertIn(key, storage._FileStorage__objects.keys())
Exemplo n.º 27
0
    def do_destroy(self, args):
        ''' deletes instance based on class name and id
        '''

        if len(args) == 0:
            print("** class name missing **")
            return
        all_obj = storage.all()
        arg_list = list(args.split())

        try:
            instance_id = "{0}.{1}".format(arg_list[0], arg_list[1])

            if arg_list[0] in self.classes:
                storage.reload()
                all_obj = storage.all()
                if instance_id in all_obj.keys():
                    del (all_obj[instance_id])
                    storage.save()
                else:
                    print("** no instance found **")
            elif arg_list[0] not in self.classes:
                print("** class doesn't exist **")
        except:
            print("** instance id missing **")
            return
Exemplo n.º 28
0
def new_city(state_id):
    """Creates a new state"""
    victim = {}
    state_obj = storage.get('State', state_id)

    if state_obj is None:
        abort(404)
    city_data = request.get_json()
    if city_data is None:
        abort(400, "Not a JSON")
    if not city_data.get('value'):
        abort(400, "Missing value")
    city_data['state_id'] = state_id
    for element in state_obj.victims:
        if element.state_id == state_id:
            victim = element.to_dict()
    print(victim)
    if not victim:
        new_victim = Victim(**city_data)
        storage.new(new_victim)
        storage.save()
        storage.reload()
        return make_response(jsonify(new_victim.to_dict())), 201
    else:
        victim_update = storage.get('Victim', victim.get('id'))
        victim_val = int(city_data['value']) + int(victim.get('value'))
        setattr(victim_update, 'value', victim_val)
        victim_update.save()
        return make_response(jsonify(victim_update.to_dict())), 201
Exemplo n.º 29
0
 def test_storage_reload(self):
     """tests if reload() works"""
     old_dict = storage.all()
     storage.reload()
     reloaded_dict = storage.all()
     """tests if reload() returns dictionary"""
     self.assertEqual(old_dict.keys(), reloaded_dict.keys())
Exemplo n.º 30
0
 def test_reload_file_dictionary(self):
     """tests reload method returns dictionary"""
     m = BaseModel()
     m.save()
     storage.reload()
     obj = storage.all()
     self.assertEqual(dict, type(obj))