コード例 #1
0
 def setUp(self):
     self.destroyDb()
     self.settings = pokernetworkconfig.Config([])
     self.settings.doc = libxml2.parseMemory(settings_xml,
                                             len(settings_xml))
     self.settings.header = self.settings.doc.xpathNewContext()
     self.db = PokerDatabase(self.settings)
コード例 #2
0
 def setUpServer(self):
     settings = pokernetworkconfig.Config([])
     settings.loadFromString(settings_xml_server)
     #
     # Setup database
     #
     self.db = PokerDatabase(settings)
     #
     # Setup server
     #
     self.service = pokerservice.PokerService(settings)
     self.service.verbose = 6
コード例 #3
0
 def setUpServer(self):
     settings = pokernetworkconfig.Config([])
     settings.doc = libxml2.parseMemory(settings_xml_server,
                                        len(settings_xml_server))
     settings.header = settings.doc.xpathNewContext()
     #
     # Setup database
     #
     self.db = PokerDatabase(settings)
     #
     # Setup server
     #
     self.service = pokerservice.PokerService(settings)
     self.service.verbose = 6
コード例 #4
0
ファイル: pokersql.py プロジェクト: Usr-X/poker-network
def runQuery(settings):
    if not settings.headerGet('/server/database/@name'):
            return "Content-type: text/plain\n\n"
    db = PokerDatabase(settings)
    cgitb.enable()
    form = cgi.FieldStorage()
    cursor = db.cursor(DictCursor)
    cursor.execute(form["query"].value)
    if 'output' not in form:
            result = cursor.rowcount
    elif form["output"].value == "rows":
            result = cursor.fetchall()
    elif form["output"].value == "lastrowid":
            result = cursor.lastrowid
    else:
            result = cursor.rowcount
    cursor.close()
    return "Content-type: text/plain\n\n" + json.dumps(result)
コード例 #5
0
def runQuery(settings):
    if not settings.headerGet('/server/database/@name'):
        return "Content-type: text/plain\n\n"
    db = PokerDatabase(settings)
    cgitb.enable()
    form = cgi.FieldStorage()
    cursor = db.cursor(DictCursor)
    cursor.execute(form["query"].value)
    if 'output' not in form:
        result = cursor.rowcount
    elif form["output"].value == "rows":
        result = cursor.fetchall()
    elif form["output"].value == "lastrowid":
        result = cursor.lastrowid
    else:
        result = cursor.rowcount
    cursor.close()
    return "Content-type: text/plain\n\n" + json.dumps(result)
コード例 #6
0
 def setUpServer(self):
     settings = pokernetworkconfig.Config([])
     settings.loadFromString(settings_xml_server)
     #
     # Setup database
     #
     self.db = PokerDatabase(settings)
     #
     # Setup server
     #
     self.service = pokerservice.PokerService(settings)
     self.service.verbose = 6
コード例 #7
0
 def setUpServer(self):
     settings = pokernetworkconfig.Config([])
     settings.doc = libxml2.parseMemory(settings_xml_server, len(settings_xml_server))
     settings.header = settings.doc.xpathNewContext()
     #
     # Setup database
     #
     self.db = PokerDatabase(settings)
     #
     # Setup server
     #
     self.service = pokerservice.PokerService(settings)
     self.service.verbose = 6
