示例#1
0
    def test_40_load(self):
        """UserDatabase: load()"""
        self.create_record_table()

        udb = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name, self.key_file)
        current_stamp = datetime.datetime.now()
        udb.name = "monty_db"
        udb.db_user = "******"
        udb.db_address = "127.0.0.1"
        udb.db_password = "******"
        udb.created = current_stamp
        udb.last_login = current_stamp
        udb.enabled = True
        udb.uid = 1
        self.assertTrue(udb._dirty, "Dirty bit not active but data changed")
        udb.save()

        udb2 = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name, self.key_file)
        udb2.load(udb.id)

        self.assertEqual(udb.id, udb2.id, "IDs on original and loaded object don't match")
        self.assertFalse(udb2._dirty, "The dirty bit is wrong after load.")
        self.assertEqual(udb2, udb, "The two copies of the record should consider themselves equal.")
        self.assertEqual(udb2.name, udb.name, "name in the table should match the name on the record.")
        self.assertEqual(udb2.uid, udb.uid, "uid in the table should match the uid on the record.")
        self.assertEqual(udb2.db_password, udb.db_password, "password in the table should match the one on the record.")        
        self.assertEqual(udb2.db_user, udb.db_user, "db_user in the table should match the one on the record.")        
        self.assertAlmostEqual(udb2.created, udb.created, delta=datetime.timedelta(seconds=1), msg="created in the table should match the one on the record.")        
        self.assertAlmostEqual(udb2.last_login, udb.last_login,  delta=datetime.timedelta(seconds=1), msg="last_login in the table should match the one on the record.")        
        self.assertEqual(udb2.enabled, udb.enabled, "enabled in the table should match the one on the record.")        
        self.assertEqual(udb2.db_address, udb.db_address, "db_address in the table should match the one on the record.")        
示例#2
0
    def test_50_delete(self):
        """UserDatabase: delete()"""
        self.create_record_table()

        udb = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name, self.key_file)
        current_stamp = datetime.datetime.now()
        udb.name = "monty_db"
        udb.db_user = "******"
        udb.db_address = "127.0.0.1"
        udb.db_password = "******"
        udb.created = current_stamp
        udb.last_login = current_stamp
        udb.enabled = True
        udb.uid = 1
        self.assertTrue(udb._dirty, "Dirty bit not active but data changed")
        udb.save()

        udb.delete()

        # Now let's go see if it's really there
        select = ("SELECT * FROM `{0}`".format(user_db.HistoriaUserDatabase.machine_type),{})
        result = self.db.execute_select(select)

        self.assertEqual(len(result), 0, "There should nothing in the table now.")
        self.assertEqual(-1, udb.id, "The ID should reset to -1")
示例#3
0
    def test_15_internals(self):
        """UserDatabase: __setattr__"""

        udb = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name, self.key_file)

        with self.assertRaises(AttributeError):
            udb.bogus_field = "Junk Data"

        attrs = ['name', 'db_user', 'db_address', 'created', 'last_record_update', 'last_login']

        # All of the listed fields on a User should raise a ValueError when they are fed an integer
        for attr in attrs:
            with self.assertRaises(ValueError):
                setattr(udb, attr, 123243)


        udb._anything = "ok"
        self.assertEqual(udb._anything, "ok", "Assignment of _ variables works fine...except that they fail all the time")

        current_stamp = datetime.datetime.now()
        udb.name = "monty_db"
        udb.db_user = "******"
        udb.db_password = "******"
        udb.db_address = "127.0.0.1"
        udb.created = current_stamp
        udb.last_login = current_stamp
        udb.enabled = True
        self.assertEqual(-1, udb.id, "ID is still -1")
        self.assertEqual(udb.name, "monty_db", "Assignment of setting name failed.")
        self.assertEqual(udb.db_password, "Plain text password", "Assignment of password failed")
        self.assertEqual(udb.db_address, "127.0.0.1", "Assignment of setting address failed.")
        self.assertEqual(udb.created, current_stamp, "Assignment of setting created timestamp failed.")
        self.assertEqual(udb.last_login, current_stamp, "Assignment of setting access timestamp failed.")
        self.assertEqual(udb.enabled, True, "Assignment of setting enabled failed.")
        self.assertEqual(udb.db_user, 'monty', "Assignment of setting user failed.")
