def test1(self):
        tourney = PokerTournament(
            name = 'Test create',
            players_quota = 4,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = 4,
            betting_structure = "level-10-20-no-limit"
        )

        for serial in xrange(1,5):
            self.failUnless(tourney.register(serial))

        self.assertEqual(len(tourney.games), 1)
        for game in tourney.games:
            for serial in game.serialsAll():
                game.botPlayer(serial)
        turn = 1
        running = True
        while running:
            turn += 1
            if turn >= 200: raise Exception('Suspecting infity loop (more than 200 turns were played).')
            for game in tourney.games:
                game.beginTurn(turn)
                tourney.removeBrokePlayers(game.id, now=True)
                if game.id in tourney.id2game and not tourney.tourneyEnd(game.id):
                    running = False 
                    break
    def test3(self):
        #
        # Multi tables sit-n-go
        #
        seats_per_game = 10
        games_count = 2
        players_count = seats_per_game * games_count
        tourney = PokerTournament(
            name = 'Test create',
            players_quota = players_count,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = seats_per_game
        )

        for serial in xrange(1,players_count + 1):
            self.failUnless(tourney.register(serial))

        self.assertEqual(len(tourney.games), games_count)
        for game in tourney.games:
            for serial in game.serialsAll():
                game.botPlayer(serial)
        turn = 1
        running = True
        while running:
            turn += 1
            if turn >= 200: raise Exception('Suspecting infity loop (more than 200 turns were played).')
            for game in tourney.games:
                if game.sitCount() > 1:
                    game.beginTurn(turn)
                    tourney.removeBrokePlayers(game.id, now=True)
                    if game.id in tourney.id2game and not tourney.tourneyEnd(game.id):
                        running = False 
                        break
Example #3
0
    def testInactivePlayersAllInactiveButOne(self):
        arguments = {
            'dirs': [path.join(TESTS_PATH, '../conf')],
            'players_quota': 3,
            'seats_per_game': 3,
            'sit_n_go': 'y',
            'inactive_delay': 1
        }

        tourney = PokerTournament(**arguments)
        
        def gameCallbackTourneyEndTurn(game_id, game_type, *args):
            if game_type == 'end':
                tourney.endTurn(game_id)
                tourney.tourneyEnd(game_id)
                            
        serials = range(3)
        for s in serials: tourney.register(s)
        
        game = tourney.games[0]
        game.registerCallback(gameCallbackTourneyEndTurn)
        
        game.beginTurn(1)
        self.assertTrue(game.isFirstRound())
        
        tourney.start_time = 0
        
        winner = game.getSerialInPosition()
        game.call(winner)
        game.autoPlayer(game.getSerialInPosition())
        game.autoPlayer(game.getSerialInPosition())
        
        self.assertTrue(tourney.state == TOURNAMENT_STATE_COMPLETE)
        self.assertEqual(tourney.winners[0], winner)
Example #4
0
    def setUp(self):
        self.tourney = PokerTournament(name='Test create',
                                       players_quota=4,
                                       dirs=[path.join(TESTS_PATH, '../conf')],
                                       seats_per_game=4)
        for serial in xrange(1, 5):
            self.assertTrue(self.tourney.register(serial))

        self.game = self.tourney.games[0]
        self.players = self.game.playersAll()
Example #5
0
    def assertTourneyPrizes(self, prizes_specs, quota, register_i,
                            assert_prizes):
        tourney = PokerTournament(dirs=[path.join(TESTS_PATH, '../conf')],
                                  prizes_specs=prizes_specs,
                                  start_time=time.time() + 2000,
                                  sit_n_go='n',
                                  buy_in=5,
                                  players_quota=quota)

        for ii in xrange(1, register_i + 1):
            tourney.register(ii)

        self.assertEqual(tourney.prizes(), assert_prizes)
    def assertTourneyPrizes(self, prizes_specs, quota, register_i, assert_prizes):
        tourney = PokerTournament(
            dirs = [path.join(TESTS_PATH, '../conf')],
            prizes_specs=prizes_specs,
            start_time = time.time() + 2000,
            sit_n_go = 'n',
            buy_in = 5,
            players_quota = quota
        )

        for ii in xrange(1, register_i+1):
            tourney.register(ii)

        self.assertEqual(tourney.prizes(), assert_prizes)
