Example #1
0
    def mark_as_favorite(cls, current_user, recipe_id):
        test = BaseModel.timestamp_to_db(datetime.datetime.now())

        engine.execute("INSERT INTO saved (user_id, recipe_id, saved_at) VALUES (%s,%s,%s)", (
            current_user.id,
            long(recipe_id),
            BaseModel.timestamp_to_db(datetime.datetime.now())
        ))
 def test_compare_dict(self):
     '''
         Test that the new_model's and my_model's
         dictionary values are same.
     '''
     my_model_dict = self.my_model.to_dict()
     new_model = BaseModel(**my_model_dict)
     new_model_dict = new_model.to_dict()
     self.assertEqual(my_model_dict, new_model_dict)
    def save(self):
        if not self.name:
            self.name = 'empty'

        self.emails = self.encode_field(self.emails)

        if self.details:
            self.details = self.encode_field(self.details)
        return BaseModel.save(self)
Example #4
0
    def save(self):
        if not self.registered_date and self.status == self.STATUS_REGISTERED:
            self.registered_date = date_helper.get_current_date()

        if not self.removed_date:
            if self.status == self.STATUS_REMOVED_USER or self.status == self.STATUS_REMOVED_SYS:
                self.removed_date = date_helper.get_current_date()

        if not self.url:
            self.get_url()

        if not self.code128:
            self.gen_code128()
            g.max_code128 = self.code128

        if not self.code:
            self.code = self.get_code(self.discodes_id)

        return BaseModel.save(self)
 def test_3(self):
     """str output checker"""
     tst = BaseModel()
     rslt = "[BaseModel] ({}) {}".format(tst.id, tst.__dict__)
     self.assertEqual(tst.__str__(), rslt)
Example #6
0
 def save(self):
     self.payment_id = str(self.payment_id).rjust(20, '0')
     return BaseModel.save(self)