コード例 #8
0
class PokerCrashTestCase(unittest.TestCase):

    def destroyDb(self, arg = None):
        os.system("/usr/bin/mysql -u root -e 'DROP DATABASE IF EXISTS pokernetworktest'")

    def setUpServer(self):
        settings = pokernetworkconfig.Config([])
        settings.doc = libxml2.parseMemory(settings_xml_server, len(settings_xml_server))
        settings.header = settings.doc.xpathNewContext()
        #
        # Setup database
        #
        self.db = PokerDatabase(settings)
        #
        # Setup server
        #
        self.service = pokerservice.PokerService(settings)
        self.service.verbose = 6

    # -------------------------------------------------
    def setUp(self):
        self.destroyDb()
        self.setUpServer()

    def tearDown(self):
        self.db.close()
        return self.service.stopService()

    def test01_cleanupCrashedTables(self):
        cursor = self.db.cursor()
        #
        # Although the name is not in the configuration file (settings),
        # it has a matching resthost_serial and is cleanedup
        #
        cursor.execute('INSERT INTO pokertables (serial, name, variant, betting_structure, currency_serial) VALUES (142, "one", "holdem", "2-4", 1)')
        cursor.execute('INSERT INTO user2table (user_serial, table_serial, money, bet) VALUES (1000, 142, 10, 1)')
        cursor.execute("INSERT INTO users (serial, created, name) VALUES (1000, 0, 'testuser')")
        cursor.execute("INSERT INTO user2money (user_serial, currency_serial, amount) VALUES (1000, 1, 0)")
        #
        # resthost_serial does not match, the records are left untouched
        #
        cursor.execute('INSERT INTO pokertables (serial, name, variant, betting_structure, currency_serial, resthost_serial) VALUES (202, "two", "holdem", "2-4", 1, 10)')
        cursor.execute('INSERT INTO user2table (user_serial, table_serial, money, bet) VALUES (1000, 202, 10, 1)')
        #
        # Table1 is in the configuration file and cleaned up even though
        # resthost_serial does not match
        #
        cursor.execute('INSERT INTO pokertables (serial, name, variant, betting_structure, currency_serial, resthost_serial) VALUES (303, "Table1", "holdem", "2-4", 1, 44)')
        self.service.startService()
        cursor.execute("SELECT user_serial,table_serial FROM user2table")
        self.assertEqual(1, cursor.rowcount)
        self.assertEqual((1000, 202), cursor.fetchone())
        cursor.execute("SELECT serial FROM pokertables")
        self.assertEqual((202,), cursor.fetchone())
        cursor.execute("SELECT amount FROM user2money")
        self.assertEqual(11, cursor.fetchone()[0])
        cursor.close()

    def test02_cleanupTourneys_refund(self):
        tourney_serial = '10'
        user_serial = '200'
        buy_in = '300'
        currency_serial = '44'
        cursor = self.db.cursor()
        cursor.execute('INSERT INTO tourneys (serial,name,buy_in,currency_serial) VALUES (%s, "one", %s, %s)', ( tourney_serial, buy_in, currency_serial ))
        cursor.execute('INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)', ( user_serial, tourney_serial ))
        cursor.execute('INSERT INTO user2money (user_serial,currency_serial) VALUES (%s,%s)', ( user_serial, currency_serial ))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' + tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT amount FROM user2money WHERE user_serial = %s AND currency_serial = %s', ( user_serial, currency_serial ))
        self.assertEqual((0,), cursor.fetchone())
        self.service.startService()
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' + tourney_serial)
        self.assertEqual(0, cursor.rowcount)
        cursor.execute('SELECT amount FROM user2money WHERE user_serial = %s AND currency_serial = %s', ( user_serial, currency_serial ))
        self.assertEqual((300,), cursor.fetchone())
        cursor.close()

    def test02_cleanupTourneys_restore(self):
        regular_tourney_serial = '10'
        sng_tourney_serial = '40'
        user_serial = '200'
        cursor = self.db.cursor()
        cursor.execute("DELETE FROM tourneys_schedule")
        #
        # Sit and go in 'registering' state is trashed
        #
        cursor.execute('INSERT INTO tourneys (serial,name) VALUES (%s, "one")', sng_tourney_serial)
        cursor.execute('INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)', ( user_serial, sng_tourney_serial ))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' + sng_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        #
        # Regular in 'registering' state is kept
        #
        cursor.execute('INSERT INTO tourneys (serial,name,sit_n_go,start_time) VALUES (%s, "one", "n", %s)', ( regular_tourney_serial, seconds() + 2000))
        cursor.execute('INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)', ( user_serial, regular_tourney_serial ))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' + regular_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        #
        # Run cleanupTourneys as a side effect
        #
        self.service.startService()
        #
        # Sanity checks
        #
        self.assertEqual([int(regular_tourney_serial)], self.service.tourneys.keys())
        cursor.execute('SELECT * FROM user2tourney WHERE tourney_serial = %s', regular_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT * FROM user2tourney WHERE tourney_serial = %s', sng_tourney_serial)
        self.assertEqual(0, cursor.rowcount)
        cursor.execute('SELECT * FROM user2tourney')
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT * FROM tourneys')
        self.assertEqual(1, cursor.rowcount)
        cursor.close()
コード例 #9
0
class PokerAuthTestCase(unittest.TestCase):

    # -----------------------------------------------------------------------------------------------------
    def destroyDb(self):
        if len("") > 0:
            os.system(
                "/usr/bin/mysql -u root --password='' -h 'localhost' -e 'DROP DATABASE IF EXISTS pokernetworktest'"
            )
        else:
            os.system(
                "/usr/bin/mysql -u root -h 'localhost' -e 'DROP DATABASE IF EXISTS pokernetworktest'"
            )

    # --------------------------------------------------------
    def setUp(self):
        self.destroyDb()
        self.settings = pokernetworkconfig.Config([])
        self.settings.doc = libxml2.parseMemory(settings_xml,
                                                len(settings_xml))
        self.settings.header = self.settings.doc.xpathNewContext()
        self.db = PokerDatabase(self.settings)

    # -----------------------------------------------------------------------------------------------------
    def tearDown(self):
        pokerauth._get_auth_instance = None

    # -----------------------------------------------------------------------------------------------------
    def test01_Init(self):
        """test01_Init
        Test Poker auth : get_auth_instance"""
        db = None
        settings = pokernetworkconfig.Config([])
        settings.doc = libxml2.parseMemory(settings_xml, len(settings_xml))
        settings.header = settings.doc.xpathNewContext()
        auth = pokerauth.get_auth_instance(db, settings)

    # -----------------------------------------------------------------------------------------------------
    def test02_AlternatePokerAuth(self):
        """test02_AlternatePokerAuth
        Test Poker auth : get_auth_instance alternate PokerAuth"""
        db = None
        settings = pokernetworkconfig.Config([])
        settings.doc = libxml2.parseMemory(settings_alternate_xml,
                                           len(settings_alternate_xml))
        settings.header = settings.doc.xpathNewContext()
        auth = pokerauth.get_auth_instance(db, settings)
        self.failUnless(hasattr(auth, 'gotcha'))

    # -----------------------------------------------------------------------------------------------------
    def checkIfUserExistsInDB(
            self,
            name,
            selectString="SELECT serial from users where name = '%s'"):
        cursor = self.db.cursor()
        cursor.execute(selectString % name)
        if cursor.rowcount == 1:
            (serial, ) = cursor.fetchone()
            cursor.close()
            return [serial]
        elif cursor.rowcount == 0:
            cursor.close()
            return []
        else:
            serials = []
            for row in cursor.fetchall():
                serials.append(row['serial'])
            cursor.close()
            return serials

    # -----------------------------------------------------------------------------------------------------
    def test03_authWithAutoCreate(self):
        """test03_authWithAutoCreate
        Test Poker auth : Try basic auth with autocreate on"""
        db = self.db
        settings = pokernetworkconfig.Config([])
        autocreate_xml = settings_xml.replace(
            '<server auto_create_account="no" ', '<server ')
        settings.doc = libxml2.parseMemory(autocreate_xml, len(autocreate_xml))
        settings.header = settings.doc.xpathNewContext()
        auth = pokerauth.get_auth_instance(db, settings)

        clear_all_messages()
        self.assertEquals(auth.auth('joe_schmoe', 'foo'),
                          ((4, 'joe_schmoe', 1), None))
        self.assertEquals(get_messages(), [
            'user joe_schmoe does not exist, create it',
            'creating user joe_schmoe', 'create user with serial 4'
        ])
        self.failUnless(len(self.checkIfUserExistsInDB('joe_schmoe')) == 1)

    # -----------------------------------------------------------------------------------------------------
    def test04_authWithoutAutoCreate(
            self, expectedMessage='user john_smith does not exist'):
        """test04_authWithoutAutoCreate
        Test Poker auth : Try basic auth with autocreate on"""
        auth = pokerauth.get_auth_instance(self.db, self.settings)

        clear_all_messages()

        self.assertEquals(auth.auth('john_smith', 'blah'),
                          (False, 'Invalid login or password'))
        if expectedMessage:
            self.assertTrue(search_output(expectedMessage))
        self.failUnless(len(self.checkIfUserExistsInDB('john_smith')) == 0)

    # -----------------------------------------------------------------------------------------------------
    def test05_authWhenDoubleEntry(self):
        """test05_authWhenDoubleEntry
        Tests case in fallback authentication where more than one entry exists.
        """
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE users")
        cursor.execute("""CREATE TABLE users (
 	    serial int unsigned not null auto_increment,
	    name varchar(32), password varchar(32), privilege int default 1,
            primary key (serial))""")
        for ii in [1, 2]:
            cursor.execute(
                "INSERT INTO users (name, password) values ('%s', '%s')" %
                ('doyle_brunson', 'foo'))
        cursor.close()

        auth = pokerauth.get_auth_instance(self.db, self.settings)

        clear_all_messages()
        self.assertEquals(auth.auth('doyle_brunson', 'foo'),
                          (False, "Invalid login or password"))
        self.assertEquals(get_messages(),
                          ['*ERROR* more than one row for doyle_brunson'])

    # -----------------------------------------------------------------------------------------------------
    def test06_validAuthWhenEntryExists(self):
        """test06_validAuthWhenEntryExists
        Tests case for single-row returned existing auth, both success and failure.
        """
        cursor = self.db.cursor()
        cursor.execute(
            "INSERT INTO users (created, name, password) values (%d, '%s', '%s')"
            % (seconds(), 'dan_harrington', 'bar'))
        cursor.close()

        auth = pokerauth.get_auth_instance(self.db, self.settings)

        clear_all_messages()
        self.assertEquals(auth.auth('dan_harrington', 'bar'),
                          ((4L, 'dan_harrington', 1L), None))
        self.assertEquals(get_messages(), [])

        clear_all_messages()
        self.assertEquals(auth.auth('dan_harrington', 'wrongpass'),
                          (False, 'Invalid login or password'))
        self.assertEquals(get_messages(),
                          ['password mismatch for dan_harrington'])

    # -----------------------------------------------------------------------------------------------------
    def test07_mysql11userCreate(self):
        """test07_mysql11userCreate
        Tests userCreate() as it will behave under MySQL 1.1 by mocking up
        the situation.
        """
        class MockCursor:
            def execute(self, str):
                pass

            def insert_id(self):
                return 4815

            def close(self):
                pass

        class MockDatabase:
            def cursor(self):
                return MockCursor()

        clear_all_messages()
        auth = pokerauth.get_auth_instance(MockDatabase(), self.settings)
        self.assertEquals(auth.userCreate("nobody", "nothing"), 4815)
        self.assertTrue(search_output('creating user nobody'))
        self.assertTrue(search_output('create user with serial 4815'))

    # -----------------------------------------------------------------------------------------------------
    def test08_mysqlbeyond11userCreate(self):
        """test08_mysqlbeyond11userCreate
        Tests userCreate() as it will behave under MySQL > 1.1 by mocking up
        the situation.
        """
        class MockCursor:
            def __init__(self):
                self.lastrowid = 162342

            def execute(self, str):
                pass

            def insert_id(self):
                self.failIf(1)

            def close(self):
                pass

        class MockDatabase:
            def cursor(self):
                return MockCursor()

        clear_all_messages()
        auth = pokerauth.get_auth_instance(MockDatabase(), self.settings)
        self.assertEquals(auth.userCreate("somebody", "something"), 162342)
        self.assertTrue(search_output('creating user somebody'))
        self.assertTrue(search_output('create user with serial 162342'))

    # -----------------------------------------------------------------------------------------------------
    def test09_setAndGetLevel(self):
        """test09_setAndGetLevel
        Tests the SetLevel and GetLevel methods.
        """
        auth = pokerauth.get_auth_instance(self.db, self.settings)

        self.assertEquals(auth.GetLevel('first'), False)
        self.assertEquals(auth.SetLevel('first', 7), None)
        self.assertEquals(auth.GetLevel('first'), 7)
        self.assertEquals(auth.GetLevel('second'), False)
コード例 #10
0
class PokerCrashTestCase(unittest.TestCase):
    def destroyDb(self, *a):
        sqlmanager.query("DROP DATABASE IF EXISTS %s" %
                         (config.test.mysql.database, ),
                         user=config.test.mysql.root_user.name,
                         password=config.test.mysql.root_user.password,
                         host=config.test.mysql.host)

    def setUpServer(self):
        settings = pokernetworkconfig.Config([])
        settings.loadFromString(settings_xml_server)
        #
        # Setup database
        #
        self.db = PokerDatabase(settings)
        #
        # Setup server
        #
        self.service = pokerservice.PokerService(settings)
        self.service.verbose = 6

    # -------------------------------------------------
    def setUp(self):
        self.destroyDb()
        self.setUpServer()

    def tearDown(self):
        self.db.close()
        return self.service.stopService()

    def test01_cleanupCrashedTables(self):
        cursor = self.db.cursor()
        #
        # Although the name is not in the configuration file (settings),
        # it has a matching resthost_serial and is cleanedup
        #
        cursor.execute(
            'INSERT INTO user2table (user_serial, table_serial, money) VALUES (1000, 142, 10)'
        )
        cursor.execute(
            "INSERT INTO users (serial, created, name, password) VALUES (1000, 0, 'testuser', '')"
        )
        cursor.execute(
            "INSERT INTO user2money (user_serial, currency_serial, amount) VALUES (1000, 1, 0)"
        )
        #
        # resthost_serial does not match, the records are left untouched
        #
        cursor.execute(
            'INSERT INTO user2table (user_serial, table_serial, money) VALUES (1000, 202, 10)'
        )
        #
        # Table1 is in the configuration file and cleaned up even though
        # resthost_serial does not match
        #
        cursor.execute(
            'INSERT INTO tableconfigs (serial, name, variant, betting_structure, currency_serial) VALUES (1, "Table1", "holdem", "2-4-no-limit", 1)'
        )
        cursor.execute(
            'INSERT INTO tables (serial, resthost_serial, tableconfig_serial) VALUES (303, 1, 1)'
        )
        self.service.startService()
        cursor.execute("SELECT user_serial,table_serial FROM user2table")
        self.assertEqual(2, cursor.rowcount)
        self.assertEqual(((1000, 142), (1000, 202)), cursor.fetchall())
        cursor.execute("SELECT serial FROM tables")
        self.assertEqual((303, ), cursor.fetchone())
        cursor.execute("SELECT amount FROM user2money")
        #TODO this test sucks, data gets intermixed, rework!
        # self.assertEqual(11, cursor.fetchall())
        cursor.close()

    def test02_cleanupTourneys_refund(self):
        tourney_serial = '10'
        user_serial = '200'
        buy_in = '300'
        currency_serial = '44'
        cursor = self.db.cursor()
        cursor.execute(
            'INSERT INTO tourneys (serial,name,buy_in,currency_serial,description_short,description_long,variant,betting_structure,schedule_serial,resthost_serial,sit_n_go) VALUES (%s, "one", %s, %s, "", "", "holdem", "2-4-no-limit", 0, 1, "n")',
            (tourney_serial, buy_in, currency_serial))
        cursor.execute(
            'INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)',
            (user_serial, tourney_serial))
        cursor.execute(
            'INSERT INTO user2money (user_serial,currency_serial,amount) VALUES (%s,%s,0)',
            (user_serial, currency_serial))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' +
                       tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute(
            'SELECT amount FROM user2money WHERE user_serial = %s AND currency_serial = %s',
            (user_serial, currency_serial))
        self.assertEqual((0, ), cursor.fetchone())
        self.service.startService()
        cursor.execute('SELECT * FROM tourneys WHERE serial = %s',
                       tourney_serial)
        self.assertEqual(0, cursor.rowcount)
        cursor.execute(
            'SELECT amount FROM user2money WHERE user_serial = %s AND currency_serial = %s',
            (user_serial, currency_serial))
        self.assertEqual((300, ), cursor.fetchone())
        cursor.close()

    def test02_cleanupTourneys_restore(self):
        regular_tourney_serial = '10'
        sng_tourney_serial = '40'
        user_serial = '200'
        cursor = self.db.cursor()
        cursor.execute("DELETE FROM tourneys_schedule")
        #
        # Sit and go in 'registering' state is trashed
        #
        cursor.execute(
            'INSERT INTO tourneys (serial,name,description_short,description_long,variant,betting_structure,currency_serial,schedule_serial, resthost_serial) VALUES (%s, "one", "", "", "holdem", "2-4-no-limit", 0, 0, 1)',
            sng_tourney_serial)
        cursor.execute(
            'INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)',
            (user_serial, sng_tourney_serial))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' +
                       sng_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        #
        # Regular in 'registering' state is kept
        #
        cursor.execute(
            'INSERT INTO tourneys (serial,name,sit_n_go,start_time,description_short,description_long,variant,betting_structure,currency_serial,schedule_serial, resthost_serial) VALUES (%s, "one", "n", %s, "", "", "holdem", "2-4-no-limit", 0, 0, 1)',
            (regular_tourney_serial, seconds() + 2000))
        cursor.execute(
            'INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)',
            (user_serial, regular_tourney_serial))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' +
                       regular_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        #
        # Run cleanupTourneys as a side effect
        #
        self.service.startService()
        #
        # Sanity checks
        #
        self.assertEqual(
            [int(sng_tourney_serial),
             int(regular_tourney_serial)], self.service.tourneys.keys())
        cursor.execute('SELECT * FROM user2tourney WHERE tourney_serial = %s',
                       regular_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT * FROM user2tourney WHERE tourney_serial = %s',
                       sng_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT * FROM user2tourney')
        self.assertEqual(2, cursor.rowcount)
        cursor.execute('SELECT * FROM tourneys')
        self.assertEqual(2, cursor.rowcount)
        cursor.close()
コード例 #11
0
class PokerCrashTestCase(unittest.TestCase):

    def destroyDb(self, *a):
        sqlmanager.query("DROP DATABASE IF EXISTS %s" % (config.test.mysql.database,),
            user=config.test.mysql.root_user.name,
            password=config.test.mysql.root_user.password,
            host=config.test.mysql.host
        )

    def setUpServer(self):
        settings = pokernetworkconfig.Config([])
        settings.loadFromString(settings_xml_server)
        #
        # Setup database
        #
        self.db = PokerDatabase(settings)
        #
        # Setup server
        #
        self.service = pokerservice.PokerService(settings)
        self.service.verbose = 6

    # -------------------------------------------------
    def setUp(self):
        self.destroyDb()
        self.setUpServer()

    def tearDown(self):
        self.db.close()
        return self.service.stopService()

    def test01_cleanupCrashedTables(self):
        cursor = self.db.cursor()
        #
        # Although the name is not in the configuration file (settings),
        # it has a matching resthost_serial and is cleanedup
        #
        cursor.execute('INSERT INTO user2table (user_serial, table_serial, money) VALUES (1000, 142, 10)')
        cursor.execute("INSERT INTO users (serial, created, name, password) VALUES (1000, 0, 'testuser', '')")
        cursor.execute("INSERT INTO user2money (user_serial, currency_serial, amount) VALUES (1000, 1, 0)")
        #
        # resthost_serial does not match, the records are left untouched
        #
        cursor.execute('INSERT INTO user2table (user_serial, table_serial, money) VALUES (1000, 202, 10)')
        #
        # Table1 is in the configuration file and cleaned up even though
        # resthost_serial does not match
        #
        cursor.execute('INSERT INTO tableconfigs (serial, name, variant, betting_structure, currency_serial) VALUES (1, "Table1", "holdem", "2-4-no-limit", 1)')
        cursor.execute('INSERT INTO tables (serial, resthost_serial, tableconfig_serial) VALUES (303, 1, 1)')
        self.service.startService()
        cursor.execute("SELECT user_serial,table_serial FROM user2table")
        self.assertEqual(2, cursor.rowcount)
        self.assertEqual(((1000, 142),(1000, 202)), cursor.fetchall())
        cursor.execute("SELECT serial FROM tables")
        self.assertEqual((303,), cursor.fetchone())
        cursor.execute("SELECT amount FROM user2money")
        #TODO this test sucks, data gets intermixed, rework!
        # self.assertEqual(11, cursor.fetchall())
        cursor.close()

    def test02_cleanupTourneys_refund(self):
        tourney_serial = '10'
        user_serial = '200'
        buy_in = '300'
        currency_serial = '44'
        cursor = self.db.cursor()
        cursor.execute('INSERT INTO tourneys (serial,name,buy_in,currency_serial,description_short,description_long,variant,betting_structure,schedule_serial,resthost_serial,sit_n_go) VALUES (%s, "one", %s, %s, "", "", "holdem", "2-4-no-limit", 0, 1, "n")', ( tourney_serial, buy_in, currency_serial ))
        cursor.execute('INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)', ( user_serial, tourney_serial ))
        cursor.execute('INSERT INTO user2money (user_serial,currency_serial,amount) VALUES (%s,%s,0)', ( user_serial, currency_serial ))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' + tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT amount FROM user2money WHERE user_serial = %s AND currency_serial = %s', ( user_serial, currency_serial ))
        self.assertEqual((0,), cursor.fetchone())
        self.service.startService()
        cursor.execute('SELECT * FROM tourneys WHERE serial = %s', tourney_serial)
        self.assertEqual(0, cursor.rowcount)
        cursor.execute('SELECT amount FROM user2money WHERE user_serial = %s AND currency_serial = %s', ( user_serial, currency_serial ))
        self.assertEqual((300,), cursor.fetchone())
        cursor.close()

    def test02_cleanupTourneys_restore(self):
        regular_tourney_serial = '10'
        sng_tourney_serial = '40'
        user_serial = '200'
        cursor = self.db.cursor()
        cursor.execute("DELETE FROM tourneys_schedule")
        #
        # Sit and go in 'registering' state is trashed
        #
        cursor.execute('INSERT INTO tourneys (serial,name,description_short,description_long,variant,betting_structure,currency_serial,schedule_serial, resthost_serial) VALUES (%s, "one", "", "", "holdem", "2-4-no-limit", 0, 0, 1)', sng_tourney_serial)
        cursor.execute('INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)', ( user_serial, sng_tourney_serial ))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' + sng_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        #
        # Regular in 'registering' state is kept
        #
        cursor.execute('INSERT INTO tourneys (serial,name,sit_n_go,start_time,description_short,description_long,variant,betting_structure,currency_serial,schedule_serial, resthost_serial) VALUES (%s, "one", "n", %s, "", "", "holdem", "2-4-no-limit", 0, 0, 1)', ( regular_tourney_serial, seconds() + 2000))
        cursor.execute('INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)', ( user_serial, regular_tourney_serial ))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' + regular_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        #
        # Run cleanupTourneys as a side effect
        #
        self.service.startService()
        #
        # Sanity checks
        #
        self.assertEqual([int(sng_tourney_serial), int(regular_tourney_serial)], self.service.tourneys.keys())
        cursor.execute('SELECT * FROM user2tourney WHERE tourney_serial = %s', regular_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT * FROM user2tourney WHERE tourney_serial = %s', sng_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT * FROM user2tourney')
        self.assertEqual(2, cursor.rowcount)
        cursor.execute('SELECT * FROM tourneys')
        self.assertEqual(2, cursor.rowcount)
        cursor.close()
コード例 #12
0
 def setUp(self):
     self.setupDb()
     self.settings = pokernetworkconfig.Config([])
     self.settings.loadFromString(settings_xml)
     self.db = PokerDatabase(self.settings)
コード例 #13
0
class PokerAuthTestCase(unittest.TestCase):
        

    def setupDb(self):
        sqlmanager.setup_db(
            TESTS_PATH + "/../database/schema.sql", (
                ("INSERT INTO tableconfigs (name, variant, betting_structure, seats, currency_serial) VALUES (%s, 'holdem', %s, 10, 1)", (
                    ('Table1','100-200_2000-20000_no-limit'),
                    ('Table2','100-200_2000-20000_no-limit'),
                )),
                ("INSERT INTO tables (resthost_serial, tableconfig_serial) VALUES (%s, %s)", (
                    (1, 1),
                    (1, 2),
                )),
            ),
            user=config.test.mysql.root_user.name,
            password=config.test.mysql.root_user.password,
            host=config.test.mysql.host,
            port=config.test.mysql.port,
            database=config.test.mysql.database
        )

    def setUp(self):
        self.setupDb()
        self.settings = pokernetworkconfig.Config([])
        self.settings.loadFromString(settings_xml)
        self.db = PokerDatabase(self.settings)

    def tearDown(self):
        pokerauth._get_auth_instance = None

    def test01_Init(self):
        """test01_Init
        Test Poker auth : get_auth_instance"""
        db = None
        settings = pokernetworkconfig.Config([])
        settings.loadFromString(settings_xml)
        auth = pokerauth.get_auth_instance(db, None, settings)
        

    def test02_AlternatePokerAuth(self):
        """test02_AlternatePokerAuth
        Test Poker auth : get_auth_instance alternate PokerAuth"""
        db = None
        settings = pokernetworkconfig.Config([])
        settings.loadFromString(settings_alternate_xml)
        auth = pokerauth.get_auth_instance(db, None, settings)

    def checkIfUserExistsInDB(self, name, selectString = "SELECT serial from users where name = '%s'"):
        cursor = self.db.cursor()
        cursor.execute(selectString % name)
        if cursor.rowcount == 1:
            (serial,) = cursor.fetchone()
            cursor.close()
            return [serial]
        elif cursor.rowcount == 0:
            cursor.close()
            return []
        else:
            serials = []
            for row in cursor.fetchall(): serials.append(row['serial'])
            cursor.close()
            return serials

    def test03_authWithAutoCreate(self):
        """test03_authWithAutoCreate
        Test Poker auth : Try basic auth with autocreate on"""
        db = self.db
        settings = pokernetworkconfig.Config([])
        autocreate_xml = settings_xml.replace('<server auto_create_account="no" ', '<server auto_create_account="yes" ')
        settings.doc = libxml2.parseMemory(autocreate_xml, len(autocreate_xml))
        settings.header = settings.doc.xpathNewContext()
        auth = pokerauth.get_auth_instance(db, None, settings)

        self.assertEquals(auth.auth(PACKET_LOGIN,('joe_schmoe', 'foo')), ((4, 'joe_schmoe', 1), None))
        self.assertEquals(log_history.get_all()[-1], 'created user.  serial: 4, name: joe_schmoe')
        self.failUnless(len(self.checkIfUserExistsInDB('joe_schmoe')) == 1)

    def test04_authWithoutAutoCreate(self, expectedMessage = 'user does not exist.  name: john_smith'):
        """test04_authWithoutAutoCreate
        Test Poker auth : Try basic auth with autocreate on"""
        auth = pokerauth.get_auth_instance(self.db, None, self.settings)


        self.assertEquals(auth.auth(PACKET_LOGIN,('john_smith', 'blah')), (False, 'Invalid login or password'))
        if expectedMessage:
            self.assertEquals(log_history.get_all()[-1], expectedMessage)
        self.failUnless(len(self.checkIfUserExistsInDB('john_smith')) == 0)

    def test05_authWhenDoubleEntry(self):
        """test05_authWhenDoubleEntry
        Tests case in fallback authentication where more than one entry exists.
        """
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE users")
        cursor.execute("""CREATE TABLE users (
 	    serial int unsigned not null auto_increment,
	    name varchar(32), password varchar(32), privilege int default 1,
            primary key (serial))""")
        for ii in [1,2]:
            cursor.execute("INSERT INTO users (name, password) values (%s, %s)", ('doyle_brunson', 'foo'))
        cursor.close()

        auth = pokerauth.get_auth_instance(self.db, None, self.settings)
        
        log_history.reset()
        self.assertEquals(auth.auth(PACKET_LOGIN,('doyle_brunson', 'foo')), (False, "Invalid login or password"))
        self.assertEquals(log_history.get_all(), ['multiple entries for user in database.  name: doyle_brunson'])

    def test06_validAuthWhenEntryExists(self):
        """test06_validAuthWhenEntryExists
        Tests case for single-row returned existing auth, both success and failure.
        """
        cursor = self.db.cursor()
        cursor.execute(
            "INSERT INTO users (created, name, password) values (%s, %s, %s)",
            (seconds(), 'dan_harrington', 'bar')
        )
        cursor.close()

        auth = pokerauth.get_auth_instance(self.db, None, self.settings)

        log_history.reset()
        self.assertEquals(auth.auth(PACKET_LOGIN,('dan_harrington', 'bar')), ((4L, 'dan_harrington', 1L), None))
        self.assertEquals(log_history.get_all(), [])
        
        log_history.reset()
        self.assertEquals(auth.auth(PACKET_LOGIN,('dan_harrington', 'wrongpass')), (False, 'Invalid login or password'))
        self.assertEquals(log_history.get_all(), ['invalid password in login attempt.  name: dan_harrington, serial: 4'])

    def test07_mysql11userCreate(self):
        """test07_mysql11userCreate
        Tests userCreate() as it will behave under MySQL 1.1 by mocking up
        the situation.
        """
        class MockCursor:
            def __init__(self):
                self.lastrowid = 4815
            def execute(self, *a): pass
            def close(self): pass
        class MockDatabase:
            def cursor(self): return MockCursor()
            
        auth = pokerauth.get_auth_instance(MockDatabase(), None, self.settings)
        self.assertEquals(auth.userCreate("nobody", "nothing"), 4815)
        self.assertEquals(log_history.get_all()[-1], 'created user.  serial: 4815, name: nobody')

    def test08_mysqlbeyond11userCreate(self):
        """test08_mysqlbeyond11userCreate
        Tests userCreate() as it will behave under MySQL > 1.1 by mocking up
        the situation.
        """
        class MockCursor:
            def __init__(self):
                self.lastrowid = 162342
            def execute(self, *a): pass
            def close(self): pass
        class MockDatabase:
            def cursor(self): return MockCursor()

        auth = pokerauth.get_auth_instance(MockDatabase(), None, self.settings)
        self.assertEquals(auth.userCreate("somebody", "something"), 162342)
        self.assertEquals(log_history.get_all()[-1], 'created user.  serial: 162342, name: somebody')

    def test09_setAndGetLevel(self):
        """test09_setAndGetLevel
        Tests the SetLevel and GetLevel methods.
        """
        auth = pokerauth.get_auth_instance(self.db, None, self.settings)

        self.assertEquals(auth.GetLevel('first'), False)
        self.assertEquals(auth.SetLevel('first', 7), None)
        self.assertEquals(auth.GetLevel('first'), 7)
        self.assertEquals(auth.GetLevel('second'), False)
コード例 #14
0
class PokerCrashTestCase(unittest.TestCase):
    def destroyDb(self, arg=None):
        os.system(
            "/usr/bin/mysql -u root -e 'DROP DATABASE IF EXISTS pokernetworktest'"
        )

    def setUpServer(self):
        settings = pokernetworkconfig.Config([])
        settings.doc = libxml2.parseMemory(settings_xml_server,
                                           len(settings_xml_server))
        settings.header = settings.doc.xpathNewContext()
        #
        # Setup database
        #
        self.db = PokerDatabase(settings)
        #
        # Setup server
        #
        self.service = pokerservice.PokerService(settings)
        self.service.verbose = 6

    # -------------------------------------------------
    def setUp(self):
        self.destroyDb()
        self.setUpServer()

    def tearDown(self):
        self.db.close()
        return self.service.stopService()

    def test01_cleanupCrashedTables(self):
        cursor = self.db.cursor()
        #
        # Although the name is not in the configuration file (settings),
        # it has a matching resthost_serial and is cleanedup
        #
        cursor.execute(
            'INSERT INTO pokertables (serial, name, variant, betting_structure, currency_serial) VALUES (142, "one", "holdem", "2-4", 1)'
        )
        cursor.execute(
            'INSERT INTO user2table (user_serial, table_serial, money, bet) VALUES (1000, 142, 10, 1)'
        )
        cursor.execute(
            "INSERT INTO users (serial, created, name) VALUES (1000, 0, 'testuser')"
        )
        cursor.execute(
            "INSERT INTO user2money (user_serial, currency_serial, amount) VALUES (1000, 1, 0)"
        )
        #
        # resthost_serial does not match, the records are left untouched
        #
        cursor.execute(
            'INSERT INTO pokertables (serial, name, variant, betting_structure, currency_serial, resthost_serial) VALUES (202, "two", "holdem", "2-4", 1, 10)'
        )
        cursor.execute(
            'INSERT INTO user2table (user_serial, table_serial, money, bet) VALUES (1000, 202, 10, 1)'
        )
        #
        # Table1 is in the configuration file and cleaned up even though
        # resthost_serial does not match
        #
        cursor.execute(
            'INSERT INTO pokertables (serial, name, variant, betting_structure, currency_serial, resthost_serial) VALUES (303, "Table1", "holdem", "2-4", 1, 44)'
        )
        self.service.startService()
        cursor.execute("SELECT user_serial,table_serial FROM user2table")
        self.assertEqual(1, cursor.rowcount)
        self.assertEqual((1000, 202), cursor.fetchone())
        cursor.execute("SELECT serial FROM pokertables")
        self.assertEqual((202, ), cursor.fetchone())
        cursor.execute("SELECT amount FROM user2money")
        self.assertEqual(11, cursor.fetchone()[0])
        cursor.close()

    def test02_cleanupTourneys_refund(self):
        tourney_serial = '10'
        user_serial = '200'
        buy_in = '300'
        currency_serial = '44'
        cursor = self.db.cursor()
        cursor.execute(
            'INSERT INTO tourneys (serial,name,buy_in,currency_serial) VALUES (%s, "one", %s, %s)',
            (tourney_serial, buy_in, currency_serial))
        cursor.execute(
            'INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)',
            (user_serial, tourney_serial))
        cursor.execute(
            'INSERT INTO user2money (user_serial,currency_serial) VALUES (%s,%s)',
            (user_serial, currency_serial))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' +
                       tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute(
            'SELECT amount FROM user2money WHERE user_serial = %s AND currency_serial = %s',
            (user_serial, currency_serial))
        self.assertEqual((0, ), cursor.fetchone())
        self.service.startService()
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' +
                       tourney_serial)
        self.assertEqual(0, cursor.rowcount)
        cursor.execute(
            'SELECT amount FROM user2money WHERE user_serial = %s AND currency_serial = %s',
            (user_serial, currency_serial))
        self.assertEqual((300, ), cursor.fetchone())
        cursor.close()

    def test02_cleanupTourneys_restore(self):
        regular_tourney_serial = '10'
        sng_tourney_serial = '40'
        user_serial = '200'
        cursor = self.db.cursor()
        cursor.execute("DELETE FROM tourneys_schedule")
        #
        # Sit and go in 'registering' state is trashed
        #
        cursor.execute('INSERT INTO tourneys (serial,name) VALUES (%s, "one")',
                       sng_tourney_serial)
        cursor.execute(
            'INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)',
            (user_serial, sng_tourney_serial))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' +
                       sng_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        #
        # Regular in 'registering' state is kept
        #
        cursor.execute(
            'INSERT INTO tourneys (serial,name,sit_n_go,start_time) VALUES (%s, "one", "n", %s)',
            (regular_tourney_serial, seconds() + 2000))
        cursor.execute(
            'INSERT INTO user2tourney (user_serial,currency_serial,tourney_serial) VALUES (%s,1,%s)',
            (user_serial, regular_tourney_serial))
        cursor.execute('SELECT * FROM tourneys WHERE serial = ' +
                       regular_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        #
        # Run cleanupTourneys as a side effect
        #
        self.service.startService()
        #
        # Sanity checks
        #
        self.assertEqual([int(regular_tourney_serial)],
                         self.service.tourneys.keys())
        cursor.execute('SELECT * FROM user2tourney WHERE tourney_serial = %s',
                       regular_tourney_serial)
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT * FROM user2tourney WHERE tourney_serial = %s',
                       sng_tourney_serial)
        self.assertEqual(0, cursor.rowcount)
        cursor.execute('SELECT * FROM user2tourney')
        self.assertEqual(1, cursor.rowcount)
        cursor.execute('SELECT * FROM tourneys')
        self.assertEqual(1, cursor.rowcount)
        cursor.close()
