Ejemplo n.º 1
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 = FileStorage()
     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()
Ejemplo n.º 2
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 = FileStorage()
     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 **")
 def test_Filestorage_new(self):
     """Tests new method"""
     tmpstor = FileStorage()
     tmpdic = tmpstor.all()
     Bob = User()
     Bob.id = 1996
     Bob.name = "Robert"
     tmpstor.new(Bob)
     k = "{}.{}".format(Bob.__class__.__name__, str(Bob.id))
     self.assertIsNotNone(tmpdic[k])
Ejemplo n.º 4
0
 def test_new(self):
     """test when new is created"""
     storage = FileStorage()
     obj = storage.all()
     user = User()
     user.id = 123455
     user.name = "Kevin"
     storage.new(user)
     key = user.__class__.__name__ + "." + str(user.id)
     self.assertIsNotNone(obj[key])
Ejemplo n.º 5
0
 def test_new(self):
     """ test method new """
     store = FileStorage()
     store_dict = store.all()
     gary = User()
     gary.id = 69
     gary.name = "Morpheous"
     store.new(gary)
     key = "{}.{}".format(gary.__class__.__name__, gary.id)
     self.assertIsNotNone(store_dict[key])
Ejemplo n.º 6
0
 def test_save(self):
     for item in self.test_objects:
         self.storage.new(item[2])
     self.storage.save()
     new_storage = FileStorage()
     new_storage._FileStorage__objects = {}
     new_storage._FileStorage__file_path = "atestfile.json"
     new_storage.reload()
     for key in self.storage.all():
         self.assertIn(key, new_storage.all())
Ejemplo n.º 7
0
 def cities(self):
     """ Getter that return a list of City instances """
     # <all> method in file_storage.py returns the dictionary .__objects
     # the __objects contains all created instances
     obj_dictionary = FileStorage.all()
     city_instances = []
     for key, value in obj_dictionary.items():
         if value.state_id == self.id:
             city_instances.append(value)
     return (city_instances)
Ejemplo n.º 8
0
 def test_new(self):
     """test if new set key properly with user as example"""
     storage = FileStorage()
     obj = storage.all()
     user = User()
     user.id = "38f22813-2753-4d42-b37c-57a17f1e4f88"
     user.name = "Betty"
     storage.new(user)
     key = user.__class__.__name__ + "." + str(user.id)
     self.assertIsNotNone(obj[key])
Ejemplo n.º 9
0
 def test_using_json(self):
     '''Check serialization and deserialization json file'''
     storage = FileStorage()
     all_objs = storage.all()
     self.assertIsInstance(all_objs, dict, "es diccionario")  # Test all
     self.obj.name = "Betty"
     self.obj.my_number = 89
     self.obj.save()
     with open("file.json", "r", encoding='utf-8') as f:
         self.assertTrue(self.obj.name in f.read())  # Test save
Ejemplo n.º 10
0
 def test_new(self):
     """
     Tests the new method
     """
     fs = FileStorage()
     bm = BaseModel()
     bmc = BaseModel.__class__.__name__
     bmid = bm.id
     dic = fs.all()
     fs.new(bm)
Ejemplo n.º 11
0
 def test_delete(self):
     """ Tests delete method to delete objects in __object """
     storage = FileStorage()
     obj_dict = storage.all()
     usr = User()
     usr.id = 12345
     storage.new(usr)
     storage.delete(usr)
     key = usr.__class__.__name__ + "." + str(usr.id)
     self.assertFalse(key in obj_dict.keys())
Ejemplo n.º 12
0
class testFileStorage(unittest.TestCase):
    '''Testing the FileStorage class'''
    def setUp(self):
        '''Initializing classes'''

        self.storage = FileStorage()
        self.my_model = BaseModel()

    def tearDown(self):
        '''Cleaning up.'''

        try:
            os.remove("file.json")
        except FileNotFoundError:
            pass

    def test_all_return_type(self):
        ''' Tests the data type of the return value of the all method.'''

        storage_all = self.storage.all()
        self.assertIsInstance(storage_all, dict)

    def test_new_method(self):
        '''Tests that the new method sets the right key and value pair
            in the FileStorage.__object attribute'''

        self.storage.new(self.my_model)
        key = str(self.my_model.__class__.__name__ + "." + self.my_model.id)
        self.assertTrue(key in self.storage._FileStorage__objects)

    def test_objects_value_type(self):
        '''Tests that the type of value contained in the FileStorage.__object
            is of type obj.__class__.__name__'''

        self.storage.new(self.my_model)
        key = str(self.my_model.__class__.__name__ + "." + self.my_model.id)
        val = self.storage._FileStorage__objects[key]
        self.assertIsInstance(self.my_model, type(val))

    def test_save_file_exists(self):
        ''' Tests that a file gets created with the name file.json'''

        self.storage.save()
        self.assertTrue(os.path.isfile("file.json"))

    def test_save_file_read(self):
        '''Testing the contents of the files inside the file.json'''

        self.storage.save()
        self.storage.new(self.my_model)

        with open("file.json", encoding="UTF8") as fd:
            content = json.load(fd)

        self.assertTrue(type(content) is dict)