Example #7
0
    def _set_up(self, options=None):
        default_opts = {
            'name': 'Test create',
            'players_quota': 4,
            'dirs': [path.join(TESTS_PATH, '../conf')],
            'seats_per_game': 4,
            'rebuy_delay': 600,
            'buy_in': 5,
            'prizes_specs':"table"
        }
        if options is not None:
            default_opts.update(options)
        self.tourney = PokerTournament(**default_opts)
        for serial in xrange(1,5):
            self.assertTrue(self.tourney.register(serial))

        self.game = self.tourney.games[0]
        self.players = self.game.playersAll()
Example #8
0
    def tourneyTableStartBalancedHelper(self, num_players, seats, num_tables,
                                        min_per_table):
        """tourneyTableStartBalancedHelper
        Helper function to test various scenarios of initial seating"""

        tourney = PokerTournament(name='Only%d' % num_players,
                                  players_quota=num_players,
                                  players_min=num_players,
                                  dirs=[path.join(TESTS_PATH, '../conf')],
                                  seats_per_game=seats,
                                  betting_structure="level-10-20-no-limit")

        for serial in xrange(1, num_players + 1):
            self.failUnless(tourney.register(serial))

        self.assertEquals(len(tourney.games), num_tables)
        for game in tourney.games:
            self.failUnless(len(game.serial2player.values()) >= min_per_table)
Example #9
0
    def testUnequalTables(self):

        tourney = PokerTournament(name='Test create',
                                  players_quota=4,
                                  dirs=[path.join(TESTS_PATH, '../conf')],
                                  seats_per_game=2)

        def tourneySoftRemovePlayer(self, game_id, serial, now):
            game = self.id2game[game_id]
            game.removePlayer(serial)
            self.finallyRemovePlayer(serial, now)

        def gameCallbackTourneyEndTurn(game_id, game_type, *args):
            if game_type == 'end':
                tourney.endTurn(game_id)
                tourney.tourneyEnd(game_id)

        for serial in xrange(1, 5):
            self.assertTrue(tourney.register(serial))

        for g in tourney.games:
            g.registerCallback(gameCallbackTourneyEndTurn)

        players = {}
        for g in tourney.games:
            for (serial, player) in g.serial2player.iteritems():
                players[serial] = player

        for g in tourney.games:
            g.beginTurn(1)

        broke_info = {}
        # in all games, one of the two players is getting broke.
        for g in tourney.games:
            serial = g.getSerialInPosition()
            broke_player = players[serial]
            broke_info[serial] = g.id
            broke_player.money = 0
            g.fold(serial)

        self.assertEquals(
            len(tourney.games), 1,
            'there should be only one game left (games: %s)' %
            tourney.id2game.keys())
    def setUp(self):
        self.tourney = PokerTournament(name = 'Test create',
            players_quota = 4,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = 4)
        for serial in xrange(1,5):
            self.assertTrue(self.tourney.register(serial))

        self.game = self.tourney.games[0]
        self.players = self.game.playersAll()
    def tourneyTableStartBalancedHelper(self, num_players, seats, num_tables, min_per_table):
        """tourneyTableStartBalancedHelper
        Helper function to test various scenarios of initial seating"""

        tourney = PokerTournament(
            name = 'Only%d' % num_players,
            players_quota = num_players,
            players_min = num_players,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = seats,
            betting_structure = "level-10-20-no-limit"
        )

        for serial in xrange(1,num_players+1):
            self.failUnless(tourney.register(serial))

        self.assertEquals(len(tourney.games), num_tables)
        for game in tourney.games:
            self.failUnless(len(game.serial2player.values()) >= min_per_table)
