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 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 validate(result): if isinstance(result, failure.Failure): raise result self.assertEqual("lock01", result) for string in ['__acquire lock01', '__acquire got MySQL lock', 'acquired' ]: if not search_output(string): print get_messages() self.failUnless(search_output(string), "missing '%s' in output" % string) return lockFastTimeout()
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()
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 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 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
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
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 test01_invalidProtocol(self): self.server_factory = FakeFactory(self) silence_all_messages() self.server_factory.buildProtocol('addr').dataReceived( "invalid protocol\n") if verbose < 0: # can only grep output when output is redirected self.assertEqual( search_output('client with protocol UNKNOWN rejected'), True)
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 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 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 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 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 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 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 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 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 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 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 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 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 findBufferedAckPacket(client): self.failUnless(search_output("(3 bytes) => type = ACK(4)"))
def serverPingTimeout(val): self.assertEqual(search_output("ping: timeout Mr.Fakey/-1"), True)
def checker(val): self.failIf(self.locker.running) self.failUnless(search_output("stopped"), "missing 'stopped' in output")
def checkCommitVerboseOutput(result): self.assertEquals(search_output("commit"), True) return result
def checkOutput(result): self.assertEquals(search_output("breakNote vaues"), True) return True
def lockTimeoutExpected_failed(result): self.assertTrue(isinstance(result, failure.Failure)) self.assertEqual(result.value[0], pokerlock.PokerLock.TIMED_OUT) self.failUnless(search_output('__acquire TIMED OUT'), "missing '__acquire TIMED OUT' in output")