Ejemplo n.º 13
0
 def default(self, line):
     """
     Default method for line
     """
     methods = {'all': self.do_all,
                'show': self.do_show,
                'destroy': self.do_destroy,
                'update': self.do_update}
     arg = re.split(r'\.', line)
     obj = arg[0]
     arg1 = re.split('[()]', arg[1])
     func = arg1[0]
     uid = ''
     flag = 0
     if obj in self.classes:
         command = eval(arg[0])
         if func == 'all':
             funtion = methods[func]
             funtion(obj)
         elif func == "count":
             storage = FileStorage()
             dict1 = storage.all()
             count = 0
             for key, val in dict1.items():
                 if command == val.__class__:
                     count += 1
             print(count)
         elif func in methods:
             funtion = methods[func]
             if func == 'update':
                 uid = eval(arg1[1])
                 new_list = list(uid)
                 print(type(new_list[1]))
                 uid = new_list[0]
                 if isinstance(new_list[1], dict):
                     for key, value in new_list[1].items():
                         attr = key
                         val = str(value)
                         line = obj + " " + uid + " " + attr + " " + val
                         funtion(line)
                         flag = 1
                 else:
                     attr = new_list[1]
                     val = str(new_list[2])
                     line = obj + " " + uid + " " + attr + " " + val
             else:
                 if arg1[1] != '':
                     uid = eval(arg1[1])
                 line = obj + " " + uid
             if flag == 0:
                 funtion(line)
         else:
             print("*** Unknown syntax:", line)
     else:
         print("*** Unknown syntax:", line)
Ejemplo n.º 14
0
class Test_FileStorage(unittest.TestCase):
    """
    Test the file storage class
    """
    def setUp(self):
        self.arr = []
        self.cli = HBNBCommand()
        self.store = FileStorage()

        test_args = {
            'updated_at': datetime(2017, 2, 12, 00, 31, 53, 331997),
            'id': 'f519fb40-1f5c-458b-945c-2ee8eaaf4900',
            'created_at': datetime(2017, 2, 12, 00, 31, 53, 331900)
        }
        self.model = BaseModel(test_args)

        self.test_len = 0
        if os.path.isfile("file.json"):
            self.test_len = len(self.store.all())

    def test_all(self):
        self.assertEqual(len(self.store.all()), self.test_len)

    def test_new(self):
        self.assertEqual(len(self.store.all()), self.test_len)
        self.model.save()
        self.assertEqual(len(self.store.all()), self.test_len + 1)
        a = BaseModel()
        a.save()
        self.assertEqual(len(self.store.all()), self.test_len + 2)
        self.cli.do_destroy("BaseModel f519fb40-1f5c-458b-945c-2ee8eaaf4900")
        self.cli.do_destroy("BaseModel " + a.id)

    def test_save(self):
        self.test_len = len(self.store.all())
        a = BaseModel()
        a.save()
        self.assertEqual(len(self.store.all()), self.test_len + 1)
        b = User()
        self.assertNotEqual(len(self.store.all()), self.test_len + 2)
        b.save()
        self.assertEqual(len(self.store.all()), self.test_len + 2)
        self.cli.do_destroy("BaseModel " + a.id)
        self.cli.do_destroy("User " + b.id)

    def test_reload(self):
        pass
Ejemplo n.º 15
0
 def test_delete(self):
     """Tests the method delete (obj, called from destroy method)"""
     storage = FileStorage()
     state = State()
     state.id = 123455
     state.name = "Medellin"
     key = state.__class__.__name__ + "." + str(state.id)
     storage.new(state)
     storage.delete(state)
     obj = storage.all()
     self.assertTrue(key not in obj.keys())