Example #12
0
    def test3(self):
        #
        # Multi tables sit-n-go
        #
        seats_per_game = 10
        games_count = 2
        players_count = seats_per_game * games_count
        tourney = PokerTournament(
            name = 'Test create',
            players_quota = players_count,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = seats_per_game
        )

        for serial in xrange(1,players_count + 1):
            self.failUnless(tourney.register(serial))

        self.assertEqual(len(tourney.games), games_count)
        for game in tourney.games:
            for serial in game.serialsAll():
                game.botPlayer(serial)
        turn = 1
        running = True
        while running:
            turn += 1
            if turn >= 200: raise Exception('Suspecting infity loop (more than 200 turns were played).')
            for game in tourney.games:
                if game.sitCount() > 1:
                    game.beginTurn(turn)
                    tourney.removeBrokePlayers(game.id, now=True)
                    if game.id in tourney.id2game and not tourney.tourneyEnd(game.id):
                        running = False 
                        break
 def testUnequalTables(self):
         
     tourney = PokerTournament(
         name = 'Test create',
         players_quota = 4,
         dirs = [path.join(TESTS_PATH, '../conf')],
         seats_per_game = 2
     )
     
     def tourneySoftRemovePlayer(self, game_id, serial, now):
         game = self.id2game[game_id]
         game.removePlayer(serial)
         self.finallyRemovePlayer(serial, now)
     
     def gameCallbackTourneyEndTurn(game_id, game_type, *args):
         if game_type == 'end':
             tourney.endTurn(game_id)
             tourney.tourneyEnd(game_id)
             
     for serial in xrange(1,5): self.assertTrue(tourney.register(serial))
     
     for g in tourney.games: g.registerCallback(gameCallbackTourneyEndTurn)
     
     players = {}
     for g in tourney.games:
         for (serial,player) in g.serial2player.iteritems(): players[serial] = player
     
     for g in tourney.games:
         g.beginTurn(1)
     
     broke_info = {}
     # in all games, one of the two players is getting broke.
     for g in tourney.games:
         serial = g.getSerialInPosition()
         broke_player = players[serial]
         broke_info[serial] = g.id
         broke_player.money = 0
         g.fold(serial)
     
     self.assertEquals(len(tourney.games),1,'there should be only one game left (games: %s)' % tourney.id2game.keys())
Example #14
0
    def test1(self):
        tourney = PokerTournament(
            name = 'Test create',
            players_quota = 4,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = 4,
            betting_structure = "level-10-20-no-limit"
        )

        for serial in xrange(1,5):
            self.failUnless(tourney.register(serial))

        self.assertEqual(len(tourney.games), 1)
        for game in tourney.games:
            for serial in game.serialsAll():
                game.botPlayer(serial)
        turn = 1
        running = True
        while running:
            turn += 1
            if turn >= 200: raise Exception('Suspecting infity loop (more than 200 turns were played).')
            for game in tourney.games:
                game.beginTurn(turn)
                tourney.removeBrokePlayers(game.id, now=True)
                if game.id in tourney.id2game and not tourney.tourneyEnd(game.id):
                    running = False 
                    break
Example #15
0
    def test2(self):
        #
        # One table sit-n-go
        #
        tourney = PokerTournament(name='Test create',
                                  players_quota=4,
                                  dirs=[path.join(TESTS_PATH, '../conf')],
                                  seats_per_game=4)

        for serial in xrange(1, 4):
            self.failUnless(tourney.register(serial))
            self.failUnless(tourney.unregister(serial))
            self.failUnless(tourney.register(serial))
        self.failUnless(tourney.register(4))
        self.failIf(tourney.unregister(4))

        self.assertEqual(len(tourney.games), 1)
        game = tourney.games[0]
        game.beginTurn(1)
    def test2(self):
        #
        # One table sit-n-go
        #
        tourney = PokerTournament(
            name = 'Test create',
            players_quota = 4,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = 4
        )

        for serial in xrange(1,4):
            self.failUnless(tourney.register(serial))
            self.failUnless(tourney.unregister(serial))
            self.failUnless(tourney.register(serial))
        self.failUnless(tourney.register(4))
        self.failIf(tourney.unregister(4))

        self.assertEqual(len(tourney.games), 1)
        game = tourney.games[0]
        game.beginTurn(1)