Example #7
0
def db_seed3():
    random.seed(1)

    conn = db_connect()
    cur = conn.cursor()
    # create the main user
    user = {
        'email' : "*****@*****.**",
        'first_name': "Anthony",
        'last_name': "Bourdain",
        'hashed_password':User.hash_password("qwerty"),
        'icon_code':1,
        'created_at' : BaseModel.timestamp_to_db(datetime.now()),
        'last_login_at' : BaseModel.timestamp_to_db(datetime.now())
    }

    cur.execute("""INSERT INTO users (email, first_name, last_name, 
                                       hashed_password, icon_code, created_at, last_login_at)
                VALUES (%(email)s, %(first_name)s, %(last_name)s, %(hashed_password)s, %(icon_code)s, 
                        %(created_at)s, %(last_login_at)s)""", user)
    cur.execute("SELECT id FROM users  WHERE email=%(email)s", {'email':user['email']})
    user_id = cur.fetchone()

    
    # Create other users 
    engine.execute("""
        INSERT INTO 
            users (email, first_name, last_name, hashed_password, icon_code, created_at, last_login_at) 
        VALUES
            ('*****@*****.**', 'Abc', 'Xyz', 'GrYOEQ1BqarF4w0IbEkIGb/jRhs4x2uWAv6WhqoKo9KMY8lqEBnjeIxAoU9CkuUP', 0, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Franklin', 'Roosevelt', '36f104ac393b8431b57e78670c350359059f5bac353ef3ce620ee7c8ccf38928', 1, '2015-10-09 12:00:00', '2015-10-09 12:00:00'),
            ('*****@*****.**', 'George', 'Washington', '1bd918318467b5edf3243b90633427d2facaf630747d2d33bce137638a8719d4', 2, '2015-10-10 12:00:00', '2015-10-10 12:00:00'),
            ('*****@*****.**', 'George', 'Bush', '1bd918318467b5edf3243b90633427d2facaf630747d2d33bce137638a8719d4', 0, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Bill', 'Clinton', '237cef09c18de58503d79d9dd966c73c9736a8a9b8def484ba08f4d97bd2d3aa', 1, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Theodore', 'Roosevelt', 'a8979eec0be4e79b40e969c701e012c56dc3dbec3ba63611e597f605fe26eac8', 2, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Richard', 'Nixon', '5f872912d9b2b6f312711902991ac83fd854c746a8922e36715ff3aff18574b1', 3, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Thomas', 'Jefferson', '62660e10f69dcf92334c3bcae6330673947c2863982a9e8af92f141ad9587ce2', 0, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'John', 'Kennedy', '9c4b7a6b4af91b44be8d9bb66d41e82589f01974702d3bf1d9b4407a55593c3c', 1, '2015-10-08 12:00:00', '2015-10-08 12:00:00'),
            ('*****@*****.**', 'Harry', 'Truman', '79ff9c4d2fe456cc3015d157cf941fa51a4b2c51629d73b057629cdbb9801416', 2, '2015-10-08 12:00:00', '2015-10-08 12:00:00');
        """)
    results = engine.execute("SELECT id from users;")
    all_user_ids = [tup[0] for tup in results]

    print "CHEF ID: ", user_id
    with open('data/recipe_data.json' ,'r') as f:
        data = json.loads(f.read())

    # load all of the ingredients
    print "INSERTING ALL INGREDIENTS"
    unique_ingredients = list(set([first_lower(i['name']) for d in data for i in d['ingredients']]))
    ingredients = [{'name':i} for i in unique_ingredients]
    cur.executemany("""INSERT INTO ingredients (name) VALUES (%(name)s)""", ingredients)
    
    # load all of the categories
    print "INSERTING ALL CATEGORIES"
    unique_categories = list(set([ t['name'] for d in data for t in d['tags']]))
    categories = [{'name':i} for i in unique_categories]
    cur.executemany("""INSERT INTO categories (name) VALUES (%(name)s)""", categories)

    # for each recipe, load it, get its id, then load its steps, ingredients, and categories
    recipe_ids = []
    recipe_count = len(data)
    for j,r in enumerate(data):
        recipe = {
            'name': r['name'],
            'servings': r['yield'],
            'preparation_time': r['preparation_time'],
            'photo_file': Photo.download_photo(r['photo_url']),
            'nutritional_info': r['description'],#get_random_nutritional_info(),
            'creator_id': user_id,
            'created_at': BaseModel.timestamp_to_db(datetime.now() - timedelta(minutes=(recipe_count - j)))
        }
        cur.execute("""INSERT INTO recipes (name, servings, preparation_time, photo_file, nutritional_info, creator_id, created_at)
                       VALUES (%(name)s, %(servings)s, %(preparation_time)s, %(photo_file)s,
                               %(nutritional_info)s, %(creator_id)s, %(created_at)s)""", recipe)
        cur.execute("SELECT id FROM recipes ORDER BY id DESC LIMIT 1;")
        recipe_id = cur.fetchone()
        recipe_ids.append(recipe_id[0])
        print "RECIPE NUM: ", recipe_id[0]

        categories = [{'recipe_id':recipe_id, 'category_name':t['name']} for t in r['tags']]
        cur.executemany("""INSERT INTO categories_recipes (recipe_id, category_name)
                           VALUES (%(recipe_id)s, %(category_name)s)""", categories)
        
        steps = [ {'id':recipe_id, 'n':s['number'], 'instructions':s['instructions']} for s in r['steps'] ]
        cur.executemany("""INSERT INTO steps (recipe_id, number, instructions)
                           VALUES (%(id)s, %(n)s, %(instructions)s)""", steps)

        ingredients = [{'name':first_lower(i['name']), 'id':recipe_id, 'q':i['quantity'], 'u':i['unit'],\
                        'comment':i['comment']} for i in r['ingredients'] ]
        cur.executemany("""INSERT INTO ingredients_recipes (ingredient_name, recipe_id, quantity, unit, comment)
                           VALUES (%(name)s, %(id)s, %(q)s, %(u)s, %(comment)s)""", ingredients)

    conn.commit()
    conn.close()
    print "INSERTING RATINGS AND COMMENTS"
    for recipe_id in recipe_ids:
        # for each recipe, use a Bernoulli do define if the recipe should be rated/favorited or not
        if random.uniform(0,10) >= 2:
            # randomly select target expected rating
            target_rating = random.randint(1,5)
            offset = target_rating - 3

            # select how many users are going to rate thsi recipe
            rating_count = random.randint(3,len(all_user_ids))

            # select which users are going to rate this recipe
            rating_user_ids = random.sample(all_user_ids, rating_count)

            # for each user, randomly select and create rating
            for ruid in rating_user_ids:
                rating = random.randint(1,5) + offset
                if rating < 1:
                    rating = 1
                elif rating > 5:
                    rating = 5
                engine.execute("INSERT INTO ratings (user_id, recipe_id, rating) VALUES (%s,%s,%s)", (ruid, recipe_id, int(rating)))

                # each user that rated has 1/3 chance of favoriting the recipe
                if random.randint(1,3) == 1:
                    engine.execute("INSERT INTO saved (user_id, recipe_id, saved_at) VALUES (%s,%s,%s)", (
                        ruid,
                        recipe_id,
                        BaseModel.timestamp_to_db(datetime.now())
                    ))

            # select how many users are going to comment (max is rating count)
            comment_count = random.randint(1,rating_count)
            comments = get_comments(comment_count)

            # select which users are going to comment in this recipe
            comment_user_ids = random.sample(rating_user_ids, comment_count)

            # for each user, randomly select and create comment
            for i, cuid in enumerate(comment_user_ids):
                engine.execute("INSERT INTO comments (user_id, recipe_id, text, created_at, updated_at) VALUES (%s,%s,%s,%s,%s)", 
                    (cuid, recipe_id, comments[i], 
                        BaseModel.timestamp_to_db(datetime.now()-timedelta(minutes=(comment_count - i))), 
                        BaseModel.timestamp_to_db(datetime.now()-timedelta(minutes=(comment_count - i)))
                    ))
    



    print "DONE"
