def deferPacket(self, client): server = self.server_factory.instance self.failUnless(search_output('protocol established')) clear_all_messages() self.deferredPacket = defer.Deferred() server.sendPackets([self.deferredPacket, PacketAck()]) self.assertEquals(get_messages(), []) self.deferredPacket.callback(PacketPing()) self.assertEquals(get_messages(), []) def callbackDeferredPacket(client): pingFound = False ackFound = False msgs = get_messages() for msg in get_messages(): if msg == '(3 bytes) => type = PING(5)': self.failIf(pingFound or ackFound) pingFound = True elif msg == '(3 bytes) => type = ACK(4)': self.failUnless(pingFound) ackFound = True self.failUnless(ackFound and pingFound) d = client.connection_lost_deferred d.addCallback(callbackDeferredPacket) return d
def deferErrorPacket(self, client): server = self.server_factory.instance clear_all_messages() self.deferredPacket = defer.Deferred() server.sendPackets([self.deferredPacket, PacketAck()]) self.assertEquals(get_messages(), []) self.deferredPacket.errback("forced to fail") self.assertEquals(get_messages(), []) def callbackDeferredPacket(client): errFound = False ackFound = False msgs = get_messages() for msg in get_messages(): if msg == "(132 bytes) => type = ERROR(3) message = [Failure instance: Traceback (failure with no frames): <class 'twisted.python.failure.DefaultException'>: forced to fail\n], code = 0, other_type = ERROR": self.failIf(errFound or ackFound) errFound = True elif msg == '(3 bytes) => type = ACK(4)': self.failUnless(errFound) ackFound = True self.failUnless(ackFound and errFound) d = client.connection_lost_deferred d.addCallback(callbackDeferredPacket) return d
def testHandleConnection(self): """Testing _handleConnection""" clear_all_messages() # there is just a pass here in the implementation, there is really # nothing to be done to truly test it. self.assertEquals(self.u._handleConnection("..."), None) self.assertEquals(get_messages(), [])
def test03_pingWithNoneTimer(self): clear_all_messages() self.server_factory = FakeFactory(self) server = self.server_factory.buildProtocol('addr') server._ping_timer = None self.assertEquals(server.ping(), None) self.assertEqual(get_messages(), [])
def test02_pingWithoutTimer(self): clear_all_messages() self.server_factory = FakeFactory(self) server = self.server_factory.buildProtocol('addr') del server.__dict__['_ping_timer'] self.assertEquals(server.ping(), None) self.assertEqual(get_messages(), [])
def test08_connectionLostNonePingTimerNoAvatar(self): global processQueuesCount processQueuesCount = 0 global ignoreIncomingDataCount ignoreIncomingDataCount = 0 clear_all_messages() self.server_factory = FakeFactory(self) server = self.server_factory.buildProtocol('addr') server._processQueues = self.processQueuesCounter server.ignoreIncomingData = self.ignoreIncomingDataCounter server._ping_timer = None server._queues = [] server.avatar = None self.assertEquals(server.connectionLost("test08"), None) self.failIf(server.__dict__.has_key('avatar')) self.assertEquals(server._ping_timer, None) self.assertEquals(processQueuesCount, 0) self.assertEquals(ignoreIncomingDataCount, 1) self.assertEquals(self.server_factory.destroyedAvatars, []) self.assertEquals(get_messages(), [ 'connectionLost: reason = test08', 'connectionLost: reason = test08', 'client with protocol different rejected (need 002.000)' ])
def test09_connectionLostNoPingTimerWithAvatarButNoQueues(self): global processQueuesCount processQueuesCount = 0 global ignoreIncomingDataCount ignoreIncomingDataCount = 0 clear_all_messages() self.server_factory = FakeFactory(self) server = self.server_factory.buildProtocol('addr') server._protocol_ok = True server._processQueues = self.processQueuesCounter server.ignoreIncomingData = self.ignoreIncomingDataCounter del server._ping_timer server._queues = [] server.avatar = FakeAvatar() self.assertEquals(server.connectionLost("test09"), None) self.failIf(server.__dict__.has_key('avatar')) self.assertEquals(server._ping_timer, None) self.assertEquals(processQueuesCount, 0) self.assertEquals(ignoreIncomingDataCount, 1) self.assertEquals(len(self.server_factory.destroyedAvatars), 1) self.failUnless( isinstance(self.server_factory.destroyedAvatars[0], FakeAvatar)) self.assertEquals(get_messages(), ['connectionLost: reason = test09'])
def getNote(self, url, value): clear_all_messages() d = self.client.getNote(url, value) self.assertEquals(search_output("_buildNote"), True) self.assertEquals(search_output("getNote"), True) if "?" in url: check_url = url[:url.index("?")] else: check_url = url def validate(result): if isinstance(result, failure.Failure): raise result # I wonder, actually, if FakeCurrencyClient is supposed to # return a list of a list as RealCurrencyClient does in this # instance. I commented out: # note = result[0] # in favor of: note = result self.assertEqual(check_url, note[0]) self.assertEqual(40, len(note[2])) self.assertEqual(value, note[3]) return [result] d.addBoth(validate) return d
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 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 getCommitedNote(self, url, value): clear_all_messages() def checkCommitVerboseOutput(result): self.assertEquals(search_output("commit"), True) return result ret = CurrencyClientTestCase.getCommitedNote(self, url, value) ret.addCallback(checkCommitVerboseOutput) return ret
def dummyClientError(self, client): silence_all_messages() clear_all_messages() client.error("stupid dummy error test since client never calls") self.assertEquals( get_messages(), ["ERROR stupid dummy error test since client never calls"]) return (client, )
def test11_mainTests_raiseForceRelease(self): import Queue import time class MockException(Exception): pass def raiseForceRelease(name, timeout): raise MockException() def succeeded(result): self.failIf(True) def failed(result): self.failUnless(issinstance(result, MockException)) # FIXME: this callback never happens; it should, however. I # am not completely sure why; I assume it's because the # reactor.callFromThread() errback call in the main() doesn't # get executed before the reactor dies. OTOH, I don't fully # understand the thread/reactor interaction issues . If # someone can figure out and make sure this callback happens, # I'd appreciate it. d = defer.Deferred() d.addErrback(failed) d.addCallback(succeeded) class MockQueue: def __init__(qSelf): qSelf.count = 1 def qsize(qSelf): return qSelf.count def get(qSelf, timeout = 1): if qSelf.count > 0: qSelf.count = 0 return ("Mocky", raiseForceRelease, 10, d) else: raise Queue.Empty def empty(qSelf): return qSelf.count <= 0 def put(qSelf, val): pass class MockLock: def release(lSelf): raise MockException("MOCKY NO LOCK RELEASE") silence_all_messages() clear_all_messages() anotherLock = pokerlock.PokerLock(self.parameters) anotherLock.q = MockQueue() anotherLock.lock = MockLock() anotherLock.verbose = 6 anotherLock.start() time.sleep(2) self.assertEquals(anotherLock.running, True) for string in [ 'exception in function Traceback', 'release because exception', 'raise MockException("MOCKY NO LOCK RELEASE")']: self.failUnless(search_output(string), "missing '%s' in output" % string)
def lockFastTimeout(): self.failUnless(search_output('acquire'), "missing 'acquire' in output") pokerlock.PokerLock.acquire_sleep = 1 clear_all_messages() d = self.locker.acquire('lock01', 0) d.addCallback(lockTimeoutExpected_succeeded) d.addErrback(lockTimeoutExpected_failed) return d
def locker2(): clear_all_messages() self.locker2 = pokerlock.PokerLock(self.parameters) self.locker2.start() self.locker2.verbose = 6 d = self.locker2.acquire('lock01', 0) d.addCallback(locker2_succeeded) d.addErrback(locker2_failed) return d
def testConnectionLost(self): """Testing ConnectionLost""" silence_all_messages() clear_all_messages() self.u.established = 1 self.u.connectionLost("testing") self.assertEquals(search_output("connectionLost: reason = testing"), True) assert self.u.established == 0
def test07_breakNote(self): clear_all_messages() d = CurrencyClientTestCase.test07_breakNote(self) def checkOutput(result): self.assertEquals(search_output("breakNote vaues"), True) return True d.addCallback(checkOutput) return d
def getServerPacket(self, client): self.failUnless(search_output('protocol established')) clear_all_messages() def findBufferedAckPacket(client): self.failUnless(search_output("(3 bytes) => type = ACK(4)")) d = client.connection_lost_deferred d.addCallback(findBufferedAckPacket) return d
def test03_acquire_dead(self): self.locker.close() clear_all_messages() try: self.locker.acquire('lock01') problem = True except Exception, e: problem = False self.assertEqual(e[0], pokerlock.PokerLock.DEAD) self.failUnless(search_output('acquire'), "missing 'acquire' in output")
def testConnectionLostWithProtocolOk(self): """Testing ConnectionLostWithProtocolOk""" silence_all_messages() clear_all_messages() self.u.established = 1 self.u._protocol_ok = True self.u.connectionLost("another") self.assertEquals(search_output("connectionLost: reason = another"), True) assert self.u.established == 0
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 locker2_failed(result): for string in [ '__acquire lock01', 'acquired', 'exception in function', 'release because exception', 'loop, queue size']: if not search_output(string): print get_messages() self.failUnless(search_output(string), "missing '%s' in output" % string) clear_all_messages() self.locker.release('lock01') self.assertTrue(isinstance(result, failure.Failure)) self.assertEqual(result.value[0], pokerlock.PokerLock.TIMED_OUT) self.locker2.close()
def test07_mainTests_stopped(self): clear_all_messages() self.locker.stopping() self.failUnless(search_output("stopping"), "missing 'stopping' in output") clear_all_messages() d = defer.Deferred() def checker(val): self.failIf(self.locker.running) self.failUnless(search_output("stopped"), "missing 'stopped' in output") reactor.callLater(pokerlock.PokerLock.acquire_sleep*3, lambda: d.callback(True)) return d
def bufferPackets(client): def checkOutput(client): msgs = get_messages() self.assertEquals(msgs[0], 'sendPacket(0) type = ACK(4) ') return (client, ) client.bufferized_packets = [PacketAck()] clear_all_messages() ccd = client.connection_lost_deferred ccd.addCallback(checkOutput) return ccd
def checkNote(result): clear_all_messages() note_to_check = result d = self.client.checkNote(note_to_check) self.assertEquals(search_output("checkNote"), True) def validate(result): if isinstance(result, failure.Failure): raise result checked_note = result self.assertEqual(note_to_check, checked_note) return result d.addBoth(validate) return d
def test07_pingWithInactiveTimerWithUser(self): clear_all_messages() self.server_factory = FakeFactory(self) server = self.server_factory.buildProtocol('addr') pt = MockPingTimer() server._ping_timer = pt self.assertEquals(server.ping(), None) self.assertEquals(server._ping_timer, None) self.assertEquals(pt.resetValues, []) self.assertEquals(pt.cancelCount, 0) self.assertEquals(server.transport.loseConnectionCount, 1) self.assertEqual(get_messages(), ['ping: timeout Mr.Fakey/-1'])
def test10_mainTests_notRunningForCallback(self): import Queue import time global myLock def setNotRunning(name, timeout): global myLock myLock.running = False d = defer.Deferred() def succeeded(result): self.failIf(True) def failed(result): self.failIf(True) d.addErrback(failed) d.addCallback(succeeded) class MockQueue: def __init__(qSelf): qSelf.count = 1 def qsize(qSelf): return qSelf.count def get(qSelf, timeout = 1): if qSelf.count > 0: qSelf.count = 0 return ("Mocky", setNotRunning, 10, d) else: raise Queue.Empty def empty(qSelf): return qSelf.count <= 0 def put(qSelf, val): pass class MockLock: def __init__(lSelf): lSelf.calledReleaseCount = 0 def release(lSelf): lSelf.calledReleaseCount += 1 silence_all_messages() clear_all_messages() anotherLock = pokerlock.PokerLock(self.parameters) anotherLock.q = MockQueue() anotherLock.lock = MockLock() anotherLock.verbose = 6 myLock = anotherLock anotherLock.start() time.sleep(2) self.failUnless(search_output('release because not running'), "missing 'release because not running' in output") self.assertEquals(anotherLock.running, False) self.assertEquals(anotherLock.lock.calledReleaseCount, 1)
def test02_pingWithNoneTimer(self): def myDataWrite(clientSelf): failIf(True) clear_all_messages() client = pokernetwork.client.UGAMEClientProtocol() client.dataWrite = myDataWrite client._ping_timer = None client.factory = None self.assertEquals(client.ping(), None) self.assertEqual(get_messages(), [])
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 test01_simple(self): clear_all_messages() d = self.locker.acquire('lock01') def validate(result): if isinstance(result, failure.Failure): raise result for string in ['__acquire lock01', '__acquire got MySQL lock', 'acquired' ]: self.failUnless(search_output(string), "missing '%s' in output" % string) self.assertEqual("lock01", result) self.locker.release('lock01') return result d.addBoth(validate) return d
def test06_pingWithInactiveTimerNoUser(self): clear_all_messages() self.server_factory = FakeFactory(self) server = self.server_factory.buildProtocol('addr') pt = MockPingTimer() server._ping_timer = pt del server.__dict__['user'] self.assertEquals(server.ping(), None) self.assertEquals(server._ping_timer, None) self.assertEquals(pt.resetValues, []) self.assertEquals(pt.cancelCount, 0) self.assertEquals(server.transport.loseConnectionCount, 1) self.assertEqual(get_messages(), [])
def testHandleData(self): """Testing handleData""" fakeProcessQueuesDeferred = self.fakeProcessQueuesDeferred() self.u._expected_len = 3 self.u._packet.append("\x00\x00\x03") self.u._packet_len = len("\x00\x00\x03") clear_all_messages() self.u.handleData() self.assertEquals(get_messages(), ['(3 bytes) => type = NONE(0)']) self.u._poll = False self.u._packet.append("\x00\x00\x03") self.u._packet_len = len("\x00\x00\x03") clear_all_messages() self.u.handleData() self.assertEquals(get_messages(), ['(3 bytes) => type = NONE(0)']) self.u._packet.append("\xff\x00\x03") self.u._packet_len = len("\xff\x00\x03") clear_all_messages() self.u.handleData() self.assertEquals(get_messages(), [': unknown message received (id 255, length 3)\n', "known types are {0: 'NONE', 1: 'STRING', 2: 'INT', 3: 'ERROR', 4: 'ACK', 5: 'PING', 6: 'SERIAL', 7: 'QUIT', 8: 'AUTH_OK', 9: 'AUTH_REFUSED', 10: 'LOGIN', 11: 'AUTH_REQUEST', 12: 'LIST', 13: 'LOGOUT', 14: 'BOOTSTRAP', 15: 'PROTOCOL_ERROR', 16: 'MESSAGE', 50: 'POKER_SEATS', 51: 'POKER_ID', 52: 'POKER_MESSAGE', 53: 'ERROR', 54: 'POKER_POSITION', 55: 'POKER_INT', 56: 'POKER_BET', 57: 'POKER_FOLD', 58: 'POKER_STATE', 59: 'POKER_WIN', 60: 'POKER_CARDS', 61: 'POKER_PLAYER_CARDS', 62: 'POKER_BOARD_CARDS', 63: 'POKER_CHIPS', 64: 'POKER_PLAYER_CHIPS', 65: 'POKER_CHECK', 66: 'POKER_START', 67: 'POKER_IN_GAME', 68: 'POKER_CALL', 69: 'POKER_RAISE', 70: 'POKER_DEALER', 71: 'POKER_TABLE_JOIN', 72: 'POKER_TABLE_SELECT', 73: 'POKER_TABLE', 74: 'POKER_TABLE_LIST', 75: 'POKER_SIT', 76: 'POKER_TABLE_DESTROY', 77: 'POKER_TIMEOUT_WARNING', 78: 'POKER_TIMEOUT_NOTICE', 79: 'POKER_SEAT', 80: 'POKER_TABLE_MOVE', 81: 'POKER_PLAYER_LEAVE', 82: 'POKER_SIT_OUT', 83: 'POKER_TABLE_QUIT', 84: 'POKER_BUY_IN', 85: 'POKER_REBUY', 86: 'POKER_CHAT', 87: 'POKER_PLAYER_INFO', 88: 'POKER_PLAYER_ARRIVE', 89: 'POKER_HAND_SELECT', 90: 'POKER_HAND_LIST', 91: 'POKER_HAND_SELECT_ALL', 92: 'POKER_USER_INFO', 93: 'POKER_GET_USER_INFO', 94: 'POKER_ANTE', 95: 'POKER_BLIND', 96: 'POKER_WAIT_BIG_BLIND', 97: 'POKER_AUTO_BLIND_ANTE', 98: 'POKER_NOAUTO_BLIND_ANTE', 99: 'POKER_CANCELED', 100: 'POKER_BLIND_REQUEST', 101: 'POKER_ANTE_REQUEST', 102: 'POKER_AUTO_FOLD', 103: 'POKER_WAIT_FOR', 104: 'POKER_STREAM_MODE', 105: 'POKER_BATCH_MODE', 106: 'POKER_LOOK_CARDS', 107: 'POKER_TABLE_REQUEST_PLAYERS_LIST', 108: 'POKER_PLAYERS_LIST', 109: 'POKER_PERSONAL_INFO', 110: 'POKER_GET_PERSONAL_INFO', 111: 'POKER_TOURNEY_SELECT', 112: 'POKER_TOURNEY', 113: 'POKER_TOURNEY_INFO', 114: 'POKER_TOURNEY_LIST', 115: 'POKER_TOURNEY_REQUEST_PLAYERS_LIST', 116: 'POKER_TOURNEY_REGISTER', 117: 'POKER_TOURNEY_UNREGISTER', 118: 'POKER_TOURNEY_PLAYERS_LIST', 119: 'POKER_HAND_HISTORY', 120: 'POKER_SET_ACCOUNT', 121: 'POKER_CREATE_ACCOUNT', 122: 'POKER_PLAYER_SELF', 123: 'POKER_GET_PLAYER_INFO', 124: 'POKER_ROLES', 125: 'POKER_SET_ROLE', 126: 'POKER_READY_TO_PLAY', 127: 'POKER_PROCESSING_HAND', 128: 'POKER_MUCK_REQUEST', 129: 'POKER_AUTO_MUCK', 130: 'POKER_MUCK_ACCEPT', 131: 'POKER_MUCK_DENY', 132: 'POKER_CASH_IN', 133: 'POKER_CASH_OUT', 134: 'POKER_CASH_OUT_COMMIT', 135: 'POKER_CASH_QUERY', 136: 'POKER_RAKE', 137: 'POKER_TOURNEY_RANK', 138: 'POKER_PLAYER_IMAGE', 139: 'POKER_GET_PLAYER_IMAGE', 140: 'POKER_HAND_REPLAY', 141: 'POKER_GAME_MESSAGE', 142: 'POKER_EXPLAIN', 143: 'POKER_STATS_QUERY', 144: 'POKER_STATS', 145: 'POKER_BUY_IN_LIMITS', 146: 'POKER_MONITOR', 147: 'POKER_MONITOR_EVENT', 148: 'POKER_GET_TOURNEY_MANAGER', 149: 'POKER_TOURNEY_MANAGER', 151: 'POKER_GET_PLAYER_PLACES', 152: 'POKER_PLAYER_PLACES', 153: 'POKER_SET_LOCALE', 154: 'POKER_TABLE_TOURNEY_BREAK_BEGIN', 155: 'POKER_TABLE_TOURNEY_BREAK_DONE', 156: 'POKER_TOURNEY_START', 161: 'POKER_PLAYER_STATS', 164: 'POKER_TOURNEY_INFO', 165: 'POKER_TABLE_PICKER', 166: 'POKER_CREATE_TOURNEY', 167: 'POKER_LONG_POLL', 168: 'POKER_LONG_POLL_RETURN', 170: 'POKER_BEST_CARDS', 171: 'POKER_POT_CHIPS', 172: 'POKER_CLIENT_ACTION', 173: 'POKER_BET_LIMIT', 174: 'POKER_SIT_REQUEST', 175: 'POKER_PLAYER_NO_CARDS', 176: 'POKER_CHIPS_PLAYER2BET', 177: 'POKER_CHIPS_BET2POT', 178: 'POKER_CHIPS_POT2PLAYER', 179: 'POKER_CHIPS_POT_MERGE', 180: 'POKER_CHIPS_POT_RESET', 181: 'POKER_CHIPS_BET2PLAYER', 182: 'POKER_END_ROUND', 183: 'POKER_DISPLAY_NODE', 184: 'POKER_DEAL_CARDS', 185: 'POKER_CHAT_HISTORY', 186: 'POKER_DISPLAY_CARD', 187: 'POKER_SELF_IN_POSITION', 188: 'POKER_SELF_LOST_POSITION', 189: 'POKER_HIGHEST_BET_INCREASE', 190: 'POKER_PLAYER_WIN', 191: 'POKER_ANIMATION_PLAYER_NOISE', 192: 'POKER_ANIMATION_PLAYER_FOLD', 193: 'POKER_ANIMATION_PLAYER_BET', 194: 'POKER_ANIMATION_PLAYER_CHIPS', 195: 'POKER_ANIMATION_DEALER_CHANGE', 196: 'POKER_ANIMATION_DEALER_BUTTON', 197: 'POKER_BEGIN_ROUND', 198: 'POKER_CURRENT_GAMES', 199: 'POKER_END_ROUND_LAST', 200: 'POKER_PYTHON_ANIMATION', 201: 'POKER_SIT_OUT_NEXT_TURN', 202: 'POKER_RENDERER_STATE', 203: 'POKER_CHAT_WORD', 204: 'POKER_SHOWDOWN', 205: 'POKER_CLIENT_PLAYER_CHIPS', 206: 'POKER_INTERFACE_COMMAND', 207: 'POKER_PLAYER_ME_LOOK_CARDS', 208: 'POKER_PLAYER_ME_IN_FIRST_PERSON', 209: 'POKER_ALLIN_SHOWDOWN', 210: 'POKER_PLAYER_HAND_STRENGTH'} "]) # trying with wrong packet self.u._packet.append("\xff\x00\x00") self.u._packet_len = len("\xff\x00\x00") clear_all_messages() self.u.handleData() # FIXME (maybe): I am not completely sure it's correct that we # should get absolutely no output when we send the "wrong packet". # I've asked Loic to take a look. self.assertEquals(get_messages(), []) return fakeProcessQueuesDeferred
def test05_many(self): self.locker.message = lambda self, string: True self.locker.verbose = 0 # Runs too slow if you have messages on dl = [] def show(x): self.locker.release('lock01') pokerlock.PokerLock.acquire_sleep = 0.01 for i in xrange(1,300): d = self.locker.acquire('lock01', 3) d.addBoth(show) dl.append(d) clear_all_messages() return defer.DeferredList(dl)
def mergeNotes(note): self.assertEquals(2, len(notes)) clear_all_messages() d = self.client.mergeNotes(*notes) self.assertEquals(search_output("mergeNotes"), True) def validate(result): if isinstance(result, failure.Failure): raise result self.assertEqual(1, len(result)) note = result[0] self.assertEqual("http://fake/", note[0]) self.assertEqual(3, note[1]) self.assertEqual(40, len(note[2])) self.assertEqual(200, note[3]) return result d.addBoth(validate) return d
def test05_authWhenDoubleEntry(self): """test05_authWhenDoubleEntry Tests case in fallback authentication where more than one entry exists. """ cursor = self.db.cursor() for ii in [1, 2]: cursor.execute( "INSERT INTO %s (username, password, privilege) values ('%s', '%s', %i)" % (self.parameters["table"], "doyle_brunson", "foo", User.REGULAR) ) 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(), [])
def test08_mainTests_emptyQueue(self): """test08_mainTests_emptyQueue This test creates a dummy PokerLock.__init__() so that a MockQueue can be used that force-raises a Queue.Empty() exception, which is caught by the running loop in the lock and ends it.""" import Queue from pokernetwork.pokerlock import PokerLock import threading class MockQueue: def __init__(qSelf): qSelf.qSizeCallCount = 0 qSelf.getCallCount = 0 def qsize(qSelf): qSelf.qSizeCallCount += 1 return 1 def get(qSelf, timeout = 1): qSelf.getCallCount += 1 raise Queue.Empty("MOCK") def empty(qSelf): return False def put(qSelf, val): pass myMockQueue = MockQueue() class MockInitLock(PokerLock): def __init__(self, parameters): self.verbose = 6 self.q = myMockQueue self.lock = threading.Lock() self.db = None self.running = True self.connect(parameters) threading.Thread.__init__(self, target = self.main) clear_all_messages() mockLocker = MockInitLock(self.parameters) mockLocker.start() mockLocker.close() self.failUnless(search_output("timeout"), "output does not contain 'timeout'") self.failUnless(search_output("loop"), "output does not contain 'loop'") self.failUnless(myMockQueue.qSizeCallCount > 0, "MockQueue.qSize() should be called at least once.") self.failUnless(myMockQueue.getCallCount > 0, "MockQueue.get() should be called at least once.")
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 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 test02_wait(self): def locker2_succeeded(result): self.locker.release('lock01') self.fail("locker2 succeeded with result = %s : should have failed with timeout") self.locker2.close() def locker2_failed(result): for string in [ '__acquire lock01', 'acquired', 'exception in function', 'release because exception', 'loop, queue size']: if not search_output(string): print get_messages() self.failUnless(search_output(string), "missing '%s' in output" % string) clear_all_messages() self.locker.release('lock01') self.assertTrue(isinstance(result, failure.Failure)) self.assertEqual(result.value[0], pokerlock.PokerLock.TIMED_OUT) self.locker2.close() def locker2(): clear_all_messages() self.locker2 = pokerlock.PokerLock(self.parameters) self.locker2.start() self.locker2.verbose = 6 d = self.locker2.acquire('lock01', 0) d.addCallback(locker2_succeeded) d.addErrback(locker2_failed) return d def validate(result): if isinstance(result, failure.Failure): raise result for string in ['__acquire lock01', 'acquired', '__acquire got MySQL lock']: if not search_output(string): print get_messages() self.failUnless(search_output(string), "%s not found in string" % string) self.assertEqual("lock01", result) return locker2() clear_all_messages() d = self.locker.acquire('lock01', 0) d.addBoth(validate) return d
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 %s (username, password, privilege) values ('%s', '%s', %i)" % (self.parameters["table"], "dan_harrington", "bar", User.REGULAR) ) cursor.close() auth = pokerauth.get_auth_instance(self.db, self.settings) clear_all_messages() self.assertEquals(auth.auth("dan_harrington", "bar"), (("dan_harrington", "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(), [])
def testCoverDataWrite(self): """Testing data write""" clear_all_messages() tot = protocol.UGAMEProtocol._stats_write global calledWrite calledWrite = 0 myData = "testing data" def mockTransportWrite(data): global calledWrite self.assertEquals(data, myData) calledWrite += 1 self.u.transport.write = mockTransportWrite self.u.dataWrite(myData) self.assertEquals(tot + len(myData), protocol.UGAMEProtocol._stats_write) self.assertEquals(calledWrite, 1) self.assertEquals(get_messages(), [])
def test04_changeNote(self): d = self.getCommitedNote('http://fake/', 100) clear_all_messages() def changeNote(result): class FakeNoteToChange: def copy(self): return [8, 0, ''] d = self.client.changeNote(FakeNoteToChange()) def validate(result): if isinstance(result, failure.Failure): raise result self.assertEqual(result[0], 8) self.assertEqual(result[1], 2) self.assertEqual(40, len(result[2])) self.assertEquals(search_output("changeNote"), True) return result d.addBoth(validate) return d d.addCallback(changeNote) return d
def validate(result): if isinstance(result, failure.Failure): raise result self.assertEqual("lock01", result) for string in ['__acquire lock01', 'acquired', '__acquire got MySQL lock']: if not search_output(string): print get_messages() self.failUnless(search_output(string), "%s not found in output" % string) clear_all_messages() self.locker.release("lock01") self.failUnless(search_output('release lock01'), "missing 'release lock01' in output") clear_all_messages() try: self.locker.release("lock01") problem = True except Exception, e: problem = False self.assertEqual(e[0], pokerlock.PokerLock.RELEASE) self.failUnless(search_output('release lock01'), "missing 'release lock01' in output")
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"])