Example #17
0
class TestRebuy(unittest.TestCase):
    def setUp(self):
        self.tourney = PokerTournament(name='Test create',
                                       players_quota=4,
                                       dirs=[path.join(TESTS_PATH, '../conf')],
                                       seats_per_game=4)
        for serial in xrange(1, 5):
            self.assertTrue(self.tourney.register(serial))

        self.game = self.tourney.games[0]
        self.players = self.game.playersAll()

    def tearDown(self):
        del self.tourney

    def test1_insertedWinnersAreCorrect(self):
        winners = [1, 2, 3, 4]

        self.tourney.winners = winners
        self.assertEqual(self.tourney.winners, winners)

        self.tourney.winners = []
        self.assertEqual(self.tourney.winners, [])

    def test2(self):
        tourney = self.tourney
        game = self.game
        players = self.players

        def myremove_player(tournament, game_id, serial, now=False):
            if now:
                tournament.removePlayer(game_id, serial, now)

        tourney.callback_remove_player = myremove_player

        def setMoney(serial, money=0):
            for player in players:
                if player.serial != serial:
                    continue
                player.money = money
                if money == 0:
                    self.assertTrue(game.isBroke(serial))

        # Player got broke
        setMoney(1)
        self.assertEqual(tourney.winners, [])

        # Even removeBrokePlayers and endTurn doesn't remove him,
        # because he has a chance for rebuy
        tourney.removeBrokePlayers(1)
        self.assertEqual(tourney.winners, [])

        # Player 2 gets broke, and chooses not to rebuy
        setMoney(2)
        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        tourney.removePlayer(1, 2)
        self.assertEqual(tourney.winners, [2])
        self.assertEqual(tourney.getRank(2), 4)

        # After Player 1 Timed out, he will be also removed
        # Note: this changes the rank for player 2
        tourney.removePlayer(1, 1)

        self.assertEqual(tourney.winners, [2, 1])
        self.assertEqual(tourney.getRank(2), 3)
        self.assertEqual(tourney.getRank(1), 4)

        # Player 3 get broke but rebuys a few times
        for _i in range(4):
            setMoney(3)

            tourney.removeBrokePlayers(1)
            tourney.tourneyEnd(1)
            self.assertEqual(tourney.winners, [2, 1])

            setMoney(3, 2000)
            tourney.reenterGame(1, 3)

            tourney.removeBrokePlayers(1)
            tourney.tourneyEnd(1)
            self.assertEqual(tourney.winners, [2, 1])

        setMoney(4)

        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        self.assertEqual(tourney.winners, [2, 1])

        setMoney(4, 2000)
        tourney.reenterGame(1, 4)

        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        self.assertEqual(tourney.winners, [2, 1])

        setMoney(4)
        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        tourney.removePlayer(1, 4)

        self.assertFalse(tourney.tourneyEnd(1))

        self.assertEqual(tourney.winners, [3, 4, 2, 1])

    def testGetNextPositionWillReturnCorrectValue(self):
        def setMoney(ids, money=0):
            for player in self.players:
                if player.serial not in ids:
                    continue
                player.money = money
                if money == 0:
                    self.assertTrue(self.game.isBroke(player.serial))

        def sortTmpWinner():
            return [
                k
                for k, _v in sorted(self.tourney._winners_dict_tmp.iteritems(),
                                    key=lambda (a, b): (b, a),
                                    reverse=True)
            ]
            return self.tourney._winners_dict_tmp.keys()

        def removePlayer(serials):
            nid = self.tourney._incrementToNextWinnerPosition()
            for serial in serials:
                self.tourney._winners_dict_tmp[serial] = nid

        def reenterPlayer(serials):
            for serial in serials:
                del self.tourney._winners_dict_tmp[serial]

        self.assertEqual(sortTmpWinner(), [])
        removePlayer([3, 4])
        self.assertEqual(sortTmpWinner(), [4, 3])
        removePlayer([2])
        self.assertEqual(sortTmpWinner(), [2, 4, 3])
        reenterPlayer([3, 4])
        self.assertEqual(sortTmpWinner(), [2])
        removePlayer([1])
        self.assertEqual(sortTmpWinner(), [1, 2])

    def testUnequalTables(self):

        tourney = PokerTournament(name='Test create',
                                  players_quota=4,
                                  dirs=[path.join(TESTS_PATH, '../conf')],
                                  seats_per_game=2)

        def tourneySoftRemovePlayer(self, game_id, serial, now):
            game = self.id2game[game_id]
            game.removePlayer(serial)
            self.finallyRemovePlayer(serial, now)

        def gameCallbackTourneyEndTurn(game_id, game_type, *args):
            if game_type == 'end':
                tourney.endTurn(game_id)
                tourney.tourneyEnd(game_id)

        for serial in xrange(1, 5):
            self.assertTrue(tourney.register(serial))

        for g in tourney.games:
            g.registerCallback(gameCallbackTourneyEndTurn)

        players = {}
        for g in tourney.games:
            for (serial, player) in g.serial2player.iteritems():
                players[serial] = player

        for g in tourney.games:
            g.beginTurn(1)

        broke_info = {}
        # in all games, one of the two players is getting broke.
        for g in tourney.games:
            serial = g.getSerialInPosition()
            broke_player = players[serial]
            broke_info[serial] = g.id
            broke_player.money = 0
            g.fold(serial)

        self.assertEquals(
            len(tourney.games), 1,
            'there should be only one game left (games: %s)' %
            tourney.id2game.keys())