Example #8
0
 def setUp(self):
     '''
     simple set up
     '''
     self.my_model = BaseModel()
     self.storage = FileStorage()
Example #9
0
 def test_print(self):
     """Print ok"""
     model = BaseModel()
     my_model_json = model.to_dict()
     self.assertEqual(my_model_json["id"], model.id)
 def SetUp(self):
     """ Create instance """
     self.test = BaseModel()
 def test_datetime(self):
     """ check datatime """
     bas1 = BaseModel()
     self.assertFalse(datetime.now() == bas1.created_at)
Example #12
0
    def save(self):
        self.emails = self.encode_field(self.emails)

        return BaseModel.save(self)
Example #13
0
    def save(self, existing_categories, existing_ingredients):
        connection = engine.connect()
        transaction = connection.begin()
        try:
            # upload photo
            if not self.upload_file.filename:
                self.photo_file = Photo.DEFAULT_IMAGE
            else:
                self.photo_file = Photo.upload_photo(self.upload_file)

            connection.execute(
                """
                INSERT INTO recipes (name, servings, preparation_time, nutritional_info, photo_file, creator_id, created_at)
                VALUES (%s,%s,%s,%s,%s,%s,%s)""",
                (
                    self.name,
                    self.servings,
                    self.preparation_time,
                    self.nutritional_info,
                    self.photo_file,
                    self.creator_id,
                    BaseModel.timestamp_to_db(datetime.datetime.now()),
                ),
            )

            # get recipe_id
            results = connection.execute("SELECT id FROM recipes ORDER BY id DESC LIMIT 1;")
            recipe_id = None
            for result in results:
                recipe_id = result[0]

            # create categories
            for category_name in self.category_names:
                if category_name not in existing_categories:
                    connection.execute("INSERT INTO categories (name) VALUES (%s)", category_name)
                connection.execute(
                    "INSERT INTO categories_recipes (recipe_id, category_name) VALUES (%s,%s)",
                    (recipe_id, category_name),
                )

            # create ingredients
            for ingredient in self.ingredients:
                if ingredient.name not in existing_ingredients:
                    connection.execute("INSERT INTO ingredients (name) VALUES (%s)", ingredient.name)
                connection.execute(
                    """
                    INSERT INTO ingredients_recipes (ingredient_name, recipe_id, quantity, unit, comment)
                    VALUES (%s,%s,%s,%s,%s)""",
                    (ingredient.name, recipe_id, ingredient.quantity, ingredient.unit, ingredient.comment),
                )

            # create steps
            for step in self.steps:
                connection.execute(
                    """
                    INSERT INTO steps (recipe_id, number, instructions)
                    VALUES (%s,%s,%s)""",
                    (recipe_id, step.number, step.instructions),
                )

            transaction.commit()
        except Exception as e:
            transaction.rollback()
            self.error_message = e.message
            return False

        return True
 def test_2(self):
     """str check"""
     d = BaseModel()
     self.assertIsInstance(d.__str__(), str)