Ejemplo n.º 16
0
 def test_new(self):
     """Tests the new method"""
     temp_storage = FileStorage()
     temp_dict = temp_storage.all()
     Holberton = User()
     Holberton.id = 972
     Holberton.name = "Holberton"
     temp_storage.new(Holberton)
     class_name = Holberton.__class__.__name__
     key = "{}.{}".format(class_name, str(Holberton.id))
     self.assertIsNotNone(temp_dict[key])
Ejemplo n.º 17
0
 def test_all_no_class(self):
     """Test all without class"""
     return True
     fs = FileStorage()
     new_state1 = State()
     fs.new(new_state1)
     fs.save()
     new_user1 = User()
     fs.new(new_user1)
     fs.save()
     self.assertEqual(8, len(fs.all()))
Ejemplo n.º 18
0
 def test_all_no_specification(self):
     ''' tests all when no class is passed '''
     return True
     fs = FileStorage()
     new_state1 = State()
     fs.new(new_state1)
     fs.save()
     new_user1 = User()
     fs.new(new_user1)
     fs.save()
     self.assertEqual(8, len(fs.all()))
Ejemplo n.º 19
0
 def test_all_state(self):
     """Tests all method with State class"""
     storage = FileStorage()
     state = State()
     state.name = "Minnesota"
     state.id = "55975"
     storage.new(state)
     obj = storage.all(State)
     key = state.__class__.__name__ + "." + str(state.id)
     self.assertIn(key, obj)
     self.assertIsInstance(obj[key], State)
Ejemplo n.º 20
0
 def test_new(self):
     """ Tests method: new (saves new object into dictionary)
     """
     m_storage = FileStorage()
     instances_dic = m_storage.all()
     user1 = User()
     user1.id = 999999
     user1.name = "user1"
     m_storage.new(user1)
     key = user1.__class__.__name__ + "." + str(user1.id)
     self.assertIsNotNone(instances_dic[key])
Ejemplo n.º 21
0
 def test_new(self):
     """Tests the new method"""
     temp_storage = FileStorage()
     temp_dict = temp_storage.all()
     notrebloh = User()
     notrebloh.id = 972
     notrebloh.name = "notrebloh"
     temp_storage.new(notrebloh)
     class_name = notrebloh.__class__.__name__
     key = "{}.{}".format(class_name, str(notrebloh.id))
     self.assertIsNotNone(temp_dict[key])
Ejemplo n.º 22
0
 def test_reload_2(self):
     '''Tests reload normal'''
     Storage = FileStorage()
     b1 = BaseModel()
     Storage.new(b1)
     Storage.save()
     Storage.reset()
     Storage.reload()
     self.assertTrue(Storage.all()["BaseModel.{}".format(b1.id)])
     self.assertTrue(Storage._FileStorage__objects["BaseModel.{}".format(
         b1.id)])
Ejemplo n.º 23
0
    def test_all(self):
        """
        Test the `all` method fills
        values into the `__objects` dict.
        """

        fs = FileStorage()
        dic = fs.all()
        self.assertIsNotNone(dic)
        self.assertEqual(type(dic), dict)
        self.assertIs(dic, fs._FileStorage__objects)
Ejemplo n.º 24
0
 def test_des_and_serialization(self):
     '''check serialization and deserialization'''
     storage = FileStorage()
     all_objs = storage.all()
     self.assertIsInstance(all_objs, dict, "es diccionario")  # Test all
     my_model = User()
     my_model.name = "Paparoachchchch"
     my_model.my_number = 95
     my_model.save()
     with open("file.json", "r", encoding='utf-8') as f:
         self.assertTrue(my_model.name in f.read())  # Test save
