def testDistrib(self): # site1 is the publisher r1 = resource.Resource() r1.putChild("there", static.Data("root", "text/plain")) site1 = server.Site(r1) f1 = pb.PBServerFactory(distrib.ResourcePublisher(site1)) self.port1 = reactor.listenTCP(0, f1) util.spinUntil(lambda: self.port1.connected) # site2 is the subscriber sub = distrib.ResourceSubscription("127.0.0.1", self.port1.getHost().port) r2 = resource.Resource() r2.putChild("here", sub) f2 = MySite(r2) self.port2 = reactor.listenTCP(0, f2) util.spinUntil(lambda: self.port2.connected) # then we hit site2 with a client d = client.getPage("http://127.0.0.1:%d/here/there" % \ self.port2.getHost().port) res = util.wait(d, timeout=1.0) self.failUnlessEqual(res, "root") # A bit of a hack: force the pb client to disconnect, for cleanup # purposes. sub.publisher.broker.transport.loseConnection()
def testClientBind(self): f = MyServerFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") self.ports.append(p) factory = MyClientFactory() reactor.connectTCP("127.0.0.1", p.getHost().port, factory, bindAddress=("127.0.0.1", 0)) spinUntil(lambda :factory.protocol is not None) self.assertEquals(factory.protocol.made, 1) port = factory.protocol.transport.getHost().port f2 = MyClientFactory() reactor.connectTCP("127.0.0.1", p.getHost().port, f2, bindAddress=("127.0.0.1", port)) spinUntil(lambda :f2.failed) self.assertEquals(f2.failed, 1) f2.reason.trap(error.ConnectBindError) self.assert_(f2.reason.check(error.ConnectBindError)) self.assertEquals(f2.stopped, 1) p.stopListening() factory.protocol.transport.loseConnection() spinWhile(lambda :p.connected) self.assertEquals(factory.stopped, 1) self.cleanPorts(*self.ports)
def testDistrib(self): # site1 is the publisher r1 = resource.Resource() r1.putChild("there", static.Data("root", "text/plain")) site1 = server.Site(r1) f1 = pb.PBServerFactory(distrib.ResourcePublisher(site1)) self.port1 = reactor.listenTCP(0, f1) util.spinUntil(lambda :self.port1.connected) # site2 is the subscriber sub = distrib.ResourceSubscription("127.0.0.1", self.port1.getHost().port) r2 = resource.Resource() r2.putChild("here", sub) f2 = MySite(r2) self.port2 = reactor.listenTCP(0, f2) util.spinUntil(lambda :self.port2.connected) # then we hit site2 with a client d = client.getPage("http://127.0.0.1:%d/here/there" % \ self.port2.getHost().port) res = util.wait(d, timeout=1.0) self.failUnlessEqual(res, "root") # A bit of a hack: force the pb client to disconnect, for cleanup # purposes. sub.publisher.broker.transport.loseConnection()
def testWriter(self): f = protocol.Factory() f.protocol = LargeBufferWriterProtocol f.done = 0 f.problem = 0 f.len = self.datalen p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) clientF = LargeBufferReaderClientFactory() reactor.connectTCP("127.0.0.1", n, clientF) while 1: rxlen = clientF.len try: spinUntil(lambda :f.done and clientF.done, timeout=30) except defer.TimeoutError: if clientF.len == rxlen: raise # if we're still making progress, keep trying continue break self.failUnless(f.done, "writer didn't finish, it probably died") self.failUnless(clientF.len == self.datalen, "client didn't receive all the data it expected " "(%d != %d)" % (clientF.len, self.datalen)) self.failUnless(clientF.done, "client didn't see connection dropped")
def testKillPty(self): if self.verbose: print "starting processes" self.createProcesses(usePTY=1) reactor.callLater(1, self.kill, 0) reactor.callLater(2, self.kill, 1) spinUntil(self.check, 5)
def testStdio(self): """twisted.internet.stdio test.""" exe = sys.executable scriptPath = util.sibpath(__file__, "process_twisted.py") p = Accumulator() # As trial chdirs to _trial_temp after startup, this makes any # possible relative entries in PYTHONPATH invalid. Attempt to # fix that up. Otherwise process_twisted.py will use the # installed Twisted, which isn't really guaranteed to exist at # this stage. def fixup(l): for path in l: if os.path.isabs(path): yield path else: yield os.path.join(os.path.pardir, path) env = {"PYTHONPATH": os.pathsep.join(fixup(sys.path))} reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=env, path=None, usePTY=self.usePTY) p.transport.write("hello, world") p.transport.write("abc") p.transport.write("123") p.transport.closeStdin() spinUntil(lambda: p.closed, 10) self.assertEquals( p.outF.getvalue(), "hello, worldabc123", "Error message from process_twisted follows:" "\n\n%s\n\n" % p.errF.getvalue(), )
def testConnectorIdentity(self): f = ClosingFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) f.port = p spinUntil(lambda: p.connected) l = [] m = [] factory = ClientStartStopFactory() factory.clientConnectionLost = lambda c, r: (l.append(c), m.append(r)) factory.startedConnecting = lambda c: l.append(c) connector = reactor.connectTCP("127.0.0.1", n, factory) self.failUnless(interfaces.IConnector.providedBy(connector)) dest = connector.getDestination() self.assertEquals(dest.type, "TCP") self.assertEquals(dest.host, "127.0.0.1") self.assertEquals(dest.port, n) spinUntil(lambda: factory.stopped) d = self.cleanPorts(*self.ports) m[0].trap(error.ConnectionDone) self.assertEquals(l, [connector, connector]) return d
def testClose(self): if self.verbose: print "starting processes" self.createProcesses() reactor.callLater(1, self.close, 0) reactor.callLater(2, self.close, 1) spinUntil(self.check, 5)
def testReconnect(self): f = ClosingFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) f.port = p spinUntil(lambda: p.connected) factory = MyClientFactory() def clientConnectionLost(c, reason): c.connect() factory.clientConnectionLost = clientConnectionLost reactor.connectTCP("127.0.0.1", n, factory) spinUntil(lambda: factory.failed) p = factory.protocol self.assertEquals((p.made, p.closed), (1, 1)) factory.reason.trap(error.ConnectionRefusedError) self.assertEquals(factory.stopped, 1) return self.cleanPorts(*self.ports)
def testWriter(self): f = protocol.Factory() f.protocol = LargeBufferWriterProtocol f.done = 0 f.problem = 0 f.len = self.datalen p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) clientF = LargeBufferReaderClientFactory() reactor.connectTCP("127.0.0.1", n, clientF) while 1: rxlen = clientF.len try: spinUntil(lambda: f.done and clientF.done, timeout=30) except defer.TimeoutError: if clientF.len == rxlen: raise # if we're still making progress, keep trying continue break self.failUnless(f.done, "writer didn't finish, it probably died") self.failUnless( clientF.len == self.datalen, "client didn't receive all the data it expected " "(%d != %d)" % (clientF.len, self.datalen)) self.failUnless(clientF.done, "client didn't see connection dropped")
def testShutdownException(self): client = self.client f = self.f f.protocol.transport.loseConnection() client.transport.write("X") client.transport.loseWriteConnection() spinUntil(lambda :f.protocol.closed, True)
def testConnectorIdentity(self): f = ClosingFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) f.port = p spinUntil(lambda :p.connected) l = []; m = [] factory = ClientStartStopFactory() factory.clientConnectionLost = lambda c, r: (l.append(c), m.append(r)) factory.startedConnecting = lambda c: l.append(c) connector = reactor.connectTCP("127.0.0.1", n, factory) self.failUnless(interfaces.IConnector.providedBy(connector)) dest = connector.getDestination() self.assertEquals(dest.type, "TCP") self.assertEquals(dest.host, "127.0.0.1") self.assertEquals(dest.port, n) spinUntil(lambda :factory.stopped) d = self.cleanPorts(*self.ports) m[0].trap(error.ConnectionDone) self.assertEquals(l, [connector, connector]) return d
def testWriteCloseNotification(self): f = self.f f.protocol.transport.loseWriteConnection() spinUntil(lambda :f.protocol.writeHalfClosed) spinUntil(lambda :self.client.readHalfClosed) self.assertEquals(f.protocol.readHalfClosed, False)
def testReadNotificationRaises(self): self.f.protocol.readConnectionLost = self.aBug self.client.transport.loseWriteConnection() spinUntil(lambda :self.f.protocol.closed) # XXX client won't be closed?! why isn't server sending RST? # or maybe it is and we have a bug here. self.client.transport.loseConnection() log.flushErrors(RuntimeError)
def testWriteCloseNotification(self): f = self.f f.protocol.transport.loseWriteConnection() spinUntil(lambda: f.protocol.writeHalfClosed) spinUntil(lambda: self.client.readHalfClosed) self.assertEquals(f.protocol.readHalfClosed, False)
def testReadNotificationRaises(self): self.f.protocol.readConnectionLost = self.aBug self.client.transport.loseWriteConnection() spinUntil(lambda: self.f.protocol.closed) # XXX client won't be closed?! why isn't server sending RST? # or maybe it is and we have a bug here. self.client.transport.loseConnection() log.flushErrors(RuntimeError)
def getFreePort(self): """Get an empty port.""" p = reactor.listenTCP(0, protocol.ServerFactory()) spinUntil(lambda: p.connected) port = p.getHost().port p.stopListening() spinWhile(lambda: p.connected) return port
def getFreePort(self): """Get an empty port.""" p = reactor.listenTCP(0, protocol.ServerFactory()) spinUntil(lambda :p.connected) port = p.getHost().port p.stopListening() spinWhile(lambda :p.connected) return port
def testDumber(self): filename = self.mktemp() f = Factory(self, filename) l = reactor.listenUNIX(filename, f) tcf = TestClientFactory(self, filename) c = reactor.connectUNIX(filename, tcf) spinUntil(lambda :getattr(f.protocol, 'made', None) and getattr(tcf.protocol, 'made', None)) self._addPorts(l, c.transport, tcf.protocol.transport, f.protocol.transport)
def testFailing(self): clientF = MyClientFactory() # XXX we assume no one is listening on TCP port 69 reactor.connectTCP("127.0.0.1", 69, clientF, timeout=5) start = time.time() spinUntil(lambda :clientF.failed) clientF.reason.trap(error.ConnectionRefusedError)
def testFailing(self): clientF = MyClientFactory() # XXX we assume no one is listening on TCP port 69 reactor.connectTCP("127.0.0.1", 69, clientF, timeout=5) start = time.time() spinUntil(lambda: clientF.failed) clientF.reason.trap(error.ConnectionRefusedError)
def testLinger(self): # See what happens when all the pipes close before the process # actually stops. This test *requires* SIGCHLD catching to work, # as there is no other way to find out the process is done. exe = sys.executable scriptPath = util.sibpath(__file__, "process_linger.py") p = Accumulator() reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=None, path=None, childFDs={1: "r", 2: 2}) spinUntil(lambda: p.closed, 7) self.failUnlessEqual(p.outF.getvalue(), "here is some text\ngoodbye\n")
def setUp(self): PortCleanerUpper.setUp(self) self.f = f = MyHCFactory() self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1") self.ports.append(p) spinUntil(lambda :p.connected) d = protocol.ClientCreator(reactor, MyHCProtocol).connectTCP( p.getHost().host, p.getHost().port) self.client = util.wait(d) self.assertEquals(self.client.transport.connected, 1)
def tearDown(self): self.check() for i in (0,1): pp, process = self.pp[i], self.processes[i] if not pp.finished: try: os.kill(process.pid, signal.SIGTERM) except OSError: print "OSError" spinUntil(self.check, 5, msg="unable to shutdown child processes")
def tearDown(self): self.check() for i in (0, 1): pp, process = self.pp[i], self.processes[i] if not pp.finished: try: os.kill(process.pid, signal.SIGTERM) except OSError: print "OSError" spinUntil(self.check, 5, msg="unable to shutdown child processes")
def testFD(self): exe = sys.executable scriptPath = util.sibpath(__file__, "process_fds.py") p = FDChecker() reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=None, path=None, childFDs={0:"w", 1:"r", 2:2, 3:"w", 4:"r", 5:"w"}) spinUntil(lambda :p.done, 5) self.failIf(p.failed, p.failed)
def testStdinReader(self): pyExe = sys.executable scriptPath = util.sibpath(__file__, "process_stdinreader.py") p = Accumulator() reactor.spawnProcess(p, pyExe, [pyExe, "-u", scriptPath], env=None, path=None) p.transport.write("hello, world") p.transport.closeStdin() spinUntil(lambda: p.closed) self.assertEquals(p.errF.getvalue(), "err\nerr\n") self.assertEquals(p.outF.getvalue(), "out\nhello, world\nout\n")
def testAbnormalTermination(self): if os.path.exists('/bin/false'): cmd = '/bin/false' elif os.path.exists('/usr/bin/false'): cmd = '/usr/bin/false' else: raise RuntimeError("false not found in /bin or /usr/bin") p = TrivialProcessProtocol() reactor.spawnProcess(p, cmd, ['false'], env=None, usePTY=self.usePTY) spinUntil(lambda :p.finished) p.reason.trap(error.ProcessTerminated) self.assertEquals(p.reason.value.exitCode, 1) self.assertEquals(p.reason.value.signal, None)
def testRegister(self): p = self.clientPort.getHost().port r = sip.Request("REGISTER", "sip:bell.example.com") r.addHeader("to", "sip:[email protected]") r.addHeader("contact", "sip:[email protected]:%d" % p) r.addHeader("via", sip.Via("127.0.0.1", port=p).toString()) self.client.sendMessage(sip.URL(host="127.0.0.1", port=self.serverAddress[1]), r) spinUntil(lambda: len(self.client.received)) self.assertEquals(len(self.client.received), 1) r = self.client.received[0] self.assertEquals(r.code, 200)
def setUp(self): PortCleanerUpper.setUp(self) self.f = f = MyHCFactory() self.p = p = reactor.listenTCP(0, f, interface="127.0.0.1") self.ports.append(p) spinUntil(lambda: p.connected) d = protocol.ClientCreator(reactor, MyHCProtocol).connectTCP( p.getHost().host, p.getHost().port) self.client = util.wait(d) self.assertEquals(self.client.transport.connected, 1)
def testAbnormalTermination(self): if os.path.exists('/bin/false'): cmd = '/bin/false' elif os.path.exists('/usr/bin/false'): cmd = '/usr/bin/false' else: raise RuntimeError("false not found in /bin or /usr/bin") p = TrivialProcessProtocol() reactor.spawnProcess(p, cmd, ['false'], env=None, usePTY=self.usePTY) spinUntil(lambda: p.finished) p.reason.trap(error.ProcessTerminated) self.assertEquals(p.reason.value.exitCode, 1) self.assertEquals(p.reason.value.signal, None)
def testPIDFile(self): filename = self.mktemp() f = Factory(self, filename) l = reactor.listenUNIX(filename, f, mode = 0600, wantPID=1) self.failUnless(lockfile.isLocked(filename + ".lock")) tcf = TestClientFactory(self, filename) c = reactor.connectUNIX(filename, tcf, checkPID=1) spinUntil(lambda :getattr(f.protocol, 'made', None) and getattr(tcf.protocol, 'made', None)) self._addPorts(l, c.transport, tcf.protocol.transport, f.protocol.transport) self.cleanPorts(*self.ports) self.failIf(lockfile.isLocked(filename + ".lock"))
def testRegister(self): p = self.clientPort.getHost().port r = sip.Request("REGISTER", "sip:bell.example.com") r.addHeader("to", "sip:[email protected]") r.addHeader("contact", "sip:[email protected]:%d" % p) r.addHeader("via", sip.Via("127.0.0.1", port=p).toString()) self.client.sendMessage( sip.URL(host="127.0.0.1", port=self.serverAddress[1]), r) spinUntil(lambda: len(self.client.received)) self.assertEquals(len(self.client.received), 1) r = self.client.received[0] self.assertEquals(r.code, 200)
def testHostAddress(self): f1 = MyServerFactory() p1 = reactor.listenTCP(0, f1, interface='127.0.0.1') n = p1.getHost().port self.ports.append(p1) f2 = MyOtherClientFactory() p2 = reactor.connectTCP('127.0.0.1', n, f2) spinUntil(lambda :p2.state == "connected") self.assertEquals(p1.getHost(), f2.address) self.assertEquals(p1.getHost(), f2.protocol.transport.getPeer()) util.wait(defer.maybeDeferred(p1.stopListening)) self.ports.append(p2.transport) self.cleanPorts(*self.ports)
def testCallLater(self): def bad(): raise RuntimeError, "this shouldn't have been called" i = reactor.callLater(0.1, bad) i.cancel() self.assertRaises(error.AlreadyCancelled, i.cancel) i = reactor.callLater(0.5, self._callback, 1, a=1) start = time.time() spinUntil(lambda :self._called, 5) self.assertApproximates(self._calledTime, start + 0.5, 0.2 ) self.assertRaises(error.AlreadyCalled, i.cancel) del self._called del self._calledTime
def testOpeningTTY(self): exe = sys.executable scriptPath = util.sibpath(__file__, "process_tty.py") p = Accumulator() reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=None, path=None, usePTY=self.usePTY) p.transport.write("hello world!\n") spinUntil(lambda: p.closed, 10) self.assertEquals( p.outF.getvalue(), "hello world!\r\nhello world!\r\n", "Error message from process_tty follows:\n\n%s\n\n" % p.outF.getvalue(), )
def testUserFail(self): f = MyServerFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) def startedConnecting(connector): connector.stopConnecting() factory = ClientStartStopFactory() factory.startedConnecting = startedConnecting reactor.connectTCP("127.0.0.1", n, factory) spinUntil(lambda :factory.stopped) self.assertEquals(factory.failed, 1) factory.reason.trap(error.UserError) return self.cleanPorts(*self.ports)
def testClientStartStop(self): f = ClosingFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") self.n = p.getHost().port self.ports.append(p) f.port = p spinUntil(lambda :p.connected) factory = ClientStartStopFactory() reactor.connectTCP("127.0.0.1", self.n, factory) self.assert_(factory.started) reactor.iterate() reactor.iterate() spinUntil(lambda :factory.stopped) return self.cleanPorts(*self.ports)
def cleanPorts(self, *ports): for p in ports: if not hasattr(p, 'disconnected'): raise RuntimeError, ("You handed something to cleanPorts that" " doesn't have a disconnected attribute, dummy!") if not p.disconnected: d = getattr(p, self.callToLoseCnx)() if isinstance(d, defer.Deferred): wait(d) else: try: spinUntil(lambda :p.disconnected) except: failure.Failure().printTraceback()
def testNormalTermination(self): if os.path.exists("/bin/true"): cmd = "/bin/true" elif os.path.exists("/usr/bin/true"): cmd = "/usr/bin/true" else: raise RuntimeError("true not found in /bin or /usr/bin") p = TrivialProcessProtocol() reactor.spawnProcess(p, cmd, ["true"], env=None, usePTY=self.usePTY) spinUntil(lambda: p.finished) p.reason.trap(error.ProcessDone) self.assertEquals(p.reason.value.exitCode, 0) self.assertEquals(p.reason.value.signal, None)
def testGetDelayedCalls(self): if not hasattr(reactor, "getDelayedCalls"): return self.checkTimers() self.addTimer(35, self.done) self.addTimer(20, self.callback) self.addTimer(30, self.callback) which = self.counter self.addTimer(29, self.callback) self.addTimer(25, self.addCallback) self.addTimer(26, self.callback) self.timers[which].cancel() del self.timers[which] self.checkTimers() spinUntil(lambda :self.finished, 5) self.checkTimers()
def testHostAddress(self): f1 = MyServerFactory() p1 = reactor.listenTCP(0, f1, interface='127.0.0.1') n = p1.getHost().port self.ports.append(p1) f2 = MyOtherClientFactory() p2 = reactor.connectTCP('127.0.0.1', n, f2) spinUntil(lambda: p2.state == "connected") self.assertEquals(p1.getHost(), f2.address) self.assertEquals(p1.getHost(), f2.protocol.transport.getPeer()) util.wait(defer.maybeDeferred(p1.stopListening)) self.ports.append(p2.transport) self.cleanPorts(*self.ports)
def loopbackUNIX(server, client, noisy=True): """Run session between server and client protocol instances over UNIX socket.""" path = tempfile.mktemp() from twisted.internet import reactor f = protocol.Factory() f.noisy = noisy f.buildProtocol = lambda addr, p=server: p serverPort = reactor.listenUNIX(path, f) reactor.iterate() clientF = LoopbackClientFactory(client) clientF.noisy = noisy reactor.connectUNIX(path, clientF) spinUntil(lambda: clientF.disconnected) # A spinWhile(lambda: server.transport.connected) # B serverPort.stopListening() spinWhile(lambda: serverPort.connected) # C
def loopbackUNIX(server, client, noisy=True): """Run session between server and client protocol instances over UNIX socket.""" path = tempfile.mktemp() from twisted.internet import reactor f = protocol.Factory() f.noisy = noisy f.buildProtocol = lambda addr, p=server: p serverPort = reactor.listenUNIX(path, f) reactor.iterate() clientF = LoopbackClientFactory(client) clientF.noisy = noisy reactor.connectUNIX(path, clientF) spinUntil(lambda :clientF.disconnected) # A spinWhile(lambda :server.transport.connected) # B serverPort.stopListening() spinWhile(lambda :serverPort.connected) # C
def testFD(self): exe = sys.executable scriptPath = util.sibpath(__file__, "process_fds.py") p = FDChecker() reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=None, path=None, childFDs={ 0: "w", 1: "r", 2: 2, 3: "w", 4: "r", 5: "w" }) spinUntil(lambda: p.done, 5) self.failIf(p.failed, p.failed)
def testClientStartStop(self): f = ClosingFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") self.n = p.getHost().port self.ports.append(p) f.port = p spinUntil(lambda: p.connected) factory = ClientStartStopFactory() reactor.connectTCP("127.0.0.1", self.n, factory) self.assert_(factory.started) reactor.iterate() reactor.iterate() spinUntil(lambda: factory.stopped) return self.cleanPorts(*self.ports)
def testAmoralRPort(self): # rport is allowed without a value, apparently because server # implementors might be too stupid to check the received port # against 5060 and see if they're equal, and because client # implementors might be too stupid to bind to port 5060, or set a # value on the rport parameter they send if they bind to another # port. p = self.clientPort.getHost().port r = sip.Request("REGISTER", "sip:bell.example.com") r.addHeader("to", "sip:[email protected]") r.addHeader("contact", "sip:[email protected]:%d" % p) r.addHeader("via", sip.Via("127.0.0.1", port=p, rport=True).toString()) self.client.sendMessage( sip.URL(host="127.0.0.1", port=self.serverAddress[1]), r) spinUntil(lambda: len(self.client.received)) self.assertEquals(len(self.client.received), 1) r = self.client.received[0] self.assertEquals(r.code, 200)
def testUserFail(self): f = MyServerFactory() p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) def startedConnecting(connector): connector.stopConnecting() factory = ClientStartStopFactory() factory.startedConnecting = startedConnecting reactor.connectTCP("127.0.0.1", n, factory) spinUntil(lambda: factory.stopped) self.assertEquals(factory.failed, 1) factory.reason.trap(error.UserError) return self.cleanPorts(*self.ports)
def testCallLater(self): # add and remove a callback def bad(): raise RuntimeError, "this shouldn't have been called" i = reactor.callLater(0.1, bad) i.cancel() self.assertRaises(error.AlreadyCancelled, i.cancel) i = reactor.callLater(0.5, self._callback, 1, a=1) start = time.time() spinUntil(lambda: self._called, 5) self.assertApproximates(self._calledTime, start + 0.5, 0.2) self.assertRaises(error.AlreadyCalled, i.cancel) del self._called del self._calledTime
def testWriter(self): f = protocol.Factory() f.protocol = WriterProtocol f.done = 0 f.problem = 0 p = reactor.listenTCP(0, f, interface="127.0.0.1") n = p.getHost().port self.ports.append(p) clientF = WriterClientFactory() reactor.connectTCP("127.0.0.1", n, clientF) spinUntil(lambda: (f.done and clientF.done)) self.failUnless(f.done, "writer didn't finish, it probably died") self.failUnless(f.problem == 0, "writer indicated an error") self.failUnless(clientF.done, "client didn't see connection dropped") expected = "".join( ["Hello Cleveland!\n", "Goodbye", " cruel", " world", "\n"]) self.failUnless(clientF.data == expected, "client didn't receive all the data it expected")
def loopbackTCP(server, client, port=0, noisy=True): """Run session between server and client protocol instances over TCP.""" from twisted.internet import reactor f = protocol.Factory() f.noisy = noisy f.buildProtocol = lambda addr, p=server: p serverPort = reactor.listenTCP(port, f, interface='127.0.0.1') reactor.iterate() clientF = LoopbackClientFactory(client) clientF.noisy = noisy reactor.connectTCP('127.0.0.1', serverPort.getHost().port, clientF) # this needs to wait until: # A: the client has disconnected # B: the server has noticed, and its own socket has disconnected # C: the listening socket has been shut down spinUntil(lambda: clientF.disconnected) # A spinWhile(lambda: server.transport.connected) # B serverPort.stopListening() spinWhile(lambda: serverPort.connected) # C
def testGetDelayedCalls(self): if not hasattr(reactor, "getDelayedCalls"): return # This is not a race because we don't do anything which might call # the reactor until we have all the timers set up. If we did, this # test might fail on slow systems. self.checkTimers() self.addTimer(35, self.done) self.addTimer(20, self.callback) self.addTimer(30, self.callback) which = self.counter self.addTimer(29, self.callback) self.addTimer(25, self.addCallback) self.addTimer(26, self.callback) self.timers[which].cancel() del self.timers[which] self.checkTimers() spinUntil(lambda: self.finished, 5) self.checkTimers()
def testTcpKeepAlive(self): f = MyServerFactory() port = reactor.listenTCP(0, f, interface="127.0.0.1") self.n = port.getHost().port self.ports.append(port) clientF = MyClientFactory() reactor.connectTCP("127.0.0.1", self.n, clientF) spinUntil(lambda: (f.called > 0 and getattr(clientF, 'protocol', None) is not None)) for p in clientF.protocol, f.protocol: transport = p.transport self.assertEquals(transport.getTcpKeepAlive(), 0) transport.setTcpKeepAlive(1) self.assertEquals(transport.getTcpKeepAlive(), 1) transport.setTcpKeepAlive(0) spinUntil(lambda: transport.getTcpKeepAlive() == 0, timeout=1.0) return self.cleanPorts(clientF.protocol.transport, port)
def testCloseWriteCloser(self): client = self.client f = self.f t = client.transport t.write("hello") spinUntil(lambda: len(t._tempDataBuffer) == 0) t.loseWriteConnection() spinUntil(lambda: t._writeDisconnected) self.assertEquals(client.closed, False) self.assertEquals(client.writeHalfClosed, True) self.assertEquals(client.readHalfClosed, False) spinUntil(lambda: f.protocol.readHalfClosed, timeout=1.0) w = client.transport.write w(" world") w("lalala fooled you") spinWhile(lambda: len(client.transport._tempDataBuffer) > 0) self.assertEquals(f.protocol.data, "hello") self.assertEquals(f.protocol.closed, False) self.assertEquals(f.protocol.readHalfClosed, True)
def testServerStartStop(self): f = StartStopFactory() # listen on port p1 = reactor.listenTCP(0, f, interface='127.0.0.1') self.n1 = p1.getHost().port self.ports.append(p1) spinUntil(lambda: (p1.connected == 1)) self.assertEquals((f.started, f.stopped), (1, 0)) # listen on two more ports p2 = reactor.listenTCP(0, f, interface='127.0.0.1') self.n2 = p2.getHost().port self.ports.append(p2) p3 = reactor.listenTCP(0, f, interface='127.0.0.1') self.n3 = p3.getHost().port self.ports.append(p3) spinUntil(lambda: (p2.connected == 1 and p3.connected == 1)) self.assertEquals((f.started, f.stopped), (1, 0)) # close two ports p1.stopListening() p2.stopListening() spinWhile(lambda: (p1.connected == 1 or p2.connected == 1)) self.assertEquals((f.started, f.stopped), (1, 0)) # close last port p3.stopListening() spinWhile(lambda: (p3.connected == 1)) self.assertEquals((f.started, f.stopped), (1, 1)) return self.cleanPorts(*self.ports)
def testProcess(self): exe = sys.executable scriptPath = util.sibpath(__file__, "process_tester.py") p = TestProcessProtocol() reactor.spawnProcess(p, exe, [exe, "-u", scriptPath], env=None) spinUntil(lambda: p.finished, 10) self.failUnless(p.finished) self.assertEquals(p.stages, [1, 2, 3, 4, 5]) # test status code f = p.reason f.trap(error.ProcessTerminated) self.assertEquals(f.value.exitCode, 23) # would .signal be available on non-posix? #self.assertEquals(f.value.signal, None) try: import process_tester, glob for f in glob.glob(process_tester.test_file_match): os.remove(f) except: pass
def testExchange(self): clientaddr = self.mktemp() serveraddr = self.mktemp() sp = ServerProto() cp = ClientProto() s = reactor.listenUNIXDatagram(serveraddr, sp) c = reactor.connectUNIXDatagram(serveraddr, cp, bindAddress = clientaddr) spinUntil(lambda:sp.started and cp.started) cp.transport.write("hi") spinUntil(lambda:sp.gotwhat == "hi" and cp.gotback == "hi back") s.stopListening() c.stopListening() os.unlink(clientaddr) os.unlink(serveraddr) spinWhile(lambda:s.connected and c.connected) self.failUnlessEqual("hi", sp.gotwhat) self.failUnlessEqual(clientaddr, sp.gotfrom) self.failUnlessEqual("hi back", cp.gotback)