def getNote(self, url, value): log_history.reset() d = self.client.getNote(url, value) self.assertEquals(log_history.search("_buildNote"), True) self.assertEquals(log_history.search("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 getNote(self, url, value): log_history.reset() d = self.client.getNote(url, value) self.assertEquals(log_history.search("_buildNote"), True) self.assertEquals(log_history.search("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 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 log_history.search(string): print log_history.get_all() self.failUnless(log_history.search(string), "missing '%s' in output" % string) return lockFastTimeout()
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 import threading from pokernetwork.pokerlock import PokerLock from pokernetwork import log as network_log 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() log = network_log.getChild('pokerlock') class MockInitLock(PokerLock): def __init__(self, parameters): self.log = log.getChild(self.__class__.__name__) self.q = myMockQueue self.lock = threading.Lock() self.db = None self.running = True self.connect(parameters) threading.Thread.__init__(self, target=self.main) log_history.reset()() mockLocker = MockInitLock(self.parameters) mockLocker.start() mockLocker.close() self.failUnless(log_history.search("timeout"), "output does not contain 'timeout'") self.failUnless(log_history.search("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 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 log_history.search(string): print log_history.get_all() self.failUnless(log_history.search(string), "missing '%s' in output" % string) return lockFastTimeout()
def deadServerTransport(self, client): server = self.server_factory.instance saveMyTransport = server.transport server.transport = None server.sendPackets([PacketPing()]) self.assertEquals(len(server.bufferized_packets), 1) self.assertEquals(server.bufferized_packets[0].type, PACKET_PING) self.assertTrue(log_history.search("bufferized")) self.assertTrue(log_history.search("no usuable transport")) server.transport = saveMyTransport return client.connection_lost_deferred
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 import threading from pokernetwork.pokerlock import PokerLock from pokernetwork import log as network_log 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() log = network_log.getChild('pokerlock') class MockInitLock(PokerLock): def __init__(self, parameters): self.log = log.getChild(self.__class__.__name__) self.q = myMockQueue self.lock = threading.Lock() self.db = None self.running = True self.connect(parameters) threading.Thread.__init__(self, target = self.main) log_history.reset()() mockLocker = MockInitLock(self.parameters) mockLocker.start() mockLocker.close() self.failUnless(log_history.search("timeout"), "output does not contain 'timeout'") self.failUnless(log_history.search("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 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(log_history.search("changeNote"), True) return result
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 log_history.reset()() anotherLock = pokerlock.PokerLock(self.parameters) anotherLock.q = MockQueue() anotherLock.lock = MockLock() myLock = anotherLock anotherLock.start() time.sleep(2) self.failUnless(log_history.search('release because not running'), "missing 'release because not running' in output") self.assertEquals(anotherLock.running, False) self.assertEquals(anotherLock.lock.calledReleaseCount, 1)
def validate(result): if isinstance(result, failure.Failure): raise result for string in ['__acquire lock01', '__acquire got MySQL lock', 'acquired' ]: self.failUnless(log_history.search(string), "missing '%s' in output" % string) self.assertEqual("lock01", result) self.locker.release('lock01') return result
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 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") log_history.reset()() anotherLock = pokerlock.PokerLock(self.parameters) anotherLock.q = MockQueue() anotherLock.lock = MockLock() anotherLock.start() time.sleep(2) self.assertEquals(anotherLock.running, True) for string in [ 'exception in function', 'failed to release lock after exception', 'raise MockException("MOCKY NO LOCK RELEASE")' ]: self.failUnless(log_history.search(string), "missing '%s' in output" % string)
def lockFastTimeout(): self.failUnless(log_history.search('acquire'), "missing 'acquire' in output") pokerlock.PokerLock.acquire_sleep = 1 log_history.reset()() d = self.locker.acquire('lock01', 0) d.addCallback(lockTimeoutExpected_succeeded) d.addErrback(lockTimeoutExpected_failed) return d
def getServerPacket(self, client): self.failUnless(log_history.search('protocol established')) log_history.reset() def findBufferedAckPacket(client): self.failUnless(log_history.search("ACK type = 4 length = 3")) d = client.connection_lost_deferred d.addCallback(findBufferedAckPacket) return d
def validate(result): if isinstance(result, failure.Failure): raise result for string in [ '__acquire lock01', '__acquire got MySQL lock', 'acquired' ]: self.failUnless(log_history.search(string), "missing '%s' in output" % string) self.assertEqual("lock01", result) self.locker.release('lock01') return result
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 test03_acquire_dead(self): self.locker.close() log_history.reset()() try: self.locker.acquire('lock01') problem = True except Exception, e: problem = False self.assertEqual(e[0], pokerlock.PokerLock.DEAD) self.failUnless(log_history.search('acquire'), "missing 'acquire' in output")
def test07_mainTests_stopped(self): log_history.reset()() self.locker.stopping() self.failUnless(log_history.search("stopping"), "missing 'stopping' in output") log_history.reset()() d = defer.Deferred() def checker(val): self.failIf(self.locker.running) self.failUnless(log_history.search("stopped"), "missing 'stopped' in output") reactor.callLater(pokerlock.PokerLock.acquire_sleep*3, lambda: d.callback(True)) return d
def locker2_failed(result): needed = [ '__acquire lock01', 'acquired', 'exception in function', 'loop, queue size' ] for s in needed: self.assertTrue(log_history.search(s), "missing '%s' in output (got %s)" % (s,log_history.get_all())) log_history.reset()() self.locker.release('lock01') self.assertTrue(isinstance(result, failure.Failure)) self.assertEqual(result.value[0], pokerlock.PokerLock.TIMED_OUT) self.locker2.close()
def validate(result): if isinstance(result, failure.Failure): raise result needed = [ '__acquire lock01', 'acquired', '__acquire got MySQL lock' ] for s in needed: self.assertTrue(log_history.search(s), "missing '%s' in output (got %s)" % (s,log_history.get_all())) self.assertEqual("lock01", result) return locker2()
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 log_history.search(string): print log_history.get_all() self.failUnless(log_history.search(string), "%s not found in output" % string) log_history.reset()() self.locker.release("lock01") self.failUnless(log_history.search('release lock01'), "missing 'release lock01' in output") log_history.reset()() try: self.locker.release("lock01") problem = True except Exception, e: problem = False self.assertEqual(e[0], pokerlock.PokerLock.RELEASE) self.failUnless(log_history.search('release lock01'), "missing 'release lock01' in output")
def validate(result): if isinstance(result, failure.Failure): raise result needed = [ '__acquire lock01', 'acquired', '__acquire got MySQL lock' ] for s in needed: self.assertTrue( log_history.search(s), "missing '%s' in output (got %s)" % (s, log_history.get_all())) self.assertEqual("lock01", result) return locker2()
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 log_history.search(string): print log_history.get_all() self.failUnless(log_history.search(string), "%s not found in output" % string) log_history.reset()() self.locker.release("lock01") self.failUnless(log_history.search('release lock01'), "missing 'release lock01' in output") log_history.reset()() try: self.locker.release("lock01") problem = True except Exception, e: problem = False self.assertEqual(e[0], pokerlock.PokerLock.RELEASE) self.failUnless(log_history.search('release lock01'), "missing 'release lock01' in output")
def checkNote(result): log_history.reset() note_to_check = result d = self.client.checkNote(note_to_check) self.assertEquals(log_history.search("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 log_history.reset()() anotherLock = pokerlock.PokerLock(self.parameters) anotherLock.q = MockQueue() anotherLock.lock = MockLock() myLock = anotherLock anotherLock.start() time.sleep(2) self.failUnless(log_history.search('release because not running'), "missing 'release because not running' in output") self.assertEquals(anotherLock.running, False) self.assertEquals(anotherLock.lock.calledReleaseCount, 1)
def locker2_failed(result): needed = [ '__acquire lock01', 'acquired', 'exception in function', 'loop, queue size' ] for s in needed: self.assertTrue( log_history.search(s), "missing '%s' in output (got %s)" % (s, log_history.get_all())) log_history.reset()() 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): log_history.reset()() self.locker.stopping() self.failUnless(log_history.search("stopping"), "missing 'stopping' in output") log_history.reset()() d = defer.Deferred() def checker(val): self.failIf(self.locker.running) self.failUnless(log_history.search("stopped"), "missing 'stopped' in output") reactor.callLater(pokerlock.PokerLock.acquire_sleep * 3, lambda: d.callback(True)) return d
def deferPacket(self, client): server = self.server_factory.instance self.failUnless(log_history.search('protocol established')) log_history.reset() self.deferredPacket = defer.Deferred() server.sendPackets([ self.deferredPacket, PacketAck()]) self.assertEquals(log_history.get_all(), []) self.deferredPacket.callback(PacketPing()) self.assertEquals(log_history.get_all(), []) def callbackDeferredPacket(client): self.assertTrue(log_history.search('ACK type = 4 length = 3')) d = client.connection_lost_deferred d.addCallback(callbackDeferredPacket) return d
def mergeNotes(note): self.assertEquals(2, len(notes)) log_history.reset() d = self.client.mergeNotes(*notes) self.assertEquals(log_history.search("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
class PokerServerRunCoverageTestCase(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.tmpdir = tempfile.mkdtemp() self.saveArgv = None self.saveStdout, sys.stdout = sys.stdout, StringIO() # ------------------------------------------------------------------------- def tearDown(self): shutil.rmtree(self.tmpdir) if self.saveArgv: sys.argv = self.saveArgv sys.stdout = self.saveStdout # ------------------------------------------------------------------------- def setArgv(self, newArgv): self.saveArgv = sys.argv sys.argv = newArgv # ------------------------------------------------------------------------- def test00_missingConfigFileGivenOnCLI(self): doesNotExistFile = os.path.join(self.tmpdir, "thisdoesnotexist.xml") caughtIt = False try: sys.argv = [doesNotExistFile] pokerServerRun() self.fail("previous line should have thrown exception") except exceptions.SystemExit, e: self.assertEquals(e.__str__(), "1") caughtIt = True self.failUnless(caughtIt, "Should have caught an Exception") self.assertTrue(log_history.search("reactor already installed"))
def lockTimeoutExpected_failed(result): self.assertTrue(isinstance(result, failure.Failure)) self.assertEqual(result.value[0], pokerlock.PokerLock.TIMED_OUT) self.failUnless(log_history.search('__acquire TIMED OUT'), "missing '__acquire TIMED OUT' in output")
def checkCommitVerboseOutput(result): self.assertEquals(log_history.search("commit"), True) return result
def checker(val): self.failIf(self.locker.running) self.failUnless(log_history.search("stopped"), "missing 'stopped' in output")
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") log_history.reset()() anotherLock = pokerlock.PokerLock(self.parameters) anotherLock.q = MockQueue() anotherLock.lock = MockLock() anotherLock.start() time.sleep(2) self.assertEquals(anotherLock.running, True) for string in [ 'exception in function', 'failed to release lock after exception', 'raise MockException("MOCKY NO LOCK RELEASE")' ]: self.failUnless(log_history.search(string), "missing '%s' in output" % string)
def serverPingTimeout(val): self.assertTrue(log_history.search("sendPacket: PacketQuit(7)"))
def findBufferedAckPacket(client): self.failUnless(log_history.search("PacketAck(4)"))
saveReactor = pollreactor.install pollreactor.install = reactorFake reactorModulesSave = sys.modules['twisted.internet.reactor'] del sys.modules['twisted.internet.reactor'] try: pokerServerRun() self.fail("previous line should have thrown exception") except exceptions.SystemExit, e: self.assertEquals(e.__str__(), "1") caughtIt = True self.failUnless(caughtIt, "Should have caught an Exception") self.assertTrue(log_history.search("installing epoll reactor")) self.failIf(reactorCalled, "epoll reactor should have been installed") if saveSystem: platform.system = saveSystem pollreactor.install = saveReactor sys.modules['twisted.internet.reactor'] = reactorModulesSave # ---------------------------------------------------------------- def GetTestSuite(): loader = runner.TestLoader() # loader.methodPrefix = "test_trynow"
def serverPingTimeout(val): self.assertTrue(log_history.search("sendPacket: QUIT type = 7 length = 3"))
reactorCalled = True saveReactor = pollreactor.install pollreactor.install = reactorFake reactorModulesSave = sys.modules['twisted.internet.reactor'] del sys.modules['twisted.internet.reactor'] try: pokerServerRun() self.fail("previous line should have thrown exception") except exceptions.SystemExit, e: self.assertEquals(e.__str__(), "1") caughtIt = True self.failUnless(caughtIt, "Should have caught an Exception") self.assertTrue(log_history.search("installing epoll reactor")) self.failIf(reactorCalled, "epoll reactor should have been installed") if saveSystem: platform.system = saveSystem pollreactor.install = saveReactor sys.modules['twisted.internet.reactor'] = reactorModulesSave # ---------------------------------------------------------------- def GetTestSuite(): loader = runner.TestLoader() # loader.methodPrefix = "test_trynow" suite = loader.suiteFactory() suite.addTest(loader.loadClass(PokerServerMakeServiceManholeTestCase)) suite.addTest(loader.loadClass(PokerServerMakeServiceCoverageTestCase))
def callbackDeferredPacket(client): self.assertTrue(log_history.search('ACK type = 4 length = 3'))
def sendLostConnectionPacket(val): client.sendPacket(PacketPing()) self.assertTrue(log_history.search("bufferized")) self.assertEqual(len(client.bufferized_packets), 1) self.assertEqual(client.bufferized_packets[0].type, PACKET_PING)
def checkOutput(result): self.assertEquals(log_history.search("breakNote values"), True) return True
def findBufferedAckPacket(client): self.failUnless(log_history.search("ACK type = 4 length = 3"))