Ejemplo n.º 25
0
class TestFileStorage(unittest.TestCase):
    """This is Unittest for the method FileStorage"""
    def setUp(self):
        """This is the setup method for Unittesting"""
        self.otter = FileStorage()
        self.otter.file_path = "test_file.json"
        self.otter.reload()
        self.objects = self.otter.objects
        self.UrchinA = self.objects["Amenity.\
19b4933a-55d0-4287-99a0-773c1dcab528"]
        self.UrchinB = self.objects["BaseModel.\
7152df91-ec26-4595-bf75-fd84f02a3bd9"]
        self.UrchinC = self.objects["City.\
f76cbf19-eb40-4901-88ca-569684490fd1"]
        self.UrchinP = self.objects["Place.\
52cf288d-f402-4564-a91f-06c71004c6b7"]
        self.UrchinR = self.objects["Review.\
ac984526-613a-4ec8-933d-ab32a5f924b9"]
        self.UrchinS = self.objects["State.\
125b2cf3-66d9-4185-b442-e8a49cb7801d"]
        self.UrchinU = self.objects["User.\
bf654f25-d81f-4d02-a3c0-1777c5bfeda5"]

    def test_all(self):
        """This is the Unittest for the method all"""
        test_dict = self.otter.all()
        self.assertIsInstance(test_dict, dict)
        for key in test_dict:
            self.assertEqual(test_dict[key], self.otter.objects[key])

    def test_new(self):
        """This is a Unittest for the method new"""
        new_obj = copy.deepcopy(self.UrchinB)
        new_obj.id = "7152df91-ec26-4595-bf75-fd84f02atest"
        self.otter.new(new_obj)
        otter_dict = self.otter.objects
        test_obj = otter_dict["BaseModel.7152df91-ec26-4595-bf75-fd84f02atest"]
        self.assertIsInstance(test_obj, BaseModel)
        self.assertEqual(test_obj.id, "7152df91-ec26-4595-bf75-fd84f02atest")

    def test_save(self):
        """This is a Unittest for the the method save"""
        if os.path.isfile("test_save.json"):
            os.remove("test_save.json")
        self.otter.reload()
        self.otter.file_path = "test_save.json"
        self.otter.save()
        with open(self.otter.file_path, "r") as FILE:
            test_save_dict = json.loads(FILE.read())
        with open("test_file.json", "r") as FILE:
            test_file_dict = json.loads(FILE.read())
        self.assertDictEqual(test_save_dict, test_file_dict)
        os.remove("test_save.json")
        self.otter.file_path = "test_file.json"
Ejemplo n.º 26
0
 def test_n(self):
     """
     """
     storage = FileStorage()
     obj = storage.all()
     user = User()
     user.id = 12345
     user.name = "Karen"
     storage.new(user)
     key = user.__class__.__name__ + "." + str(user.id)
     self.assertIsNotNone(obj[key])
Ejemplo n.º 27
0
 def test_all_instance(self):
     am = Amenity()
     keyam = str(am.__class__.__name__) + '.' + str(am.id)
     ci = City()
     keyci = str(ci.__class__.__name__) + '.' + str(ci.id)
     pl = Place()
     keypl = str(pl.__class__.__name__) + '.' + str(pl.id)
     rev = Review()
     keyrev = str(rev.__class__.__name__) + '.' + str(rev.id)
     st = State()
     keyst = str(st.__class__.__name__) + '.' + str(st.id)
     us = User()
     keyus = str(us.__class__.__name__) + '.' + str(us.id)
     all_obj = FileStorage()
     self.assertTrue(keyam in all_obj.all())
     self.assertTrue(keyci in all_obj.all())
     self.assertTrue(keypl in all_obj.all())
     self.assertTrue(keyrev in all_obj.all())
     self.assertTrue(keyst in all_obj.all())
     self.assertTrue(keyus in all_obj.all())
Ejemplo n.º 28
0
 def test_new(self):
     """ Cheking when new object is created
     """
     fileStorage = FileStorage()
     new_obj = fileStorage.all()
     city = City()
     city.state_id = "123abc"
     city.name = "Cali"
     fileStorage.new(city)
     k = "{}.{}".format(type(city).__name__, city.id)
     self.assertIsNotNone(new_obj[k])
Ejemplo n.º 29
0
    def test_create_00(self):
        ''' Tests for the create command. '''
        # Create console session.
        cons = self.create_session()

        # Test "create {} name='California'".
        with patch('sys.stdout', new=StringIO()) as Output:
            cons.onecmd('create State name=\"California\"')
            create_stdout = Output.getvalue().strip()
            create_stdout = 'State.{}'.format(create_stdout)
            self.assertTrue(create_stdout in Storage.all())
Ejemplo n.º 30
0
    def test_class_variables(self):
        """ slkjdfgh """
        subject = FileStorage()
        to_d = []
        if os.path.exists('file.json'):
            os.remove('file.json')
        for e in subject.all().keys():
            to_d.append(subject.all()[e])
        for e in to_d:
            del subject.all()[e.__class__.__name__ + '.' + e.id]

        # check attributes exist
        self.assertFalse(hasattr(FileStorage, '__file_path'))
        self.assertFalse(hasattr(FileStorage, '__objects'))
        self.assertFalse(hasattr(subject, '__file_path'))
        self.assertFalse(hasattr(subject, '__objects'))
        del subject
        if os.path.exists('file.json'):
            print('file still exists')
            os.remove('file.json')