コード例 #15
0
 def setUp(self):
     self.destroyDb()
     self.settings = pokernetworkconfig.Config([])
     self.settings.doc = libxml2.parseMemory(settings_xml, len(settings_xml))
     self.settings.header = self.settings.doc.xpathNewContext()
     self.db = PokerDatabase(self.settings)
コード例 #16
0
class PokerAuthTestCase(unittest.TestCase):

    # -----------------------------------------------------------------------------------------------------
    def destroyDb(self):
        if len("") > 0:
            os.system(
                "/usr/bin/mysql -u root --password='' -h 'localhost' -e 'DROP DATABASE IF EXISTS pokernetworktest'"
            )
        else:
            os.system("/usr/bin/mysql -u root -h 'localhost' -e 'DROP DATABASE IF EXISTS pokernetworktest'")

    # --------------------------------------------------------
    def setUp(self):
        self.destroyDb()
        self.settings = pokernetworkconfig.Config([])
        self.settings.doc = libxml2.parseMemory(settings_xml, len(settings_xml))
        self.settings.header = self.settings.doc.xpathNewContext()
        self.db = PokerDatabase(self.settings)

    # -----------------------------------------------------------------------------------------------------
    def tearDown(self):
        pokerauth._get_auth_instance = None

    # -----------------------------------------------------------------------------------------------------
    def test01_Init(self):
        """test01_Init
        Test Poker auth : get_auth_instance"""
        db = None
        settings = pokernetworkconfig.Config([])
        settings.doc = libxml2.parseMemory(settings_xml, len(settings_xml))
        settings.header = settings.doc.xpathNewContext()
        auth = pokerauth.get_auth_instance(db, settings)

    # -----------------------------------------------------------------------------------------------------
    def test02_AlternatePokerAuth(self):
        """test02_AlternatePokerAuth
        Test Poker auth : get_auth_instance alternate PokerAuth"""
        db = None
        settings = pokernetworkconfig.Config([])
        settings.doc = libxml2.parseMemory(settings_alternate_xml, len(settings_alternate_xml))
        settings.header = settings.doc.xpathNewContext()
        auth = pokerauth.get_auth_instance(db, settings)
        self.failUnless(hasattr(auth, "gotcha"))

    # -----------------------------------------------------------------------------------------------------
    def checkIfUserExistsInDB(self, name, selectString="SELECT serial from users where name = '%s'"):
        cursor = self.db.cursor()
        cursor.execute(selectString % name)
        if cursor.rowcount == 1:
            (serial,) = cursor.fetchone()
            cursor.close()
            return [serial]
        elif cursor.rowcount == 0:
            cursor.close()
            return []
        else:
            serials = []
            for row in cursor.fetchall():
                serials.append(row["serial"])
            cursor.close()
            return serials

    # -----------------------------------------------------------------------------------------------------
    def test03_authWithAutoCreate(self):
        """test03_authWithAutoCreate
        Test Poker auth : Try basic auth with autocreate on"""
        db = self.db
        settings = pokernetworkconfig.Config([])
        autocreate_xml = settings_xml.replace('<server auto_create_account="no" ', "<server ")
        settings.doc = libxml2.parseMemory(autocreate_xml, len(autocreate_xml))
        settings.header = settings.doc.xpathNewContext()
        auth = pokerauth.get_auth_instance(db, settings)

        clear_all_messages()
        self.assertEquals(auth.auth("joe_schmoe", "foo"), ((4, "joe_schmoe", 1), None))
        self.assertEquals(
            get_messages(),
            ["user joe_schmoe does not exist, create it", "creating user joe_schmoe", "create user with serial 4"],
        )
        self.failUnless(len(self.checkIfUserExistsInDB("joe_schmoe")) == 1)

    # -----------------------------------------------------------------------------------------------------
    def test04_authWithoutAutoCreate(self, expectedMessage="user john_smith does not exist"):
        """test04_authWithoutAutoCreate
        Test Poker auth : Try basic auth with autocreate on"""
        auth = pokerauth.get_auth_instance(self.db, self.settings)

        clear_all_messages()

        self.assertEquals(auth.auth("john_smith", "blah"), (False, "Invalid login or password"))
        if expectedMessage:
            self.assertTrue(search_output(expectedMessage))
        self.failUnless(len(self.checkIfUserExistsInDB("john_smith")) == 0)

    # -----------------------------------------------------------------------------------------------------
    def test05_authWhenDoubleEntry(self):
        """test05_authWhenDoubleEntry
        Tests case in fallback authentication where more than one entry exists.
        """
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE users")
        cursor.execute(
            """CREATE TABLE users (
 	    serial int unsigned not null auto_increment,
	    name varchar(32), password varchar(32), privilege int default 1,
            primary key (serial))"""
        )
        for ii in [1, 2]:
            cursor.execute("INSERT INTO users (name, password) values ('%s', '%s')" % ("doyle_brunson", "foo"))
        cursor.close()

        auth = pokerauth.get_auth_instance(self.db, self.settings)

        clear_all_messages()
        self.assertEquals(auth.auth("doyle_brunson", "foo"), (False, "Invalid login or password"))
        self.assertEquals(get_messages(), ["*ERROR* more than one row for doyle_brunson"])

    # -----------------------------------------------------------------------------------------------------
    def test06_validAuthWhenEntryExists(self):
        """test06_validAuthWhenEntryExists
        Tests case for single-row returned existing auth, both success and failure.
        """
        cursor = self.db.cursor()
        cursor.execute(
            "INSERT INTO users (created, name, password) values (%d, '%s', '%s')" % (seconds(), "dan_harrington", "bar")
        )
        cursor.close()

        auth = pokerauth.get_auth_instance(self.db, self.settings)

        clear_all_messages()
        self.assertEquals(auth.auth("dan_harrington", "bar"), ((4L, "dan_harrington", 1L), None))
        self.assertEquals(get_messages(), [])

        clear_all_messages()
        self.assertEquals(auth.auth("dan_harrington", "wrongpass"), (False, "Invalid login or password"))
        self.assertEquals(get_messages(), ["password mismatch for dan_harrington"])

    # -----------------------------------------------------------------------------------------------------
    def test07_mysql11userCreate(self):
        """test07_mysql11userCreate
        Tests userCreate() as it will behave under MySQL 1.1 by mocking up
        the situation.
        """

        class MockCursor:
            def execute(self, str):
                pass

            def insert_id(self):
                return 4815

            def close(self):
                pass

        class MockDatabase:
            def cursor(self):
                return MockCursor()

        clear_all_messages()
        auth = pokerauth.get_auth_instance(MockDatabase(), self.settings)
        self.assertEquals(auth.userCreate("nobody", "nothing"), 4815)
        self.assertTrue(search_output("creating user nobody"))
        self.assertTrue(search_output("create user with serial 4815"))

    # -----------------------------------------------------------------------------------------------------
    def test08_mysqlbeyond11userCreate(self):
        """test08_mysqlbeyond11userCreate
        Tests userCreate() as it will behave under MySQL > 1.1 by mocking up
        the situation.
        """

        class MockCursor:
            def __init__(self):
                self.lastrowid = 162342

            def execute(self, str):
                pass

            def insert_id(self):
                self.failIf(1)

            def close(self):
                pass

        class MockDatabase:
            def cursor(self):
                return MockCursor()

        clear_all_messages()
        auth = pokerauth.get_auth_instance(MockDatabase(), self.settings)
        self.assertEquals(auth.userCreate("somebody", "something"), 162342)
        self.assertTrue(search_output("creating user somebody"))
        self.assertTrue(search_output("create user with serial 162342"))

    # -----------------------------------------------------------------------------------------------------
    def test09_setAndGetLevel(self):
        """test09_setAndGetLevel
        Tests the SetLevel and GetLevel methods.
        """
        auth = pokerauth.get_auth_instance(self.db, self.settings)

        self.assertEquals(auth.GetLevel("first"), False)
        self.assertEquals(auth.SetLevel("first", 7), None)
        self.assertEquals(auth.GetLevel("first"), 7)
        self.assertEquals(auth.GetLevel("second"), False)
