def do_show(self, arg): '''Prints the string representation of an instance''' split_arg = arg.split() if len(split_arg) < 1: print("** class name missing **") return False if split_arg[0] not in CLASSES: print("** class doesn't exist **") return False if len(split_arg) == 1: print("** instance id missing **") return False storage = FileStorage() # Save the info in a new instance and deserializes the data in it storage.reload() data_storage = storage.all() # Return the dictorionary of storage and save it in new instance key = "{}.{}".format(split_arg[0], split_arg[1]) if key not in data_storage.keys(): print("** no instance found **") return False print(data_storage[key])
def test_reload(self): """Task 5. Store first object Tests public instance method `reload()`. """ fs1 = FileStorage() # TypeError: any args self.assertRaises(TypeError, fs1.reload, 'arg') # Normal use: no args, file contains string compatible with json.load() fs1.save() self.assertTrue(os.path.isfile(fs1._FileStorage__file_path)) fs1.reload() with open(fs1._FileStorage__file_path, encoding='utf-8') as file: self.assertEqual(json.load(file), fs1._FileStorage__objects) # if __file_path does not exist, do nothing, no exception raised fs2 = FileStorage() __objects_pre_reload = fs2._FileStorage__objects fs2.save() os.remove(fs2._FileStorage__file_path) fs2.reload() self.assertEqual(fs2._FileStorage__objects, __objects_pre_reload) # file exists already but doesn't contain JSON format string __file_path = fs2._FileStorage__file_path content = 'Test text 0123456789abcdefghijklmnopqrstuvwxyz' with open(__file_path, 'w+', encoding='utf-8') as file: file.write(content) print(file.read()) self.assertRaises(ValueError, fs2.reload)
def do_destroy(self, arg): '''Deletes an instance based on the class name and id''' split_arg = arg.split() if len(split_arg) == 0: print("** class name missing **") return False if len(split_arg) == 1: print("** instance id missing **") return False if split_arg[0] not in CLASSES: print("** class doesn't exist **") return False storage = FileStorage() storage.reload() data_storage = storage.all() key = "{}.{}".format(split_arg[0], split_arg[1]) if key not in data_storage.keys(): print("** no instance found **") return False # Deletes de data saved in the instanc del data_storage[key] storage.save()
def do_update(self, arg): "Holder\n" f = FileStorage() f.reload() objs = f.all() args = arg.split() if (arg == ""): print("** class name missing **") elif (not hasattr(idClasses, args[0])): print("** class doesn't exist **") elif (len(args) < 2): print("** instance id missing **") elif not (args[0] + "." + args[1] in objs): print("** no instance found **") elif (len(args) < 3): print("** attribute name missing **") elif (len(args) < 4): print("** value missing **") else: for key in objs: obj = key.split(".") if obj[0] == args[0] and obj[1] == args[1]: value = objs[key] setattr(value, args[2], args[3]) f.save()
def test_reload_method_valid(self): """Tests that the reload method correctly deserializes JSON file when file exists""" storage = FileStorage() a = BaseModel() b = BaseModel() a.save() b.save() a_id = 'BaseModel' + '.' + a.id b_id = 'BaseModel' + '.' + b.id expected_dict = {a_id: a.to_dict(), b_id: b.to_dict()} storage.save() del a, b # Check that json file exists now self.assertEqual(True, os.path.exists('file.json')) storage.reload() # Check that restored values are equivalent to the original actual_dict = storage.all() for key, value in actual_dict.items(): self.assertEqual(type(value), BaseModel) actual_dict = {k: v.to_dict() for k, v in actual_dict.items()} self.assertEqual(actual_dict, expected_dict)
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 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 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_destroy(self, arg): """Deletes an instance based on the class name and id Usage: destroy <class> """ arg_split = arg.split() if len(arg_split) == 0: print("** class name missing **") return False if len(arg_split) == 1: print("** instance id missing **") return False if arg_split[0] not in CLASS: print("** class doesn't exist **") storage = FileStorage() storage.reload() data = storage.all() key = "{}.{}".format(arg_split[0], arg_split[1]) if key not in data.keys(): print("** no instance found **") return False # Deletes data and save in JSON file del data[key] storage.save()
def test_reload_no_args(self): """ no args please """ self.resetStorage() with self.assertRaises(TypeError) as e: FileStorage.reload() msg = "reload() missing 1 required positional argument: 'self'" self.assertEqual(str(e.exception), msg)
def test_reload_such_args(self): """ such args much wow """ self.resetStorage() with self.assertRaises(TypeError) as e: FileStorage.reload(self, 98) msg = "reload() takes 1 positional argument but 2 were given" self.assertEqual(str(e.exception), msg)
def do_destroy(self, line): """ Destroy instance of BaseModel """ arg = line.split() if len(line) == 0: print("** class name missing **") elif len(arg) < 2: print("** instance id missing **") else: storage = FileStorage() storage.reload() dict1 = storage.all() key = arg[0] + "." + arg[1] obj = dict1.get(key) if obj is not None: instance = eval(arg[0]) if obj.id == arg[1] and instance == obj.__class__: del dict1[key] else: print("** no instance found **") storage.save() elif arg[0] in self.classes: print("** no instance found **") else: print("** class doesn't exist **")
def do_show(self, arg): """Display string representation of a class with id Usage: show <class> <id> """ arg_split = arg.split() if len(arg_split) < 1: print("** class name missing **") return False if arg_split[0] not in CLASS: print("** class doesn't exist **") return False if len(arg_split) == 1: print("** instance id missing **") return False # NOT FINISHED YET storage = FileStorage() storage.reload() datas = storage.all() key = "{}.{}".format(arg_split[0], arg_split[1]) if key not in datas.keys(): print("** no instance found **") return False print(datas[key])
def do_destroy(self, line): """ Deletes an instance """ try: if line: args = line.split(" ") if not isinstance(eval(args[0])(), BaseModel): raise NameError if len(args) < 2: raise ValueError obj_name, obj_id = args obj_repr = "{}.{}".format(obj_name, obj_id) data = FileStorage() data.reload() data_loaded = data.all() if obj_repr in list(data_loaded.keys()): data_loaded.pop(obj_repr) d = {} for key, value in data_loaded.items(): d[key] = value.to_dict() with open(data.path(), mode='w', encoding="utf-8") as file: file.write(json.dumps(d)) else: print("** no instance found **") else: print("** class name missing **") except ValueError: print("** instance id missing **") except NameError: print("** class doesn't exist **")
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 if os.getenv("HBNB_TYPE_STORAGE") != "db": 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 **") else: from models import storage obj_dict = storage.all(eval(args[0])) for i in obj_dict.values(): if i.id == args[1]: print(i)
def test_reload_args(self): """Test reload function with arguments""" fs = FileStorage() with self.assertRaises(TypeError): fs.reload(None) with self.assertRaises(TypeError): fs.reload(2)
class TestFileStorage(unittest.TestCase): """Class to test FileStorage""" def test_pep8_conformance_FileStorage(self): """Test that we conform to PEP8.""" pep8style = pep8.StyleGuide(quiet=True) result = pep8style.check_files(['models/engine/file_storage.py']) self.assertEqual(result.total_errors, 0) def test_docstrings(self): """Test docstrings""" self.assertIsNotNone(FileStorage.__doc__) self.assertIsNotNone(FileStorage.all.__doc__) self.assertIsNotNone(FileStorage.new.__doc__) self.assertIsNotNone(FileStorage.save.__doc__) self.assertIsNotNone(FileStorage.reload.__doc__) def setUp(self): """Set variables""" self.my_model = BaseModel() self.storaged = FileStorage() def test_file_storage_methods(self): """test if the methods exist""" self.assertTrue(hasattr(self.storaged, "all")) self.assertTrue(hasattr(self.storaged, "new")) self.assertTrue(hasattr(self.storaged, "save")) self.assertTrue(hasattr(self.storaged, "reload")) def test_all_method(self): """Test for all method """ dict_tmp = self.storaged.all() self.assertEqual(type(dict_tmp), dict) self.assertIs(dict_tmp, self.storaged._FileStorage__objects) def test_new_method(self): """Test for new method """ self.storaged.new(self.my_model) key = 'BaseModel.{}'.format(self.my_model.id) self.assertIn(key, self.storaged.all()) def test_attr(self): """Test for attributes """ self.assertTrue(isinstance(storage._FileStorage__objects, dict)) self.assertTrue(isinstance(storage._FileStorage__file_path, str)) def test_save_method(self): """Test for save method """ self.my_model.save() key = "BaseModel.{}".format(self.my_model.id) self.assertIn(key, self.storaged._FileStorage__objects.keys()) def test_reload_method(self): """Test for reload method """ self.storaged.reload() self.assertTrue(len(self.storaged._FileStorage__objects) > 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()
class testDBStorage(unittest.TestCase): ''' Testing the DBStorage class ''' def setUp(self): ''' Initializing tables and declaritive classes, and open session Set storage to FileStorage when host machine doesn't have mysql installed ''' utility.env_switcher('file') from models.base_model import BaseModel from models.engine.db_storage import DBStorage from models.engine.file_storage import FileStorage if os.getenv('HBNB_TYPE_STORAGE') == 'db': self.storage = DBStorage() else: self.storage = FileStorage() self.storage.reload() ## insert some starter data - after testing insert capability def test_empty(self): ''' Empty test to ensure there are no errors ''' self.assertEqual(True, True)
def test_reload_method_updates___objects_dict(self): """tests that reload() updates __objects with data from json file""" f = FileStorage() model = BaseModel() f.new(model) f.save() f.reload() self.assertNotEqual(f._FileStorage__objects, {})
def test_reload(self): """ testing reload """ test = FileStorage() test1 = BaseModel() test.new(test1) test.save() test2 = test.all() test.reload() self.assertEqual(test2, test.all())
def test_create_with_integer_value_arguments(self): """ Test that create an object with args """ # self.assertFalse(os.path.exists("file.json")) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create Place name="M" price_by_night=300') f = FileStorage() f.reload() for k, v in f._FileStorage__objects.items(): self.assertEqual(v.price_by_night, 300)
def test_create_with_boolean_value_arguments(self): """ Test that create an object with args """ # self.assertFalse(os.path.exists("file.json")) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create Place name="M" longitude=-122.431297') f = FileStorage() f.reload() for k, v in f._FileStorage__objects.items(): self.assertEqual(v.longitude, -122.431297)
def test_reload(self): """ Tests reload() method """ bm1 = BaseModel() fs1 = FileStorage() fs1.new(bm1) fs1.save() dict1 = fs1.reload() # check reload() output self.assertTrue(dict1 is fs1.reload())
def test_reload(self): storage = FileStorage() base = Amenity() base.name = 'test_storage' base.email = '*****@*****.**' base.save() FileStorage._FileStorage__objects = {} storage.reload() self.assertNotEqual(storage.all(), {})
def test_save_load(self): """ Tests save and reload """ if os.path.exists('save.json'): os.remove('save.json') _save = FileStorage() _save.reload() _object = self.test_class() self.assertTrue(self.test_name + '.' + _object.id in _save.all())
def test_FileStorage_new(self): """ test reload method """ st = FileStorage() st.reload() with self.assertRaises(TypeError): st.reload("reload")
def test_new(self): """testing change """ s = FileStorage() l1 = len(s.all()) new = BaseModel() s.save() s.reload() l2 = len(s.all()) self.assertEqual(l1, l2 - 1)
def test_filestorage_all_empty(self): """ tests that FileStorage all method returns an empty dict if freshly instantiated. """ f1 = FileStorage() all_before = f1.all() f1.reload() self.assertEqual(all_before, f1.all())
def test_reload_no_jsonfile(self): """ test if the json file is exist after using the reload method """ bill = FileStorage() if os.path.isfile("file.json"): os.remove("file.json") bill.reload() self.assertFalse(os.path.isfile("file.json"))
def test_create_with_one_good_arguments_with_space_in_name(self): """ Test that create an object with args """ # self.assertFalse(os.path.exists("file.json")) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create City name="Boston" state_id="0001"') f = FileStorage() f.reload() for k, v in f._FileStorage__objects.items(): self.assertEqual(v.name, "Boston")
def test_create_with_name_And_underscore_value_arguments(self): """ Test that create an object with args """ # self.assertFalse(os.path.exists("file.json")) with patch('sys.stdout', new=StringIO()) as f: HBNBCommand().onecmd('create Place name="My_little_house"') f = FileStorage() f.reload() for k, v in f._FileStorage__objects.items(): self.assertEqual(v.name, "My little house")
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_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)
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)
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)
#!/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()