Example #18
0
class TestRebuy(unittest.TestCase):

    def setUp(self):
        self._set_up()

    def _set_up(self, options=None):
        default_opts = {
            'name': 'Test create',
            'players_quota': 4,
            'dirs': [path.join(TESTS_PATH, '../conf')],
            'seats_per_game': 4,
            'rebuy_delay': 600,
            'buy_in': 5,
            'prizes_specs':"table"
        }
        if options is not None:
            default_opts.update(options)
        self.tourney = PokerTournament(**default_opts)
        for serial in xrange(1,5):
            self.assertTrue(self.tourney.register(serial))

        self.game = self.tourney.games[0]
        self.players = self.game.playersAll()

    def tearDown(self):
        del self.tourney
        del self.game
        del self.players

    def test1_insertedWinnersAreCorrect(self):
        winners = [1,2,3,4]

        self.tourney.winners = winners
        self.assertEqual(self.tourney.winners, winners)

        self.tourney.winners = []
        self.assertEqual(self.tourney.winners, [])
        
    def test2(self):
        tourney = self.tourney
        game = self.game
        players = self.players
        player3 = [p for p in players if p.serial == 3][0]
        original_startmoney = player3.money

        def myremove_player(tournament, game_id, serial, now=False):
            if now:
                tournament.finallyRemovePlayer(serial, now)

        tourney.callback_remove_player = myremove_player
        def my_rebuy(tournament, serial, table_id, player_chips, tourney_chips):
            self.assertEqual(table_id, game.id)
            self.assertEqual(tourney.buy_in, player_chips)
            if serial == 1:
                return 0
            return tourney_chips

        tourney.callback_rebuy_payment = my_rebuy

        def updateShowdownStack(serial, money):
            if len(game.showdown_stack) == 0:
                game.showdown_stack.append({'serial2delta':{}})

            game.showdown_stack[0]['serial2delta'][serial] = - money

        def looseMoney(serial, set_money_to=0):
            for player in players:
                if player.serial != serial:
                    continue
                money = set_money_to - player.money
                player.money = set_money_to
                if set_money_to == 0:
                    self.assertTrue(game.isBroke(serial))
                updateShowdownStack(serial, money)

        # prizes will be cached, but we have to make sure that the rebuy process 
        # will update the cache.
        tourney.prizes()

        # Player got broke
        looseMoney(1)
        self.assertEqual(tourney.winners, [])

        # Even removeBrokePlayers and endTurn doesn't remove him, 
        # because he has a chance for rebuy
        tourney.removeBrokePlayers(1)
        self.assertEqual(tourney.winners, [])

        # Player 2 gets broke, and chooses not to rebuy
        looseMoney(2)
        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        tourney.removePlayer(1, 2)
        self.assertEqual(tourney.winners, [2])
        self.assertEqual(tourney.getRank(2), 4)

        # Player 1 tries to rebuy but has not enough money
        success, error = tourney.rebuyPlayerRequest(game.id, 1)
        self.assertFalse(success)
        self.assertEquals(error, "money")

        # After Player 1 Timed out, he will be also removed
        # Note: this changes the rank for player 2
        tourney.removePlayer(1, 1)

        self.assertEqual(tourney.winners, [2, 1])
        self.assertEqual(tourney.getRank(2), 3)
        self.assertEqual(tourney.getRank(1), 4)

        # Player 3 get broke but rebuys a few times
        for _i in range(4):
            looseMoney(3)
            self.assertEqual(player3.money, 0)

            tourney.removeBrokePlayers(1)
            tourney.tourneyEnd(1)
            self.assertEqual(tourney.winners, [2, 1])

            success, error = tourney.rebuyPlayerRequest(game.id, 3)
            self.assertTrue(success, error)

            tourney.removeBrokePlayers(1)
            tourney.tourneyEnd(1)
            self.assertEqual(tourney.winners, [2, 1])

        # after the rebuy player 3 has the same money as he started 
        self.assertEqual(original_startmoney, player3.money)
        self.assertEqual(tourney.winners, [2, 1])

        looseMoney(4, set_money_to=game.buyIn())

        # rebuy will fail because users money plus the new game.buyIn() is bigger than game.maxBuyIn()
        success, error = tourney.rebuyPlayerRequest(game.id, 4)
        self.assertFalse(success)
        self.assertEqual(error, "user")

        looseMoney(4, set_money_to=game.buyIn()-1)
        success, error = tourney.rebuyPlayerRequest(game.id, 4)
        self.assertTrue(success)
        
        looseMoney(4)
        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        
        # if game.rebuy fails, there should be an error message in the log!
        log_history.reset()
        self.assertEqual(log_history.get_all(), [])
        old_rebuy = game.rebuy
        game.rebuy = lambda *args, **kw: False
        success, error = tourney.rebuyPlayerRequest(game.id, 4)
        self.assertFalse(success)
        self.assertEqual(len(log_history.get_all()), 1)

        game.rebuy = old_rebuy
        success, error = tourney.rebuyPlayerRequest(game.id, 4)
        self.assertTrue(success, error)

        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        self.assertEqual(tourney.winners, [2, 1])

        looseMoney(4)
        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        tourney.removePlayer(1, 4)

        self.assertFalse(tourney.tourneyEnd(1))

        self.assertEqual(tourney.winners, [3,4,2,1])
        # We have just one winner and he wins the complete pot (4 * buy_in) + ( 6 * succesfull_rebuys)
        self.assertEqual(sum(tourney.prizes()), 50)

    def test3(self):
        # test2 should also pass with a different prizes object 
        self.tearDown()
        self._set_up({'prizes_specs':"algorithm"})
        self.test2()

    def testGetNextPositionWillReturnCorrectValue(self):
        game = self.tourney.games[0]
        def sortTmpWinner():
            return self.tourney.winners

        def removePlayer(serials):
            nid = self.tourney._incrementToNextWinnerPosition()
            for serial, money in serials:
                self.tourney.winners_dict[serial] = (nid,money)

        def reenterPlayer(serials):
            for serial in serials:
                del self.tourney.winners_dict[serial]

        self.assertEqual(sortTmpWinner(), [])
        removePlayer([(3, 200),(4, 200)])
        self.assertEqual(sortTmpWinner(), [4,3])

        reenterPlayer([3,4])
        removePlayer([(3, 300),(4, 200)])
        self.assertEqual(sortTmpWinner(), [3,4])

        removePlayer([(2, 200)])
        self.assertEqual(sortTmpWinner(), [2,3,4])
        reenterPlayer([3,4])
        self.assertEqual(sortTmpWinner(), [2])
        removePlayer([(1, 200)])
        self.assertEqual(sortTmpWinner(), [1,2])
    
    def testUnequalTables(self):
            
        tourney = PokerTournament(
            name = 'Test create',
            players_quota = 4,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = 2
        )
        
        def tourneySoftRemovePlayer(self, game_id, serial, now):
            game = self.id2game[game_id]
            game.removePlayer(serial)
            self.finallyRemovePlayer(serial, now)
        
        def gameCallbackTourneyEndTurn(game_id, game_type, *args):
            if game_type == 'end':
                tourney.endTurn(game_id)
                tourney.tourneyEnd(game_id)
                
        for serial in xrange(1,5): self.assertTrue(tourney.register(serial))
        
        for g in tourney.games: g.registerCallback(gameCallbackTourneyEndTurn)
        
        players = {}
        for g in tourney.games:
            for (serial,player) in g.serial2player.iteritems(): players[serial] = player
        
        for g in tourney.games:
            g.beginTurn(1)
        
        broke_info = {}
        # in all games, one of the two players is getting broke.
        for g in tourney.games:
            serial = g.getSerialInPosition()
            broke_player = players[serial]
            broke_info[serial] = g.id
            broke_player.money = 0
            g.fold(serial)
        
        self.assertEquals(len(tourney.games),1,'there should be only one game left (games: %s)' % tourney.id2game.keys())

    def testInactivePlayersAllInactive(self):
        arguments = {
            'dirs': [path.join(TESTS_PATH, '../conf')],
            'players_quota': 3,
            'seats_per_game': 3,
            'sit_n_go': 'y',
            'inactive_delay': 1
        }

        tourney = PokerTournament(**arguments)
        
        def gameCallbackTourneyEndTurn(game_id, game_type, *args):
            if game_type == 'end':
                tourney.endTurn(game_id)
                tourney.tourneyEnd(game_id)
                            
        serials = range(3)
        for s in serials: tourney.register(s)
        
        game = tourney.games[0]
        game.registerCallback(gameCallbackTourneyEndTurn)
        
        game.beginTurn(1)
        self.assertTrue(game.isFirstRound())
        
        tourney.start_time = 0
        
        game.autoPlayer(game.getSerialInPosition())
        game.autoPlayer(game.getSerialInPosition())
        
        self.assertTrue(tourney.state == TOURNAMENT_STATE_COMPLETE)
        
    def testInactivePlayersAllInactiveButOne(self):
        arguments = {
            'dirs': [path.join(TESTS_PATH, '../conf')],
            'players_quota': 3,
            'seats_per_game': 3,
            'sit_n_go': 'y',
            'inactive_delay': 1
        }

        tourney = PokerTournament(**arguments)
        
        def gameCallbackTourneyEndTurn(game_id, game_type, *args):
            if game_type == 'end':
                tourney.endTurn(game_id)
                tourney.tourneyEnd(game_id)
                            
        serials = range(3)
        for s in serials: tourney.register(s)
        
        game = tourney.games[0]
        game.registerCallback(gameCallbackTourneyEndTurn)
        
        game.beginTurn(1)
        self.assertTrue(game.isFirstRound())
        
        tourney.start_time = 0
        
        winner = game.getSerialInPosition()
        game.call(winner)
        game.autoPlayer(game.getSerialInPosition())
        game.autoPlayer(game.getSerialInPosition())
        
        self.assertTrue(tourney.state == TOURNAMENT_STATE_COMPLETE)
        self.assertEqual(tourney.winners[0], winner)