示例#4
0
 def test_20_generate_DB_SQL(self):
     """UserDatabase: generate database SQL statements"""
     
     udb = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name, self.key_file)
     
     statements = udb.generate_database_SQL()
     
     self.assertEqual(len(statements), (len(udb.member_classes)*2)+2, "There should be 2 statements for each class + 2 for the database itself")
     
     self.assertIn(self.test_user_db_name, statements[0][0], "DB name not in db create statement")
     self.assertIn(self.test_user_db_name, statements[1][0], "DB name not in db use statement")
示例#5
0
 def test_10_construct(self):
     """UserDatabase: __init__()"""
     
     db = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name, self.key_file)
     
     self.assertIsInstance(db._logger, logging.Logger, "Default logger isn't a logger")
     self.assertEqual(db.name, self.test_user_db_name.lower(), "Name passed to object didn't make it")
     self.assertEqual(db._id, -1, "ID should be -1 for user databases")
     self.assertEqual(len(db.connection_settings), 5, "Incorrect number of DB settings")
     self.assertEqual(db.database_defaults['charset'], 'utf8', 'User database should always use UTF-8')
     self.assertIsNone(db.connection, "Where did the database get a connection object already")
示例#6
0
 def test_60_connect(self):
     """UserDatabase: Connect to db"""
     
     udb = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name, self.key_file)
     udb.db_user = self.config['database']['user']
     udb.db_password = self.config['database']['password']
     udb.db_address =  self.config['database']['host']
     udb.name = self.test_master_db_name #Normally this would be wrong, but it's needed for testing.
     
     udb.connect()
     
     self.assertTrue(udb.connected, "User database unable to connect when setting connection values.")
示例#7
0
    def test_30_save(self):
        """UserDatabase: save()"""
        udb = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name, self.key_file)

        self.assertRaises(exceptions.DataSaveError, udb.save)
        
        # Create the required table and try again
        self.create_record_table()
        
        current_stamp = datetime.datetime.now()
        udb.name = "monty_db"
        udb.db_user = "******"
        udb.db_address = "127.0.0.1"
        udb.db_password = "******"
        udb.created = current_stamp
        udb.last_login = current_stamp
        udb.enabled = True
        self.assertTrue(udb._dirty, "Dirty bit not active but data changed")
        
        self.assertRaises(exceptions.DataSaveError, udb.save) # still can't save because we're lacking a UID
        udb.uid = 1
        
        udb.save()
        
        self.assertFalse(udb._dirty, "Dirty bit active after save")
        self.assertNotEqual(udb.id, -1, "Record ID still -1 after save.")

        # Now let's go see if it's really there
        select = ("SELECT * FROM `{0}`".format(user_db.HistoriaUserDatabase.machine_type),{})
        result = self.db.execute_select(select)

        self.assertEqual(len(result), 1, "There should be 1 and only 1 entry in the table.")
        self.assertEqual(result[0]['name'], udb.name, "name in the table should match the name on the record.")
        self.assertNotEqual(result[0]['db_password'], udb.db_password, "password in the table should not match the one on the record.")        
        self.assertEqual(result[0]['db_user'], udb.db_user, "db_user in the table should match the one on the record.")
        self.assertAlmostEqual(result[0]['created'], udb.created, delta=datetime.timedelta(seconds=1), msg="created in the table should match the one on the record.")        
        self.assertAlmostEqual(result[0]['last_login'], udb.last_login,  delta=datetime.timedelta(seconds=1), msg="last_login in the table should match the one on the record.")        
        self.assertEqual(result[0]['enabled'], udb.enabled, "enabled in the table should match the one on the record.")        
        self.assertEqual(result[0]['db_address'], udb.db_address, "db_address in the table should match the one on the record.")