Example #15
0
    def save(self):
        if self.auth == self.AUTH_HID:
            self.blacklist = self.BLACKLIST_OFF

        return BaseModel.save(self)
 def test_updatenow(self):
     '''check update with saving'''
     fde = BaseModel()
     x, y = fde.save(), datetime.utcnow()
     self.assertNotEqual(fde.updated_at, y)
 def test0_1(self):
     """type id"""
     my_model = BaseModel()
     my_model.name = "Holberton"
     my_model.my_number = 89
     self.assertEqual(type(my_model.id), str)
Example #18
0
 def test_save_method(self):
     # self.assertIsInstance(self.storage._FileStorage__objects, dict)
     self.x = BaseModel()
     self.storage.save()
     self.assertTrue(os.path.exists(self.file))
     self.assertTrue(os.stat(self.file).st_size != 0)
Example #19
0
#!/usr/bin/python3
from models import storage
from models.base_model import BaseModel

all_objs = storage.all()
print("-- Reloaded objects --")
for obj_id in all_objs.keys():
    obj = all_objs[obj_id]
    print(obj)

print("-- Create a new object --")
my_model = BaseModel()
my_model.name = "Holberton"
my_model.my_number = 89
my_model.save()
print(my_model)
 def test_ids_differ(self):
     '''
         Checks that the ids between two instances are different.
     '''
     new_model = BaseModel()
     self.assertNotEqual(new_model.id, self.my_model.id)
#!/usr/bin/python3
import sys
import os
sys.path.insert(1, os.path.join(os.path.split(__file__)[0], '../'))

from models import storage
from models.base_model import BaseModel

all_objs = storage.all()
print("-- Reloaded objects --")
for obj_id in all_objs.keys():
    obj = all_objs[obj_id]
    print(obj)

print("-- Create a new object --")
my_model = BaseModel()
my_model.name = "Holberton"
my_model.my_number = 89
my_model.save()
print(my_model)
 def test_4(self):
     """dict cheker"""
     d = BaseModel()
     self.assertIsInstance(d.to_dict(), dict)
 def test5(self):
     '''check instance'''
     fde = BaseModel()
     self.assertIsInstance(fde, BaseModel)
 def test6(self):
     """ to dict name """
     fde = BaseModel()
     fde.name = "Foued"
     ok = fde.to_dict()
     self.assertEqual(ok["name"], fde.name)