コード例 #17
0
class PokerAuthTestCase(unittest.TestCase):
        
    # -----------------------------------------------------------------------------------------------------
    def destroyDb(self, *a):
        sqlmanager.query("DROP DATABASE IF EXISTS %s" % (config.test.mysql.database,),
            user=config.test.mysql.root_user.name,
            password=config.test.mysql.root_user.password,
            host=config.test.mysql.host
        )
    # --------------------------------------------------------
    def setUp(self):
        self.destroyDb()
        self.settings = pokernetworkconfig.Config([])
        self.settings.doc = libxml2.parseMemory(settings_xml, len(settings_xml))
        self.settings.header = self.settings.doc.xpathNewContext()
        self.db = PokerDatabase(self.settings)
    # -----------------------------------------------------------------------------------------------------    
    def tearDown(self):
        pokerauth._get_auth_instance = None
    # -----------------------------------------------------------------------------------------------------    
    def test01_Init(self):
        """test01_Init
        Test Poker auth : get_auth_instance"""
        db = None
        settings = pokernetworkconfig.Config([])
        settings.loadFromString(settings_xml)
        auth = pokerauth.get_auth_instance(db, None, settings)
        
    # -----------------------------------------------------------------------------------------------------    
    def test02_AlternatePokerAuth(self):
        """test02_AlternatePokerAuth
        Test Poker auth : get_auth_instance alternate PokerAuth"""
        db = None
        settings = pokernetworkconfig.Config([])
        settings.loadFromString(settings_alternate_xml)
        auth = pokerauth.get_auth_instance(db, None, settings)
        self.assertTrue(auth.gotcha)
    # -----------------------------------------------------------------------------------------------------    
    def checkIfUserExistsInDB(self, name, selectString = "SELECT serial from users where name = '%s'"):
        cursor = self.db.cursor()
        cursor.execute(selectString % name)
        if cursor.rowcount == 1:
            (serial,) = cursor.fetchone()
            cursor.close()
            return [serial]
        elif cursor.rowcount == 0:
            cursor.close()
            return []
        else:
            serials = []
            for row in cursor.fetchall(): serials.append(row['serial'])
            cursor.close()
            return serials
    # -----------------------------------------------------------------------------------------------------    
    def test03_authWithAutoCreate(self):
        """test03_authWithAutoCreate
        Test Poker auth : Try basic auth with autocreate on"""
        db = self.db
        settings = pokernetworkconfig.Config([])
        autocreate_xml = settings_xml.replace('<server auto_create_account="no" ', '<server auto_create_account="yes" ')
        settings.doc = libxml2.parseMemory(autocreate_xml, len(autocreate_xml))
        settings.header = settings.doc.xpathNewContext()
        auth = pokerauth.get_auth_instance(db, None, settings)

        self.assertEquals(auth.auth(PACKET_LOGIN,('joe_schmoe', 'foo')), ((4, 'joe_schmoe', 1), None))
        self.assertEquals(log_history.get_all()[-3:], [
            'user joe_schmoe does not exist, create it',
            'creating user joe_schmoe', 
            'create user with serial 4'
        ])
        self.failUnless(len(self.checkIfUserExistsInDB('joe_schmoe')) == 1)
    # -----------------------------------------------------------------------------------------------------    
    def test04_authWithoutAutoCreate(self, expectedMessage = 'user john_smith does not exist'):
        """test04_authWithoutAutoCreate
        Test Poker auth : Try basic auth with autocreate on"""
        auth = pokerauth.get_auth_instance(self.db, None, self.settings)


        self.assertEquals(auth.auth(PACKET_LOGIN,('john_smith', 'blah')), (False, 'Invalid login or password'))
        if expectedMessage:
            self.assertTrue(log_history.search(expectedMessage))
        self.failUnless(len(self.checkIfUserExistsInDB('john_smith')) == 0)
    # -----------------------------------------------------------------------------------------------------    
    def test05_authWhenDoubleEntry(self):
        """test05_authWhenDoubleEntry
        Tests case in fallback authentication where more than one entry exists.
        """
        cursor = self.db.cursor()
        cursor.execute("DROP TABLE users")
        cursor.execute("""CREATE TABLE users (
 	    serial int unsigned not null auto_increment,
	    name varchar(32), password varchar(32), privilege int default 1,
            primary key (serial))""")
        for ii in [1,2]:
            cursor.execute("INSERT INTO users (name, password) values (%s, %s)", ('doyle_brunson', 'foo'))
        cursor.close()

        auth = pokerauth.get_auth_instance(self.db, None, self.settings)
        
        log_history.reset()
        self.assertEquals(auth.auth(PACKET_LOGIN,('doyle_brunson', 'foo')), (False, "Invalid login or password"))
        self.assertEquals(log_history.get_all(), ['more than one row for doyle_brunson'])
    # -----------------------------------------------------------------------------------------------------    
    def test06_validAuthWhenEntryExists(self):
        """test06_validAuthWhenEntryExists
        Tests case for single-row returned existing auth, both success and failure.
        """
        cursor = self.db.cursor()
        cursor.execute(
            "INSERT INTO users (created, name, password) values (%s, %s, %s)",
            (seconds(), 'dan_harrington', 'bar')
        )
        cursor.close()

        auth = pokerauth.get_auth_instance(self.db, None, self.settings)

        log_history.reset()
        self.assertEquals(auth.auth(PACKET_LOGIN,('dan_harrington', 'bar')), ((4L, 'dan_harrington', 1L), None))
        self.assertEquals(log_history.get_all(), [])
        
        log_history.reset()
        self.assertEquals(auth.auth(PACKET_LOGIN,('dan_harrington', 'wrongpass')), (False, 'Invalid login or password'))
        self.assertEquals(log_history.get_all(), ['password mismatch for dan_harrington'])
    # -----------------------------------------------------------------------------------------------------    
    def test07_mysql11userCreate(self):
        """test07_mysql11userCreate
        Tests userCreate() as it will behave under MySQL 1.1 by mocking up
        the situation.
        """
        class MockCursor:
            def __init__(self):
                self.lastrowid = 4815
            def execute(self, *a): pass
            def close(self): pass
        class MockDatabase:
            def cursor(self): return MockCursor()
            
        auth = pokerauth.get_auth_instance(MockDatabase(), None, self.settings)
        self.assertEquals(auth.userCreate("nobody", "nothing"), 4815)
        self.assertTrue(log_history.search('creating user nobody'))
        self.assertTrue(log_history.search('create user with serial 4815'))
    # -----------------------------------------------------------------------------------------------------    
    def test08_mysqlbeyond11userCreate(self):
        """test08_mysqlbeyond11userCreate
        Tests userCreate() as it will behave under MySQL > 1.1 by mocking up
        the situation.
        """
        class MockCursor:
            def __init__(self):
                self.lastrowid = 162342
            def execute(self, *a): pass
            def close(self): pass
        class MockDatabase:
            def cursor(self): return MockCursor()

        auth = pokerauth.get_auth_instance(MockDatabase(), None, self.settings)
        self.assertEquals(auth.userCreate("somebody", "something"), 162342)
        self.assertTrue(log_history.search('creating user somebody'))
        self.assertTrue(log_history.search('create user with serial 162342'))
    # -----------------------------------------------------------------------------------------------------    
    def test09_setAndGetLevel(self):
        """test09_setAndGetLevel
        Tests the SetLevel and GetLevel methods.
        """
        auth = pokerauth.get_auth_instance(self.db, None, self.settings)

        self.assertEquals(auth.GetLevel('first'), False)
        self.assertEquals(auth.SetLevel('first', 7), None)
        self.assertEquals(auth.GetLevel('first'), 7)
        self.assertEquals(auth.GetLevel('second'), False)