Ejemplo n.º 31
0
class Test_FileStorage(unittest.TestCase):
    """
    Test FileStorage
    """
    def setUp(self):
        self.store = FileStorage()

        test_args = {
            'updated_at': datetime(2019, 7, 6, 1, 0, 0, 100000),
            'id': '12345678-0123-0123-0123-012345678901',
            'created_at': datetime(2019, 7, 5, 1, 0, 0, 100000)
        }
        self.model = BaseModel(test_args)

        self.test_len = 0
        if os.path.isfile("file.json"):
            self.test_len = len(self.store.all())

    def tearDown(self):
        import os
        if os.path.isfile("file.json"):
            os.remove('file.json')

    def test_all(self):
        self.assertEqual(len(self.store.all()), self.test_len)

    def test_new(self):
        self.assertEqual(len(self.store.all()), self.test_len)
        self.model.save()
        self.assertEqual(len(self.store.all()), self.test_len + 1)
        a = BaseModel()
        a.save()
        self.assertEqual(len(self.store.all()), self.test_len + 2)

    def test_save(self):
        self.test_len = len(self.store.all())
        a = BaseModel()
        a.save()
        self.assertEqual(len(self.store.all()), self.test_len + 1)
        b = User()
        self.assertNotEqual(len(self.store.all()), self.test_len + 2)
        b.save()
        self.assertEqual(len(self.store.all()), self.test_len + 2)

    def test_reload(self):
        pass
 def test_new(self):
     """
     Tests the new method
     """
     new_fs = FileStorage()
     dict_2 = new_fs.all()
     Holbie = User()
     Holbie.id = 8888
     Holbie.name = "Dennis"
     new_fs.new(Dennis)
     key = new_fs.__class__.__name__ + "." + str(new_fs.id)
     self.assertIsNotNone(dict_2[key])
Ejemplo n.º 33
0
 def do_count(self, args):
     '''
         Counts/retrieves the number of instances.
     '''
     obj_list = []
     storage = FileStorage()
     storage.reload()
     objects = storage.all()
     try:
         if len(args) != 0:
             eval(args)
     except NameError:
         print("** class doesn't exist **")
         return
     for key, val in objects.items():
         if len(args) != 0:
             if type(val) is eval(args):
                 obj_list.append(val)
         else:
             obj_list.append(val)
     print(len(obj_list))
Ejemplo n.º 34
0
 def do_update(self, args):
     '''
         Update an instance based on the class name and id
         sent as args.
     '''
     storage = FileStorage()
     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()
Ejemplo n.º 35
0
    def do_all(self, args):
        '''
            Prints all string representation of all instances
            based or not on the class name.
        '''
        obj_list = []
        storage = FileStorage()
        storage.reload()
        objects = storage.all()
        try:
            if len(args) != 0:
                eval(args)
        except NameError:
            print("** class doesn't exist **")
            return
        for key, val in objects.items():
            if len(args) != 0:
                if type(val) is eval(args):
                    obj_list.append(val)
            else:
                obj_list.append(val)

        print(obj_list)
Ejemplo n.º 36
0
class Test_FileStorage(unittest.TestCase):
    """
    Test the file storage class
    """

    def setUp(self):
        self.store = FileStorage()

        test_args = {'updated_at': datetime(2017, 2, 12, 00, 31, 53, 331997),
                     'id': 'f519fb40-1f5c-458b-945c-2ee8eaaf4900',
                     'created_at': datetime(2017, 2, 12, 00, 31, 53, 331900)}
        self.model = BaseModel(**test_args)

        self.test_len = len(self.store.all())

#    @classmethod
#    def tearDownClass(cls):
#        import os
#        if os.path.isfile("test_file.json"):
#            os.remove('test_file.json')

    def test_all(self):
        self.assertEqual(len(self.store.all()), self.test_len)

    def test_all_arg(self):
        """test all(State)"""
        new_obj = State()
        new_obj.save()
        everything = self.store.all()
        nb_states = 0
        for e in everything.values():
            if e.__class__.__name__ == "State":
                nb_states += 1
        self.assertEqual(len(self.store.all("State")), nb_states)