class test_for_base_model(unittest.TestCase):
    """ Class test for BaseModel """
    my_model = BaseModel()

    def TearDown(self):
        """ delete json file """
        del self.test

    def SetUp(self):
        """ Create instance """
        self.test = BaseModel()

    def test_attr_none(self):
        """None attribute."""
        object_test = BaseModel(None)
        self.assertTrue(hasattr(object_test, "id"))
        self.assertTrue(hasattr(object_test, "created_at"))
        self.assertTrue(hasattr(object_test, "updated_at"))

    def test_kwargs_constructor_2(self):
        """ check id with data """
        dictonary = {'score': 100}

        object_test = BaseModel(**dictonary)
        self.assertTrue(hasattr(object_test, 'id'))
        self.assertTrue(hasattr(object_test, 'created_at'))
        self.assertTrue(hasattr(object_test, 'updated_at'))
        self.assertTrue(hasattr(object_test, 'score'))

    def test_str(self):
        """ Test string """
        dictonary = {
            'id': 'cc9909cf-a909-9b90-9999-999fd99ca9a9',
            'created_at': '2025-06-28T14:00:00.000001',
            '__class__': 'BaseModel',
            'updated_at': '2030-06-28T14:00:00.000001',
            'score': 100
        }

        object_test = BaseModel(**dictonary)
        out = "[{}] ({}) {}\n".format(
            type(object_test).__name__, object_test.id, object_test.__dict__)

    def test_to_dict(self):
        """ check dict """
        object_test = BaseModel(score=300)
        n_dict = object_test.to_dict()

        self.assertEqual(n_dict['id'], object_test.id)
        self.assertEqual(n_dict['score'], 300)
        self.assertEqual(n_dict['__class__'], 'BaseModel')
        self.assertEqual(n_dict['created_at'],
                         object_test.created_at.isoformat())
        self.assertEqual(n_dict['updated_at'],
                         object_test.updated_at.isoformat())

        self.assertEqual(type(n_dict['created_at']), str)
        self.assertEqual(type(n_dict['created_at']), str)

    def test_datetime(self):
        """ check datatime """
        bas1 = BaseModel()
        self.assertFalse(datetime.now() == bas1.created_at)

    def test_BaseModel(self):
        """ check attributes values in a BaseModel """

        self.my_model.name = "Holbie"
        self.my_model.my_number = 100
        self.my_model.save()
        my_model_json = self.my_model.to_dict()

        self.assertEqual(self.my_model.name, my_model_json['name'])
        self.assertEqual(self.my_model.my_number, my_model_json['my_number'])
        self.assertEqual('BaseModel', my_model_json['__class__'])
        self.assertEqual(self.my_model.id, my_model_json['id'])

    def test_savefirst(self):
        """check numbers"""
        with self.assertRaises(AttributeError):
            BaseModel.save([455, 323232, 2323, 2323, 23332])

    def test_savesecond(self):
        """ check string """
        with self.assertRaises(AttributeError):
            BaseModel.save("THIS IS A TEST")

    def test_inst(self):
        """check class """
        ml = BaseModel()
        self.assertTrue(ml, BaseModel)
 def test_updatetypy(self):
     """test"""
     self.assertTrue(isinstance(BaseModel().updated_at, datetime))
 def test_attr_none(self):
     """None attribute."""
     object_test = BaseModel(None)
     self.assertTrue(hasattr(object_test, "id"))
     self.assertTrue(hasattr(object_test, "created_at"))
     self.assertTrue(hasattr(object_test, "updated_at"))
class TestFileStorage(unittest.TestCase):
    """
    Unittest for file_storage.py
    """
    storage = FileStorage()
    path = storage._FileStorage__file_path
    bm_instance = BaseModel(**my_dict)
    storage.new(bm_instance)

    def test_module_docstring(self):
        """
        Tests docstring for module
        """
        self.assertTrue(len(mrdoc) > 20)

    def test_methods_docstring(self):
        """
        Tests docstring for methods
        """
        methods = inspect.getmembers(FileStorage, predicate=inspect.ismethod)
        for name, func in methods:
            self.assertTrue(len(func.__doc__) > 20)
        methods = inspect.getmembers(FileStorage, predicate=inspect.isfunction)
        for name, func in methods:
            self.assertTrue(len(func.__doc__) > 20)

    def test_pep8(self):
        """
        Tests for PEP-8
        """
        pep8style = pep8.StyleGuide(quiet=True)
        result = pep8style.check_files(["models/base_model.py"])
        self.assertEqual(result.total_errors, 0)

    def test_docstring_for_test(self):
        """
        Tests docstring for this test
        """
        self.assertTrue(len(__doc__) > 20)

    def test_docstring_class_test(self):
        """
        Tests dosctring for class TestBaseModel
        """
        self.assertTrue(len(TestFileStorage.__doc__) > 20)

    def test_docstring_methods(self):
        """
        Tests docstring for all methods in TestBaseModel class
        """
        methods = inspect.getmembers(TestFileStorage,
                                     predicate=inspect.ismethod)
        for name, func in methods:
            self.assertTrue(len(func.__doc__) > 20)

    def test_storage_isinstance(self):
        """
        Tests if storage is an instance of FileStorage
        """
        self.assertIsInstance(TestFileStorage.storage, FileStorage)

    def test_file_json(self):
        """
        Tests for path existence
        """
        TestFileStorage.storage.save()
        self.assertTrue(os.path.exists(TestFileStorage.path))

    def test_reload(self):
        """
        Test for instances reloaded from path
        """
        key = my_dict["__class__"] + "." + my_dict["id"]
        with open(TestFileStorage.path, mode="r", encoding="utf-8") as f:
            reader = json.load(f)
        attributes = reader[key]
        self.assertEqual(my_dict, attributes)
        self.assertIsInstance(TestFileStorage.storage.all()[key], BaseModel)

    def test_save_another_instance(self):
        """
        Tests for save another instance in path
        """
        bm2_instance = BaseModel()
        bm2_instance.save()
        key = type(bm2_instance).__name__ + "." + str(bm2_instance.id)
        with open(TestFileStorage.path, mode="r", encoding="utf-8") as f:
            reader = json.load(f)
        self.assertEqual(reader[key],
                         TestFileStorage.storage.all()[key].to_dict())

    def test_pep8(self):
        """Pep 8 Test
        """
        pep8style = pep8.StyleGuide(quiet=True)
        result = pep8style.check_files(["models/base_model.py"])
        self.assertEqual(result.total_errors, 0)
 def test_savefirst(self):
     """check numbers"""
     with self.assertRaises(AttributeError):
         BaseModel.save([455, 323232, 2323, 2323, 23332])