示例#8
0
    def create_database(self,
                        database_name,
                        connection_settings,
                        db_type="user"):
        """Create a new database with database_name. The optional parameter
        allows the caller to pick the type of database to be created.  Valid
        types are: system or user."""

        if db_type == 'system':
            db = system_db.HistoriaSystemDatabase(database_name)
            db.connection_settings = connection_settings
            db.createDatabase(db)
            return db
        elif db_type == 'user':
            # Check to see if there is a database record on file for that name.
            db = user_db.HistoriaUserDatabase(
                self.database, database_name,
                self.config['server']['aes_key_file'])
            db.connection_settings = connection_settings
            self.database.createDatabase(db)
            return db
        else:
            raise ValueError("Databases much be of type 'system' or 'user'")
示例#9
0
    def test_40_createUserDatabase(self):
        """SystemDatabase: Create a new user database"""
        self.db = system_db.HistoriaSystemDatabase(self.test_master_db_name)
        self.db.connection_settings = self.default_settings
        self.db.createDatabase(self.db)

        # db should now exist and be connected to itself....let's find out.
        self.assertTrue(self.db.connected,
                        "DB not connected after creating itself")

        # Create a user database
        udb = user_db.HistoriaUserDatabase(self.db, self.test_user_db_name,
                                           self.key_file)

        self.db.createDatabase(udb)

        self.assertTrue(udb.connected,
                        "User database not connected after creation")
        self.assertEqual(udb.db_user, udb.name[:16],
                         "User name for MySQL user not generated correctly.")
        cur = self.db.cursor()

        # Check for database
        sql = "SHOW DATABASES;"
        cur.execute(sql)
        result = [tbl['Database'] for tbl in cur.fetchall()]
        self.assertIn(udb.name, result,
                      "User database doesn't appear to exist")

        # Check db user
        sql = "USE mysql"
        cur.execute(sql)
        sql = """SELECT `user`.`User` AS UserName, `db`.* 
                    FROM `user` LEFT JOIN `db` ON `user`.`User` = `db`.`User` 
                    WHERE `user`.`User` =  %(user)s AND `user`.`Password` = PASSWORD(%(password)s)"""
        cur.execute(sql, {'user': udb.db_user, 'password': udb.db_password})
        result = cur.fetchall()
        self.assertEqual(
            len(result), 1,
            "There should be one and one 1 reference for this user in MySQL")
        result = result[0]
        self.assertEqual(result['UserName'].decode(), udb.db_user,
                         "Wrong user name set on new user (huh?)")
        self.assertEqual(result['User'].decode(), udb.db_user,
                         "Wrong user name set on new user in db table (huh?)")
        self.assertEqual(result['Host'].decode(), self.db.local_address,
                         "Wrong host set on new user")
        self.assertEqual(result['Db'].decode(), udb.name,
                         "Wrong database used for new user's access (Crap)")
        yes_privs = [
            'Select_priv', 'Insert_priv', 'Update_priv', 'Delete_priv',
            'Create_priv', 'Drop_priv', 'References_priv', 'Index_priv',
            'Alter_priv', 'Create_tmp_table_priv', 'Lock_tables_priv',
            'Create_view_priv', 'Show_view_priv', 'Create_routine_priv',
            'Alter_routine_priv', 'Execute_priv', 'Event_priv', 'Trigger_priv'
        ]
        no_privs = ['Grant_priv']

        for priv in yes_privs:
            self.assertEqual(result[priv], 'Y',
                             "User was not given: {0}".format(priv))
        for priv in no_privs:
            self.assertEqual(result[priv], 'N',
                             "User was given: {0}".format(priv))

        # Check that udb is connected
        udb_cur = udb.cursor()
        sql = "SELECT DATABASE();"
        udb_cur.execute(sql)
        result = udb_cur.fetchall()
        self.assertEqual(udb.name, result[0]['DATABASE()'],
                         "Database in use is not me")

        # Check structure
        sql = "SHOW TABLES;"
        udb_cur.execute(sql)
        result = udb_cur.fetchall()
        col = "Tables_in_{0}".format(udb.name)
        class_names = [n.machine_type for n in udb.member_classes]
        self.assertEqual(len(result), len(udb.member_classes),
                         "Wrong number of tables in database")
        for tbl in result:
            self.assertIn(tbl[col], class_names,
                          "Table {0} not in my table list.".format(tbl[col]))