# should test with a bad class name

    def test_new(self):
        # note: we cannot assume order of test is order written
        test_len = len(self.store.all())
        # self.assertEqual(len(self.store.all()), self.test_len)
        new_obj = State()
        new_obj.save()
        self.assertEqual(len(self.store.all()), test_len + 1)
        a = BaseModel()
        a.save()
        self.assertEqual(len(self.store.all()), self.test_len + 2)

    def test_save(self):
        self.test_len = len(self.store.all())
        a = BaseModel()
        a.save()
        self.assertEqual(len(self.store.all()), self.test_len + 1)
        b = User()
        self.assertNotEqual(len(self.store.all()), self.test_len + 2)
        b.save()
        self.assertEqual(len(self.store.all()), self.test_len + 2)

    def test_reload(self):
        self.model.save()
        a = BaseModel()
        a.save()
        self.store.reload()
        for value in self.store.all().values():
            self.assertIsInstance(value.created_at, datetime)

    def test_state(self):
        """test State creation with an argument"""
        a = State(name="Kamchatka", id="Kamchatka666")
        a.save()
        self.assertIn("Kamchatka666", self.store.all("State").keys())

    def test_count(self):
        """test count all"""
        test_len = len(self.store.all())
        a = Amenity(name="test_amenity")
        a.save()
        self.assertEqual(test_len + 1, self.store.count())

    def test_count_arg(self):
        """test count with an argument"""
        test_len = len(self.store.all("Amenity"))
        a = Amenity(name="test_amenity_2")
        a.save()
        self.assertEqual(test_len + 1, self.store.count("Amenity"))

    def test_count_bad_arg(self):
        """test count with dummy class name"""
        self.assertEqual(-1, self.store.count("Dummy"))

    def test_get(self):
        """test get with valid cls and id"""
        a = Amenity(name="test_amenity3", id="test_3")
        a.save()
        result = self.store.get("Amenity", "test_3")
        self.assertEqual(a.name, result.name)
        self.assertEqual(a.created_at, result.created_at)

    def test_get_bad_cls(self):
        """test get with invalid cls"""
        result = self.store.get("Dummy", "test")
        self.assertIsNone(result)

    def test_get_bad_id(self):
        """test get with invalid id"""
        result = self.store.get("State", "very_bad_id")
        self.assertIsNone(result)
Ejemplo n.º 37
0
class testFileStorage(unittest.TestCase):
    '''
        Testing the FileStorage class
    '''

    def setUp(self):
        '''
            Initializing classes
        '''
        self.storage = FileStorage()
        self.my_model = BaseModel()

    def tearDown(self):
        '''
            Cleaning up.
        '''

        try:
            os.remove("file.json")
        except FileNotFoundError:
            pass

    def test_all_return_type(self):
        '''
            Tests the data type of the return value of the all method.
        '''
        storage_all = self.storage.all()
        self.assertIsInstance(storage_all, dict)

    def test_new_method(self):
        '''
            Tests that the new method sets the right key and value pair
            in the FileStorage.__object attribute
        '''
        self.storage.new(self.my_model)
        key = str(self.my_model.__class__.__name__ + "." + self.my_model.id)
        self.assertTrue(key in self.storage._FileStorage__objects)

    def test_objects_value_type(self):
        '''
            Tests that the type of value contained in the FileStorage.__object
            is of type obj.__class__.__name__
        '''
        self.storage.new(self.my_model)
        key = str(self.my_model.__class__.__name__ + "." + self.my_model.id)
        val = self.storage._FileStorage__objects[key]
        self.assertIsInstance(self.my_model, type(val))

    def test_save_file_exists(self):
        '''
            Tests that a file gets created with the name file.json
        '''
        self.storage.save()
        self.assertTrue(os.path.isfile("file.json"))

    def test_save_file_read(self):
        '''
            Testing the contents of the files inside the file.json
        '''
        self.storage.save()
        self.storage.new(self.my_model)

        with open("file.json", encoding="UTF8") as fd:
            content = json.load(fd)

        self.assertTrue(type(content) is dict)

    def test_the_type_file_content(self):
        '''
            testing the type of the contents inside the file.
        '''
        self.storage.save()
        self.storage.new(self.my_model)

        with open("file.json", encoding="UTF8") as fd:
            content = fd.read()

        self.assertIsInstance(content, str)

    def test_reaload_without_file(self):
        '''
            Tests that nothing happens when file.json does not exists
            and reload is called
        '''

        try:
            self.storage.reload()
            self.assertTrue(True)
        except:
            self.assertTrue(False)