Example #30
0
 def test_do_create(self):
     """Tests creation of a new object"""
     x = self.hbnb.do_create("BaseModel")
     self.assertEqual(type(x), type(BaseModel()))
 def test_1(self):
     """  Test Dictionary """
     model = BaseModel()
     model.save()
     new_object = storage.all()
     self.assertEqual(dict, type(new_object))
Example #32
0
class TestBaseModel(unittest.TestCase):
    """
    Test the BaseModel class
    """
    def setUp(self):
        """
        Setup the test
        """
        self.b1 = BaseModel()
        self.b2 = BaseModel()
        self.b3 = BaseModel()
        self.tests = [self.b1, self.b2, self.b3]

    def test_uniq_id(self):
        """
        Test if IDs are always uniq
 ttributes.reated_at       """
        self.assertNotEqual(self.b1.id, self.b2.id)
        self.assertNotEqual(self.b1.id, self.b3.id)
        self.assertNotEqual(self.b2.id, self.b3.id)

    def test_datetime_format(self):
        """
        Test datetime format
        """
        for base in self.tests:
            self.assertIsNotNone(base.created_at.year)
            self.assertIsNotNone(base.created_at.month)
            self.assertIsNotNone(base.created_at.day)
            self.assertIsNotNone(base.created_at.hour)
            self.assertIsNotNone(base.created_at.minute)
            self.assertIsNotNone(base.created_at.second)
            self.assertIsNotNone(base.created_at.microsecond)

    def test_creation_order(self):
        """
        Test if BaseModel order creation
        """
        self.assertGreaterEqual(self.b2.created_at.microsecond,
                                self.b1.created_at.microsecond)
        self.assertLessEqual(self.b1.created_at.microsecond,
                             self.b3.created_at.microsecond)
        self.assertGreaterEqual(self.b3.created_at.microsecond,
                                self.b2.created_at.microsecond)

    def test_right_datetime(self):
        """
        Test that datetime works
        """
        dateTime = datetime.now()
        test = BaseModel()
        self.assertEqual(dateTime.year, test.created_at.year)
        self.assertEqual(dateTime.month, test.created_at.month)
        self.assertEqual(dateTime.day, test.created_at.day)
        self.assertEqual(dateTime.hour, test.created_at.hour)
        self.assertEqual(dateTime.minute, test.created_at.minute)
        self.assertEqual(dateTime.second, test.created_at.second)

    def test__str__(self):
        """
        Test str method
        """
        for base in self.tests:
            value = "[BaseModel] ({}) {}\n".format(base.id, base.__dict__)
            with patch('sys.stdout', new=StringIO()) as fake_out:
                print(base)
                self.assertEqual(fake_out.getvalue(), value)

    def test_save_method(self):
        """Test save method"""
        for base in self.tests:
            prev_t = base.updated_at.microsecond
            self.assertLessEqual(prev_t, base.updated_at.microsecond)
        for base in self.tests:
            creation = base.created_at
            self.assertEqual(creation, base.created_at)

    def test_to_dict_method(self):
        """
        Test to_dict method
        """
        for base in self.tests:
            json = base.to_dict()
            self.assertEqual(type(json["__class__"]), str)
            self.assertEqual(type(json["updated_at"]), str)
            self.assertEqual(type(json["id"]), str)
            self.assertEqual(type(json["created_at"]), str)
            c = base.created_at
            e1 = "{}-{:02d}-{:02d}T\
{:02d}:{:02d}:{:02d}.{:06d}".format(c.year, c.month, c.day, c.hour, c.minute,
                                    c.second, c.microsecond)
            c = base.updated_at
            e2 = "{}-{:02d}-{:02d}T\
{:02d}:{:02d}:{:02d}.{:06d}".format(c.year, c.month, c.day, c.hour, c.minute,
                                    c.second, c.microsecond)
            self.assertEqual(json["updated_at"], e2)
            self.assertEqual(json["created_at"], e1)

    def test_arg_errors(self):
        """
        Test number of arguments
        """
        with self.assertRaises(Exception):
            BaseModel(1, 2)
            self.b1.save(1, 2)
            self.b1.to_dict(1, 2)

    def test_kwargs(self):
        """
        Test kwargs
        """
        for base in self.tests:
            json = base.to_dict()
            copy = BaseModel(**json)
            self.assertFalse(copy is base)
            self.assertEqual(copy.id, base.id)
            self.assertEqual(copy.__dict__, base.__dict__)
            self.assertEqual(copy.__class__.__name__, base.__class__.__name__)
            copy2 = BaseModel({})
            self.assertNotEqual(copy2.__dict__, base.__dict__)