class TestRebuy(unittest.TestCase):

    def setUp(self):
        self.tourney = PokerTournament(name = 'Test create',
            players_quota = 4,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = 4)
        for serial in xrange(1,5):
            self.assertTrue(self.tourney.register(serial))

        self.game = self.tourney.games[0]
        self.players = self.game.playersAll()

    def tearDown(self):
        del self.tourney

    def test1_insertedWinnersAreCorrect(self):
        winners = [1,2,3,4]

        self.tourney.winners = winners
        self.assertEqual(self.tourney.winners, winners)

        self.tourney.winners = []
        self.assertEqual(self.tourney.winners, [])
    
    def test2(self):
        tourney = self.tourney
        game = self.game
        players = self.players

        def myremove_player(tournament, game_id, serial, now=False):
            if now:
                tournament.removePlayer(game_id, serial, now)

        tourney.callback_remove_player = myremove_player

        def setMoney(serial, money=0):
            for player in players:
                if player.serial != serial:
                    continue
                player.money = money
                if money == 0:
                    self.assertTrue(game.isBroke(serial))

        # Player got broke
        setMoney(1)
        self.assertEqual(tourney.winners, [])

        # Even removeBrokePlayers and endTurn doesn't remove him, 
        # because he has a chance for rebuy
        tourney.removeBrokePlayers(1)
        self.assertEqual(tourney.winners, [])

        # Player 2 gets broke, and chooses not to rebuy
        setMoney(2)
        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        tourney.removePlayer(1, 2)
        self.assertEqual(tourney.winners, [2])
        self.assertEqual(tourney.getRank(2), 4)

        # After Player 1 Timed out, he will be also removed
        # Note: this changes the rank for player 2
        tourney.removePlayer(1, 1)

        self.assertEqual(tourney.winners, [2, 1])
        self.assertEqual(tourney.getRank(2), 3)
        self.assertEqual(tourney.getRank(1), 4)

        # Player 3 get broke but rebuys a few times
        for _i in range(4):
            setMoney(3)

            tourney.removeBrokePlayers(1)
            tourney.tourneyEnd(1)
            self.assertEqual(tourney.winners, [2, 1])

            setMoney(3, 2000)
            tourney.reenterGame(1, 3)

            tourney.removeBrokePlayers(1)
            tourney.tourneyEnd(1)
            self.assertEqual(tourney.winners, [2, 1])

        setMoney(4)

        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        self.assertEqual(tourney.winners, [2, 1])

        setMoney(4, 2000)
        tourney.reenterGame(1, 4)

        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        self.assertEqual(tourney.winners, [2, 1])

        setMoney(4)
        tourney.removeBrokePlayers(1)
        tourney.tourneyEnd(1)
        tourney.removePlayer(1, 4)

        self.assertFalse(tourney.tourneyEnd(1))

        self.assertEqual(tourney.winners, [3,4,2,1])

    def testGetNextPositionWillReturnCorrectValue(self):
        def setMoney(ids, money=0):
            for player in self.players:
                if player.serial not in ids:
                    continue
                player.money = money
                if money == 0:
                    self.assertTrue(self.game.isBroke(player.serial))

        def sortTmpWinner():
            return [k for k,_v in sorted(self.tourney._winners_dict_tmp.iteritems() ,key=lambda (a,b):(b,a),reverse=True)]
            return self.tourney._winners_dict_tmp.keys()

        def removePlayer(serials):
            nid = self.tourney._incrementToNextWinnerPosition()
            for serial in serials:
                self.tourney._winners_dict_tmp[serial] = nid

        def reenterPlayer(serials):
            for serial in serials:
                del self.tourney._winners_dict_tmp[serial]

        self.assertEqual(sortTmpWinner(), [])
        removePlayer([3,4])
        self.assertEqual(sortTmpWinner(), [4,3])
        removePlayer([2])
        self.assertEqual(sortTmpWinner(), [2,4,3])
        reenterPlayer([3,4])
        self.assertEqual(sortTmpWinner(), [2])
        removePlayer([1])
        self.assertEqual(sortTmpWinner(), [1,2])
    
    def testUnequalTables(self):
            
        tourney = PokerTournament(
            name = 'Test create',
            players_quota = 4,
            dirs = [path.join(TESTS_PATH, '../conf')],
            seats_per_game = 2
        )
        
        def tourneySoftRemovePlayer(self, game_id, serial, now):
            game = self.id2game[game_id]
            game.removePlayer(serial)
            self.finallyRemovePlayer(serial, now)
        
        def gameCallbackTourneyEndTurn(game_id, game_type, *args):
            if game_type == 'end':
                tourney.endTurn(game_id)
                tourney.tourneyEnd(game_id)
                
        for serial in xrange(1,5): self.assertTrue(tourney.register(serial))
        
        for g in tourney.games: g.registerCallback(gameCallbackTourneyEndTurn)
        
        players = {}
        for g in tourney.games:
            for (serial,player) in g.serial2player.iteritems(): players[serial] = player
        
        for g in tourney.games:
            g.beginTurn(1)
        
        broke_info = {}
        # in all games, one of the two players is getting broke.
        for g in tourney.games:
            serial = g.getSerialInPosition()
            broke_player = players[serial]
            broke_info[serial] = g.id
            broke_player.money = 0
            g.fold(serial)
        
        self.assertEquals(len(tourney.games),1,'there should be only one game left (games: %s)' % tourney.id2game.keys())