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 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())
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))
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()
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()
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)
#!/usr/bin/python3 """This module instantiates an object of class FileStorage""" from os import getenv if getenv('HBNB_TYPE_STORAGE') == 'db': from models.engine.db_storage import DBStorage storage = DBStorage() storage.reload() else: from models.engine.file_storage import FileStorage storage = FileStorage() storage.reload()
#!/usr/bin/python3 """ TEST TO CHECK COMMENTS """ from models.engine.file_storage import FileStorage storage = FileStorage() storage.reload()
class Test_FileStorage(unittest.TestCase): """ Test the file storage class """ def setUp(self): self.store = FileStorage() test_args = { 'name': 'wifi', '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 = Amenity(test_args) self.model.save() self.test_len = len(self.store.all()) def tearDown(self): self.store.delete(self.model) # @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_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) self.store.delete(a) self.store.delete(new_obj) 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.store.delete(a) self.store.delete(b) def test_reload(self): a = BaseModel() a.save() self.store.reload() for value in self.store.all().values(): self.assertIsInstance(value.created_at, datetime) self.store.delete(a) def test_state(self): """test State creation with an argument""" pass def test_get(self): """Test retrieving an object""" my_list = ["name", "id", "created_at", "updated_at"] a = self.store.get("Amenity", 'f519fb40-1f5c-458b-945c-2ee8eaaf4900') for k in my_list: self.assertIsNotNone(getattr(a, k, None)) self.assertIsNone(getattr(a, "fake_key", None)) b = self.store.get(None, 'invalid-id') self.assertIsNone(b) self.store.delete(self.model) def test_count(self): """Test storage count""" self.assertEqual(len(self.store.all()), 1) a = Amenity(name="Bob") a.save() self.assertEqual(len(self.store.all()), 2) self.store.delete(a)
#!/usr/bin/python3 """ Test delete feature """ from models.engine.file_storage import FileStorage from models.state import State fs = FileStorage() # All States all_states = fs.all(State) print("All States: {}".format(len(all_states.keys()))) for state_key in all_states.keys(): print(all_states[state_key]) # Create a new State new_state = State() new_state.name = "California" fs.new(new_state) fs.save() print("New State: {}".format(new_state)) # All States all_states = fs.all(State) print("All States: {}".format(len(all_states.keys()))) for state_key in all_states.keys(): print(all_states[state_key]) # Delete the new State fs.delete(new_state) # All States
def setUp(self): 'called multiple times, once before each test' self.new_inst = FileStorage()
def test_FileStorage_instantiation(self): """Tests instantiation""" temp_storage = FileStorage() self.assertIsInstance(temp_storage, FileStorage)
class TestFileStorage(unittest.TestCase): ''' class for test of file storage module tests for all method -- returns dict and format of dict new method -- adds new pair to object/file storage instance save -- test stoarage and extraction of storage file ''' temp_path = "" fs_attr = FileStorage() def setUp(self): '''init filestorage instance for test case''' FileStorage._FileStorage__objects = {} TestFileStorage.temp_path = FileStorage._FileStorage__file_path FileStorage._FileStorage__file_path = "file.json" def tearDown(self): '''delete file for filestorage''' try: os.remove('file.json') except: pass FileStorage._FileStorage__file_path = TestFileStorage.temp_path def testAll(self): ''' test all() should return dict ''' test_store = FileStorage() new_base = BaseModel() test_store.new(new_base) self.assertEqual(type(test_store.all()), dict) def testDictObj(self): ''' test all() returns valid dict contents ''' new_dict = { "BaseModel.1234": { "att1": 1, "att2": 2 }, "BaseModel.4321": { "att3": 3, "att4": 4 } } FileStorage._FileStorage__objects = new_dict self.assertEqual(new_dict, TestFileStorage.fs_attr.all()) def testNew(self): ''' test new() adds pair to storage instance ''' test_s = FileStorage() new_base = BaseModel() test_s.new(new_base) self.assertEqual(type(test_s.all()), dict) self.assertEqual(len(test_s.all()), 1) self.assertEqual(test_s.all()["BaseModel.{}".format(new_base.id)], new_base) def testSave(self): ''' test save() storage ''' new_base1 = BaseModel() new_base2 = BaseModel() FileStorage().new(new_base1) FileStorage().new(new_base2) FileStorage().save() self.assertTrue(os.path.exists('file.json')) with open("file.json", "r") as file: self.assertEqual(json.loads(file.read()), { key: val.to_dict() for key, val in FileStorage().all().items() }) def testRelaod(self): ''' test reload() data can be saved to and loadedfrom json ''' f = storage._FileStorage__file_path self.assertFalse(os.path.exists(f)) storage.reload() self.assertFalse(storage.all()) new_base1 = BaseModel() storage.save() self.assertTrue(os.path.exists(f)) with open(f, "r") as file: loaded_json = json.load(file) cmp_json = {key: val.to_dict() for key, val in storage.all().items()} self.assertEqual(cmp_json, loaded_json)
def setUp(self): """setup method""" self.my_storage = FileStorage()
#!/usr/bin/python3 """ Test delete feature """ from models.engine.file_storage import FileStorage from models.state import State fs = FileStorage() # All States print("All States: {}".format(fs.all(State))) # Create a new State new_state = State() new_state.name = "California" fs.new(new_state) fs.save() print("New State: {}".format(fs.all(new_state))) # All States print("All States: {}".format(fs.all(State))) # Delete the new State fs.delete(new_state) # All States print("All States: {}".format(fs.all(State)))
class TestFileStorage(unittest.TestCase): @classmethod def setUpClass(cls): """sepup class""" print('setupClass') @classmethod def tearDownClass(cls): """teardownclass""" print('teardownClass') def setUp(self): """setup method""" self.my_storage = FileStorage() def tearDown(self): """tearDown""" print('tearDown\n') # ---------------task 5 ---------------- def test_file_path(self): self.assertTrue(isinstance(self.my_storage._FileStorage__file_path, str)) def test_all(self): objects = self.my_storage.all() self.assertTrue(isinstance(objects, dict)) def test_all_not_none(self): objects = self.my_storage.all() self.assertIsNotNone(objects) def test_all_object_attr(self): objects = self.my_storage.all() self.assertIs(objects, self.my_storage._FileStorage__objects) def test_new(self): my_base = BaseModel() self.my_storage.new(my_base) key = my_base.__class__.__name__ + '.' + str(my_base.id) self.assertIn(key, self.my_storage._FileStorage__objects.keys()) def test_save(self): my_base = BaseModel() self.my_storage.new(my_base) self.my_storage.save() key = my_base.__class__.__name__ + '.' + my_base.id with open("file.json", mode='r') as f: my_dict = json.load(f) self.assertIn(key, my_dict.keys()) def test_reload(self): my_base = BaseModel() self.my_storage.new(my_base) self.my_storage.save() self.my_storage.reload() key = my_base.__class__.__name__ + '.' + my_base.id with open("file.json", mode='r') as f: my_dict = json.load(f) self.assertIn(key, my_dict.keys()) def test_pep8(self): style_test = pep8.StyleGuide(quiet=True).check_files(['models/engine/file_storage.py']) self.assertEqual(style_test.total_errors, 0, "Fix pep8 errors")
def test_instantiation(self): """ Tests for proper instantiation """ storage = FileStorage() self.assertIsInstance(storage, FileStorage)
def test_Filestorage_all(self): """Tests all method""" tmpstor = FileStorage() tmpdic = tmpstor.all() self.assertIsNotNone(tmpdic) self.assertEqual(type(tmpdic), dict)
def setUpClass(cls): '''set up before every test method''' cls.files1 = FileStorage()
def setUpClass(cls): """Set up class before start testing.""" cls.FS1 = FileStorage() cls.FS2 = FileStorage()
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)
def setUp(self): ''' Initializing classes ''' self.storage = FileStorage() self.my_model = BaseModel()
def setUp(self): """Creates FileStorage instance and sets file_path to test.json.""" self.storage = FileStorage() FileStorage._FileStorage__file_path = "test.json" FileStorage._FileStorage__objects = {} self.storage.reload()
def test_Filestorage_reload(self): """Tests reaload method """ Bob = FileStorage() sizeofobj = len(Bob._FileStorage__objects) self.assertGreater(sizeofobj, 0)
class TestFileStorage(unittest.TestCase): """Defines individual tests for FileStorage.""" def setUp(self): """Creates FileStorage instance and sets file_path to test.json.""" self.storage = FileStorage() FileStorage._FileStorage__file_path = "test.json" FileStorage._FileStorage__objects = {} self.storage.reload() def tearDown(self): """Deletes the test json file.""" if os.path.exists("test.json"): os.remove("test.json") def test_file_path_exists(self): """Tests for __file_path value.""" self.assertEqual(hasattr(FileStorage, "_FileStorage__file_path"), True) self.assertIs(type(FileStorage._FileStorage__file_path), str) def test_objects_exists(self): """Tests for __objects value.""" self.assertEqual(hasattr(FileStorage, "_FileStorage__objects"), True) self.assertIs(type(FileStorage._FileStorage__objects), dict) self.assertEqual(FileStorage._FileStorage__objects, {}) def test_all_default(self): """Tests all with default __objects.""" self.assertIs(type(self.storage.all()), dict) self.assertEqual(self.storage.all(), {}) def test_all_BaseModel_instance(self): """Tests all with one BaseModel instance.""" instance = BaseModel() self.assertIs(type(self.storage.all()), dict) self.assertEqual(self.storage.all(), {"BaseModel." + instance.id: instance}) def test_new(self): """Test new with a BaseModel instance.""" my_dict = { "__class__": "BaseModel", "id": "5e2d1d8d-92e5-4bc5-ad9a-991ef2268eb8", "updated_at": "2019-11-08T23:23:15.141214", "created_at": "2019-11-08T23:23:15.141191" } key = "BaseModel.5e2d1d8d-92e5-4bc5-ad9a-991ef2268eb8" instance = BaseModel(**my_dict) self.storage.new(instance) self.assertIn(key, self.storage.all()) self.assertIs(self.storage.all()[key], instance) def test_save(self): """Test save with a BaseModel instance.""" my_dict = { "__class__": "BaseModel", "id": "5e2d1d8d-92e5-4bc5-ad9a-991ef2268eb8", "updated_at": "2019-11-08T23:23:15.141214", "created_at": "2019-11-08T23:23:15.141191" } key = "BaseModel.5e2d1d8d-92e5-4bc5-ad9a-991ef2268eb8" expected = {key: my_dict} instance = BaseModel(**my_dict) self.storage.new(instance) self.storage.save() with open("test.json", "r") as f: json_dict = json.load(f) self.assertEqual(json_dict, expected) def test_reload(self): """Test save with a BaseModel instance.""" my_dict = { "__class__": "BaseModel", "id": "5e2d1d8d-92e5-4bc5-ad9a-991ef2268eb8", "updated_at": "2019-11-08T23:23:15.141214", "created_at": "2019-11-08T23:23:15.141191" } key = "BaseModel.5e2d1d8d-92e5-4bc5-ad9a-991ef2268eb8" instance = BaseModel(**my_dict) self.storage.new(instance) self.storage.save() self.storage.reload() self.assertEqual(len(self.storage.all().keys()), 1) self.assertIn(key, self.storage.all()) self.assertEqual(self.storage.all()[key].to_dict(), my_dict)
def save(self): """ save """ self.updated_at = datetime.now() FileStorage.save(None)
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)
class Test_console(unittest.TestCase): """Test cases for the console.py file """ clis = ['BaseModel', 'User', 'Place', 'City', 'Amenity', 'Review', 'State'] storage = FileStorage() def setUp(self): """set environment to start testing""" # Empty objects in engine FileStorage._FileStorage__objects = {} # Remove file.json if exists if os.path.exists("file.json"): os.remove("file.json") def tearDown(self): """set enviroment when testing is finished""" # Empty objects in engine FileStorage._FileStorage__objects = {} # Remove file.json if exists if os.path.exists("file.json"): os.remove("file.json") @unittest.skipIf(type_storage == 'db', "No apply for db") def test_create(self): """Test for create command """ with patch('sys.stdout', new=StringIO()) as f: command = "create State name=\"California\"" HBNBCommand().onecmd(command) _id = f.getvalue().strip() key = "State" + "." + _id self.assertTrue(key in storage.all().keys()) @unittest.skipIf(type_storage == 'db', "No apply for db") def test_create2(self): """Test for create command 2 """ with patch('sys.stdout', new=StringIO()) as f: state = State() command = "create City name=\"Texas\" state_id=\"{}\"".format( state.id) HBNBCommand().onecmd(command) _id = f.getvalue().strip() key = "City" + "." + _id nname = storage.all()[key].name sid = storage.all()[key].state_id self.assertTrue(key in storage.all().keys()) self.assertEqual('Texas', nname) self.assertEqual(state.id, sid) @unittest.skipIf(type_storage == 'db', "No apply for db") def test_create3(self): """Test for create command 2 """ with patch('sys.stdout', new=StringIO()) as f: state = State(name='Poloombia') command = "create City name=\"Tex_as\" state_id=\"{}\"".format( state.id) HBNBCommand().onecmd(command) _id = f.getvalue().strip() key = "City" + "." + _id nname = storage.all()[key].name sid = storage.all()[key].state_id self.assertTrue(key in storage.all().keys()) self.assertEqual('Tex as', nname) self.assertEqual(state.id, sid) self.assertEqual('Poloombia', state.name)
#!/usr/bin/python3 ''' Package initializer ''' from models.engine.file_storage import FileStorage from models.base_model import BaseModel from models.user import User from models.place import Place from models.state import State from models.city import City from models.amenity import Amenity from models.review import Review classes = {"User": User, "BaseModel": BaseModel, "Place": Place, "State": State, "City": City, "Amenity": Amenity, "Review": Review} storage = FileStorage() storage.reload()
def setUpClass(cls): cls.storage = FileStorage() cls.storage._FileStorage__objects = {} cls.storage._FileStorage__file_path = "atestfile.json"