Example #33
0
 def test_print1(self):
     """Print ok"""
     model = BaseModel()
     my_model_json = model.to_dict()
     self.assertEqual(my_model_json["created_at"],
                      model.created_at.isoformat())
Example #34
0
 def test_new(self):
     """ New object is correctly added to __objects """
     new = BaseModel()
     for obj in storage.all().values():
         temp = obj
     self.assertTrue(temp is obj)
Example #35
0
 def save(self):
     if not self.min_item:
         self.min_item = self.DEFAULT_MIN_ITEM
     if not self.max_item:
         self.max_item = self.DEFAULT_MAX_ITEM
     return BaseModel.save(self)
Example #36
0
 def test_all(self):
     """ __objects is properly returned """
     new = BaseModel()
     temp = storage.all()
     self.assertIsInstance(temp, dict)
 def save(self):
     self.timestamp = date_helper.get_current_utc()
     return BaseModel.save(self)
Example #38
0
 def test_base_model_instantiation(self):
     """ File is not created on BaseModel save """
     new = BaseModel()
     self.assertFalse(os.path.exists('file.json'))
Example #39
0
class TestBase(unittest.TestCase):
    '''
        Testing the base class model.
    '''

    def setUp(self):
        '''
            Initializing instance.
        '''
        self.my_model = BaseModel()
        self.my_model.name = "Binita Rai"

    def TearDown(self):
        '''
            Removing instance.
        '''
        del self.my_model

    def test_id_type(self):
        '''
            Checks that the type of the id is string.
        '''
        self.assertEqual("<class 'str'>", str(type(self.my_model.id)))

    def test_ids_differ(self):
        '''
            Checks that the ids between two instances are different.
        '''
        new_model = BaseModel()
        self.assertNotEqual(new_model.id, self.my_model.id)

    def test_name(self):
        '''
            Checks that an attribute can be added.
        '''
        self.assertEqual("Binita Rai", self.my_model.name)

    def test_a_updated_created_equal(self):
        '''
            Checks that both dates are equal.
        '''
        self.assertEqual(self.my_model.updated_at.year,
                         self.my_model.created_at.year)

    def test_save(self):
        '''
            Checks that after updating the instance; the dates differ in the
            updated_at attribute.
        '''
        old_update = self.my_model.updated_at
        self.my_model.save()
        self.assertNotEqual(self.my_model.updated_at, old_update)

    def test_str_overide(self):
        '''
            Checks that the right message gets printed.
        '''
        backup = sys.stdout
        inst_id = self.my_model.id
        capture_out = StringIO()
        sys.stdout = capture_out
        print(self.my_model)

        cap = capture_out.getvalue().split(" ")
        self.assertEqual(cap[0], "[BaseModel]")

        self.assertEqual(cap[1], "({})".format(inst_id))
        sys.stdout = backup

    def test_to_dict_type(self):
        '''
            Checks that the to_dict method return type.
        '''

        self.assertEqual("<class 'dict'>",
                         str(type(self.my_model.to_dict())))

    def test_to_dict_class(self):
        '''
            Checks that the __class__ key exists.
        '''

        self.assertEqual("BaseModel", (self.my_model.to_dict())["__class__"])

    def test_to_dict_type_updated_at(self):
        '''
            Checks the type of the value of updated_at.
        '''
        self.assertEqual("<class 'str'>",
                         str(type((self.my_model.to_dict())["updated_at"])))

    def test_to_dict_type_created_at(self):
        '''
            Checks the type of the value of created_at.
        '''
        tmp = self.my_model.to_dict()
        self.assertEqual("<class 'str'>", str(type(tmp["created_at"])))

    def test_kwargs_instantiation(self):
        '''
            Test that an instance is created using the
            key value pair.
        '''
        my_model_dict = self.my_model.to_dict()
        new_model = BaseModel(**my_model_dict)
        self.assertEqual(new_model.id, self.my_model.id)

    def test_type_created_at(self):
        '''
            Test that the new_model's updated_at
            data type is datetime.
        '''
        my_model_dict = self.my_model.to_dict()
        new_model = BaseModel(my_model_dict)
        self.assertTrue(isinstance(new_model.created_at, datetime.datetime))

    def test_type_updated_at(self):
        '''
            Test that the new_model's created_at
            data type is datetime.
        '''
        my_model_dict = self.my_model.to_dict()
        new_model = BaseModel(my_model_dict)
        self.assertTrue(isinstance(new_model.updated_at, datetime.datetime))

    def test_compare_dict(self):
        '''
            Test that the new_model's and my_model's
            dictionary values are same.
        '''
        my_model_dict = self.my_model.to_dict()
        new_model = BaseModel(**my_model_dict)
        new_model_dict = new_model.to_dict()
        self.assertEqual(my_model_dict, new_model_dict)

    def test_instance_diff(self):
        '''
            Test that the my_model and new_model are
            not the same instance.
        '''
        my_model_dict = self.my_model.to_dict()
        new_model = BaseModel(my_model_dict)
        self.assertNotEqual(self.my_model, new_model)
Example #40
0
 def test_save(self):
     """ FileStorage save method """
     new = BaseModel()
     storage.save()
     self.assertTrue(os.path.exists('file.json'))
Example #41
0
 def setUp(self):
     '''
         Initializing instance.
     '''
     self.my_model = BaseModel()
     self.my_model.name = "Binita Rai"
Example #42
0
 def test_base_model_save(self):
     """ BaseModel save method calls storage save """
     new = BaseModel()
     new.save()
     self.assertTrue(os.path.exists('file.json'))
Example #43
0
    def create_comment(cls, user, recipe_id, text):
        user_id = long(user.id)
        recipe_id = long(recipe_id)
        created_at = datetime.datetime.now()
        updated_at = created_at

        engine.execute("INSERT INTO comments (user_id, recipe_id, text, created_at, updated_at) VALUES (%s,%s,%s,%s,%s)", (user_id, recipe_id, text, BaseModel.timestamp_to_db(created_at), BaseModel.timestamp_to_db(updated_at)))
 def test_savesecond(self):
     """ check string """
     with self.assertRaises(AttributeError):
         BaseModel.save("THIS IS A TEST")
Example #45
0
 def save(self):
     self.status = self.get_status()
     return BaseModel.save(self)
 def test_inst(self):
     """check class """
     ml = BaseModel()
     self.assertTrue(ml, BaseModel)
Example #47
0
 def save(self):
     self.activkey = hash_helper.get_activkey(self.password)
     return BaseModel.save(self)
Example #48
0
 def __init__(self, data_layer):
     BaseModel.__init__(self, 'archive', data_layer, {}, ItemValidator())