def testNoParamsForPASS(self): """Issuing PASS without a password is a syntax error.""" wait(self.client.queueStringCommand('USER foo')) d = self.client.queueStringCommand('PASS') self.failUnlessEqual( ['500 Syntax error: PASS requires an argument.'], self._waitForCommandFailure(d))
def _makeDataConnection(self): # Establish a passive data connection (i.e. client connecting to # server). responseLines = wait(self.client.queueStringCommand("PASV")) host, port = ftp.decodeHostPort(responseLines[-1][4:]) downloader = wait(protocol.ClientCreator(reactor, _BufferingProtocol).connectTCP("127.0.0.1", port)) return downloader
def testTCP(self): s = service.MultiService() s.startService() factory = protocol.ServerFactory() factory.protocol = TestEcho TestEcho.d = defer.Deferred() t = internet.TCPServer(0, factory) t.setServiceParent(s) num = t._port.getHost().port class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write('lalala\r\n') def lineReceived(self, line): self.factory.line = line self.transport.loseConnection() factory = protocol.ClientFactory() factory.protocol = Foo factory.line = None internet.TCPClient('127.0.0.1', num, factory).setServiceParent(s) util.spinWhile(lambda: factory.line is None) self.assertEqual(factory.line, 'lalala') # Cleanup the reactor util.wait(defer.maybeDeferred(s.stopService)) util.wait(TestEcho.d)
def test_upnp_mapper(self): from shtoom.upnp import UPnPMapper ae = self.assertEquals ar = self.assertRaises checkUPnP() mapper = UPnPMapper() uprot = DatagramProtocol() uport = reactor.listenUDP(random.randint(10000,20000), uprot) class tfactory(Factory): protocol = Protocol tport = reactor.listenTCP(0, tfactory()) for port in uport, tport: ar(ValueError, mapper.unmap, port) ar(ValueError, mapper.info, port) t = TestMapper(mapper, port) d = t.go() util.wait(d, timeout=16) ae(len(t.map_res), 2) ae(t.map_res, t.info_res) ae(t.unmap_res, None) # Can't unmap a port that's not mapped ar(ValueError, mapper.unmap, port) d = port.stopListening() util.wait(d) # Can't map a closed port ar(ValueError, mapper.map, port) # Can't get info on a closed port ar(ValueError, mapper.info, port)
def testTCP(self): s = service.MultiService() c = compat.IOldApplication(s) factory = protocol.ServerFactory() factory.protocol = TestEcho TestEcho.d = defer.Deferred() c.listenTCP(0, factory) s.privilegedStartService() s.startService() num = list(s)[0]._port.getHost().port class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write('lalala\r\n') def lineReceived(self, line): self.factory.line = line self.transport.loseConnection() factory = protocol.ClientFactory() factory.protocol = Foo factory.line = None c.connectTCP('127.0.0.1', num, factory) util.spinWhile(lambda: factory.line is None) util.wait(defer.maybeDeferred(s.stopService)) self.assertEqual(factory.line, 'lalala') # Cleanup the reactor util.wait(TestEcho.d)
def testUNIX(self): if not interfaces.IReactorUNIX(reactor, None): raise unittest.SkipTest, "This reactor does not support UNIX domain sockets" s = service.MultiService() c = compat.IOldApplication(s) factory = protocol.ServerFactory() factory.protocol = TestEcho TestEcho.d = defer.Deferred() if os.path.exists('.hello.skt'): os.remove('hello.skt') c.listenUNIX('./hello.skt', factory) class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write('lalala\r\n') def lineReceived(self, line): self.factory.line = line self.transport.loseConnection() factory = protocol.ClientFactory() factory.protocol = Foo factory.line = None c.connectUNIX('./hello.skt', factory) s.privilegedStartService() s.startService() util.spinWhile(lambda: factory.line is None) util.wait(defer.maybeDeferred(s.stopService)) self.assertEqual(factory.line, 'lalala') # Cleanup the reactor util.wait(TestEcho.d)
def testFailedRETR(self): try: f = protocol.Factory() f.noisy = 0 port = reactor.listenTCP(0, f, interface="127.0.0.1") portNum = port.getHost().port responses = ['220 ready, dude (vsFTPd 1.0.0: beat me, break me)', '331 Please specify the password.', '230 Login successful. Have fun.', '200 Binary it is, then.', '227 Entering Passive Mode (127,0,0,1,%d,%d)' % (portNum >> 8, portNum & 0xff), '550 Failed to open file.'] f.buildProtocol = lambda addr: PrintLines(responses) client = ftp.FTPClient(passive=1) cc = protocol.ClientCreator(reactor, ftp.FTPClient, passive=1) client = wait(cc.connectTCP('127.0.0.1', portNum)) p = protocol.Protocol() d = client.retrieveFile('/file/that/doesnt/exist', p) d.addCallback(lambda r, self=self: self.fail('Callback incorrectly called: %r' % r)) def p(failure): failure.trap(ftp.CommandFailed) d.addErrback(p) wait(d) log.flushErrors(ftp.FTPError) finally: d = port.stopListening() if d is not None: wait(d)
def test_nullmapper(self): from shtoom.nat import getNullMapper mapper = getNullMapper() ae = self.assertEquals ar = self.assertRaises uprot = DatagramProtocol() uport = reactor.listenUDP(0, uprot) class tfactory(Factory): protocol = Protocol tport = reactor.listenTCP(0, tfactory()) for port in uport, tport: ar(ValueError, mapper.unmap, port) ar(ValueError, mapper.info, port) t = TestMapper(mapper, port) d = t.go() util.wait(d) ae(len(t.map_res), 2) ae(t.map_res, t.info_res) ae(t.unmap_res, None) # Can't unmap a port that's not mapped ar(ValueError, mapper.unmap, port) d = port.stopListening() util.wait(d) # Can't map a closed port ar(ValueError, mapper.map, port) # Can't get info on a closed port ar(ValueError, mapper.info, port)
def testStopTrying(self): f = Factory() f.protocol = In f.connections = 0 f.allMessages = [] c = ReconnectingClientFactory() c.initialDelay = c.delay = 0.2 c.protocol = Out c.howManyTimes = 2 port = reactor.listenTCP(0, f) PORT = port.getHost().port reactor.connectTCP('127.0.0.1', PORT, c) now = time.time() while len(f.allMessages) != 2 and (time.time() < now + 10): reactor.iterate(0.1) util.wait(defer.maybeDeferred(port.stopListening)) self.assertEquals(len(f.allMessages), 2, "not enough messages -- %s" % f.allMessages) self.assertEquals(f.connections, 2, "Number of successful connections incorrect %d" % f.connections) self.assertEquals(f.allMessages, [Out.msgs] * 2) self.failIf(c.continueTrying, "stopTrying never called or ineffective")
def eoc_create(name, *owners): """Create list with given name""" assert '@' in name assert not name.startswith('.') site = getSite() d = site.create(name, owners) wait(d)
def testTCP(self): s = service.MultiService() c = compat.IOldApplication(s) factory = protocol.ServerFactory() factory.protocol = TestEcho TestEcho.d = defer.Deferred() c.listenTCP(0, factory) s.privilegedStartService() s.startService() num = list(s)[0]._port.getHost().port class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write("lalala\r\n") def lineReceived(self, line): self.factory.line = line self.transport.loseConnection() factory = protocol.ClientFactory() factory.protocol = Foo factory.line = None c.connectTCP("127.0.0.1", num, factory) util.spinWhile(lambda: factory.line is None) util.wait(defer.maybeDeferred(s.stopService)) self.assertEqual(factory.line, "lalala") util.wait(TestEcho.d)
def testTCP(self): s = service.MultiService() s.startService() factory = protocol.ServerFactory() factory.protocol = TestEcho TestEcho.d = defer.Deferred() t = internet.TCPServer(0, factory) t.setServiceParent(s) num = t._port.getHost().port class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write("lalala\r\n") def lineReceived(self, line): self.factory.line = line self.transport.loseConnection() factory = protocol.ClientFactory() factory.protocol = Foo factory.line = None internet.TCPClient("127.0.0.1", num, factory).setServiceParent(s) util.spinWhile(lambda: factory.line is None) self.assertEqual(factory.line, "lalala") util.wait(defer.maybeDeferred(s.stopService)) util.wait(TestEcho.d)
def testUNIX(self): if not interfaces.IReactorUNIX(reactor, None): raise unittest.SkipTest, "This reactor does not support UNIX domain sockets" s = service.MultiService() c = compat.IOldApplication(s) factory = protocol.ServerFactory() factory.protocol = TestEcho TestEcho.d = defer.Deferred() if os.path.exists(".hello.skt"): os.remove("hello.skt") c.listenUNIX("./hello.skt", factory) class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write("lalala\r\n") def lineReceived(self, line): self.factory.line = line self.transport.loseConnection() factory = protocol.ClientFactory() factory.protocol = Foo factory.line = None c.connectUNIX("./hello.skt", factory) s.privilegedStartService() s.startService() util.spinWhile(lambda: factory.line is None) util.wait(defer.maybeDeferred(s.stopService)) self.assertEqual(factory.line, "lalala") util.wait(TestEcho.d)
def test_upnp_mapper(self): from shtoom.upnp import UPnPMapper ae = self.assertEqual ar = self.assertRaises checkUPnP() mapper = UPnPMapper() uprot = DatagramProtocol() uport = reactor.listenUDP(random.randint(10000, 20000), uprot) class tfactory(Factory): protocol = Protocol tport = reactor.listenTCP(0, tfactory()) for port in uport, tport: ar(ValueError, mapper.unmap, port) ar(ValueError, mapper.info, port) t = TestMapper(mapper, port) d = t.go() util.wait(d, timeout=16) ae(len(t.map_res), 2) ae(t.map_res, t.info_res) ae(t.unmap_res, None) # Can't unmap a port that's not mapped ar(ValueError, mapper.unmap, port) d = port.stopListening() util.wait(d) # Can't map a closed port ar(ValueError, mapper.map, port) # Can't get info on a closed port ar(ValueError, mapper.info, port)
def tearDown(self): # Wait until all the protocols on the server-side of this test have # been disconnected, to avoid leaving junk in the reactor. for d in self.serverConns: util.wait(d) PortCleanerUpper.tearDown(self)
def _reentrantWait(self): def threadedOperation(n): time.sleep(n) return n d1 = threads.deferToThread(threadedOperation, 0.125) d2 = threads.deferToThread(threadedOperation, 0.250) d1.addCallback(lambda ignored: util.wait(d2)) util.wait(d1)
def checkUPnP(): from shtoom.upnp import getUPnP d = getUPnP() s = Saver() d.addCallback(s.save) util.wait(d, timeout=8) if s.val is None: raise unittest.SkipTest('no UPnP available')
def setUp(self): # import here not to get twisted.internet.reactor imported too soon from solipsis.services.profile.network.manager import NetworkManager self.network = NetworkManager() util.wait(self.network.start(), timeout=10) self.network.on_new_peer(FakePeer("boby")) self.network.on_service_data( "boby", "HELLO 127.0.0.1:%s"% str(self.network.server.local_port))
def testStateMachine(self): d = defer.Deferred() A = StateMachineOne(d) reactor.callLater(0, A._start) s = Saver() d.addCallback(s.save) util.wait(d) self.assertEquals(s.res, [0, 1, 2, 3])
def testStateMachine(self): d = defer.Deferred() A = StateMachineOne(d) reactor.callLater(0, A._start) s = Saver() d.addCallback(s.save) util.wait(d) self.assertEquals(s.res, [0,1,2,3])
def _makeDataConnection(self): responseLines = wait(self.client.queueStringCommand('PASV')) host, port = ftp.decodeHostPort(responseLines[-1][4:]) downloader = wait( protocol.ClientCreator(reactor, _BufferingProtocol).connectTCP('127.0.0.1', port) ) return downloader
def _makeDataConnection(self): # Establish a passive data connection (i.e. client connecting to # server). responseLines = wait(self.client.queueStringCommand('PASV')) host, port = ftp.decodeHostPort(responseLines[-1][4:]) downloader = wait( protocol.ClientCreator(reactor, _BufferingProtocol).connectTCP( '127.0.0.1', port)) return downloader
def tearDown(self): # disconnect first one util.wait(self.assertResponse("disconnect", "Disconnected")) NetworkTest.tearDown(self) # second one util.wait(self.assertOtherResponse("disconnect", "Disconnected")) self.other_factory.stopTrying() self.other_factory.stopFactory() self.other_connector.disconnect()
def test_stundiscovery(self): from shtoom.stun import getSTUN, _NatType ae = self.assertEquals a_ = self.assert_ d = getSTUN() s = Saver() d.addCallback(s.save) util.wait(d, timeout=16) a_(isinstance(s.arg, _NatType), "%s, %s :: %s" % (s, s.arg, type(s.arg),))
def testBrokenStateMachine(self): d = defer.Deferred() A = StateMachineTwo(d) reactor.callLater(0, A._start) s = Saver() d.addCallback(s.save) d.addErrback(s.error) util.wait(d) self.assertEquals(s.res, None) self.assert_(isinstance(s.err.value, EventNotSpecifiedError))
def testManyLargeDownloads(self): self._anonymousLogin() for size in range(100000, 110000, 500): fObj = file(os.path.join(self.directory, '%d.txt' % (size,)), 'wb') fObj.write('x' * size) fObj.close() downloader = self._makeDataConnection() d = self.client.queueStringCommand('RETR %d.txt' % (size,)) wait(defer.gatherResults([d, downloader.d])) self.assertEqual('x' * size, downloader.buffer)
def _anonymousLogin(self): responseLines = wait(self.client.queueStringCommand('USER anonymous')) self.assertEquals( ['331 Guest login ok, type your email address as password.'], responseLines) responseLines = wait( self.client.queueStringCommand('PASS [email protected]')) self.assertEquals( ['230 Anonymous login ok, access restrictions apply.'], responseLines)
def _bail(self): from twisted.internet import reactor d = defer.Deferred() reactor.addSystemEventTrigger('after', 'shutdown', lambda: d.callback(None)) reactor.fireSystemEvent('shutdown') # radix's suggestion treactor = interfaces.IReactorThreads(reactor, None) if treactor is not None: treactor.suggestThreadPoolSize(0) util.wait(d) # so that the shutdown event completes
def tearDown(self): # Clean up sockets self.client.transport.loseConnection() d = self.port.stopListening() if d is not None: wait(d) del self.serverProtocol # Clean up temporary directory shutil.rmtree(self.directory)
def testStateMachineWithDeferreds(self): d = defer.Deferred() A = StateMachineThree(d) reactor.callLater(0, A._start) class Saver: res = None def save(self, res): self.res = res s = Saver() d.addCallback(s.save) util.wait(d) self.assertEqual(s.res, [0,1,2,3])
def testStateMachineWithDeferreds(self): d = defer.Deferred() A = StateMachineThree(d) reactor.callLater(0, A._start) class Saver: res = None def save(self, res): self.res = res s = Saver() d.addCallback(s.save) util.wait(d) self.assertEquals(s.res, [0,1,2,3])
def test_interruptDoesntShutdown(self): reactor.addSystemEventTrigger('after', 'shutdown', self._shutdownCalled) d = defer.Deferred() d.addCallback(self.raiseKeyInt) reactor.callLater(0, d.callback, None) try: util.wait(d, useWaitError=False) except KeyboardInterrupt: self.failIf(self.shutdownCalled, "System shutdown triggered") else: self.fail("KeyboardInterrupt wasn't raised")
def _anonymousLogin(self): responseLines = wait(self.client.queueStringCommand('USER anonymous')) self.assertEquals( ['331 Guest login ok, type your email address as password.'], responseLines ) responseLines = wait(self.client.queueStringCommand( 'PASS [email protected]') ) self.assertEquals( ['230 Anonymous login ok, access restrictions apply.'], responseLines )
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 testPORTCannotConnect(self): self._anonymousLogin() port = reactor.listenTCP(0, protocol.Factory(), interface='127.0.0.1') portNum = port.getHost().port d = port.stopListening() if d is not None: wait(d) cmd = 'PORT ' + ftp.encodeHostPort('127.0.0.1', portNum) d = self.client.queueStringCommand(cmd) self.failUnlessEqual( ["425 Can't open data connection."], self._waitForCommandFailure(d) )
def test_nullDougApp(self): app = TestDougApplication(NullApp) app.configFileName = None app.boot(args=['--listenport', '0']) app._voiceappArgs = {} d = app._trial_def = defer.Deferred() s = Saver() d.addCallback(s.save) # We explicitly start the voiceapp here reactor.callLater(0, app.startVoiceApp) util.wait(d) self.assertEquals(s.val, 'hello world') app.stopSIP()
def _makeDataConnection(self): deferred = defer.Deferred() class DataFactory(protocol.ServerFactory): protocol = _BufferingProtocol def buildProtocol(self, addr): p = protocol.ServerFactory.buildProtocol(self, addr) reactor.callLater(0, deferred.callback, p) return p dataPort = reactor.listenTCP(0, DataFactory(), interface='127.0.0.1') self.dataPorts.append(dataPort) cmd = 'PORT ' + ftp.encodeHostPort('127.0.0.1', dataPort.getHost().port) responseLines = wait(self.client.queueStringCommand(cmd)) downloader = wait(deferred) return downloader
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 testUNIX(self): if not interfaces.IReactorUNIX(reactor, None): raise unittest.SkipTest, "This reactor does not support UNIX domain sockets" s = service.MultiService() s.startService() factory = protocol.ServerFactory() factory.protocol = TestEcho TestEcho.d = defer.Deferred() t = internet.UNIXServer("echo.skt", factory) t.setServiceParent(s) class Foo(basic.LineReceiver): def connectionMade(self): self.transport.write("lalala\r\n") def lineReceived(self, line): self.factory.line = line self.transport.loseConnection() factory = protocol.ClientFactory() factory.protocol = Foo factory.line = None internet.UNIXClient("echo.skt", factory).setServiceParent(s) util.spinWhile(lambda: factory.line is None) self.assertEqual(factory.line, "lalala") util.wait(defer.maybeDeferred(s.stopService)) util.wait(TestEcho.d) TestEcho.d = defer.Deferred() factory.line = None s.startService() util.spinWhile(lambda: factory.line is None) self.assertEqual(factory.line, "lalala") util.wait(defer.maybeDeferred(s.stopService)) util.wait(TestEcho.d)
def testManyLargeDownloads(self): # Login self._anonymousLogin() # Download a range of different size files for size in range(100000, 110000, 500): fObj = file(os.path.join(self.directory, '%d.txt' % (size, )), 'wb') fObj.write('x' * size) fObj.close() downloader = self._makeDataConnection() d = self.client.queueStringCommand('RETR %d.txt' % (size, )) wait(defer.gatherResults([d, downloader.d])) self.assertEqual('x' * size, downloader.buffer)
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 setUp(self): # Create a directory self.directory = self.mktemp() os.mkdir(self.directory) # Start the server p = portal.Portal(ftp.FTPRealm(self.directory)) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) self.factory = ftp.FTPFactory(portal=p) self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1") # Hook the server's buildProtocol to make the protocol instance # accessible to tests. buildProtocol = self.factory.buildProtocol def _rememberProtocolInstance(addr): protocol = buildProtocol(addr) self.serverProtocol = protocol.wrappedProtocol return protocol self.factory.buildProtocol = _rememberProtocolInstance # Connect a client to it portNum = self.port.getHost().port clientCreator = protocol.ClientCreator(reactor, ftp.FTPClientBasic) self.client = wait(clientCreator.connectTCP("127.0.0.1", portNum))
def testNothing(self): def _genNothing(): if 0: yield 1 _genNothing = deferredGenerator(_genNothing) self.assertEquals(util.wait(_genNothing()), None)
def testFailedRETR(self): try: f = protocol.Factory() f.noisy = 0 port = reactor.listenTCP(0, f, interface="127.0.0.1") portNum = port.getHost().port # This test data derived from a bug report by ranty on #twisted responses = [ '220 ready, dude (vsFTPd 1.0.0: beat me, break me)', # USER anonymous '331 Please specify the password.', # PASS [email protected] '230 Login successful. Have fun.', # TYPE I '200 Binary it is, then.', # PASV '227 Entering Passive Mode (127,0,0,1,%d,%d)' % (portNum >> 8, portNum & 0xff), # RETR /file/that/doesnt/exist '550 Failed to open file.' ] f.buildProtocol = lambda addr: PrintLines(responses) client = ftp.FTPClient(passive=1) cc = protocol.ClientCreator(reactor, ftp.FTPClient, passive=1) client = wait(cc.connectTCP('127.0.0.1', portNum)) p = protocol.Protocol() d = client.retrieveFile('/file/that/doesnt/exist', p) # This callback should not be called, because we're expecting a # failure. d.addCallback(lambda r, self=self: self.fail( 'Callback incorrectly called: %r' % r)) def p(failure): # Make sure we got the failure we were expecting. failure.trap(ftp.CommandFailed) d.addErrback(p) wait(d) log.flushErrors(ftp.FTPError) finally: d = port.stopListening() if d is not None: wait(d)
def not_test_callAndStartup(self): lapp = TestDougApplication(NullListenApp) lapp.boot(args=['--listenport', '0']) # Now get the port number we actually listened on port = lapp.sipListener.getHost().port lapp._voiceappArgs = {} d = lapp._trial_def = defer.Deferred() s = Saver() d.addCallback(s.save) capp = TestDougApplication(SimpleCallApp) capp.boot(args=['--listenport', '0']) capp._voiceappArgs = {'callURL': 'sip:[email protected]:%d' % port} reactor.callLater(0, capp.startVoiceApp) util.wait(d) self.assertEquals(s.val, 'hello world') lapp.stopSIP() capp.stopSIP()
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 testPORTCannotConnect(self): # Login self._anonymousLogin() # Listen on a port, and immediately stop listening as a way to find a # port number that is definitely closed. port = reactor.listenTCP(0, protocol.Factory(), interface='127.0.0.1') portNum = port.getHost().port d = port.stopListening() if d is not None: wait(d) # Tell the server to connect to that port with a PORT command, and # verify that it fails with the right error. cmd = 'PORT ' + ftp.encodeHostPort('127.0.0.1', portNum) d = self.client.queueStringCommand(cmd) self.failUnlessEqual(["425 Can't open data connection."], self._waitForCommandFailure(d))
def testStackUsage2(self): def _loop(): for x in range(5000): # Test with yielding a random value yield 1 yield 0 _loop = deferredGenerator(_loop) self.assertEquals(util.wait(_loop()), 0)
def _makeDataConnection(self): # Establish an active data connection (i.e. server connecting to # client). deferred = defer.Deferred() class DataFactory(protocol.ServerFactory): protocol = _BufferingProtocol def buildProtocol(self, addr): p = protocol.ServerFactory.buildProtocol(self, addr) reactor.callLater(0, deferred.callback, p) return p dataPort = reactor.listenTCP(0, DataFactory(), interface='127.0.0.1') self.dataPorts.append(dataPort) cmd = 'PORT ' + ftp.encodeHostPort('127.0.0.1', dataPort.getHost().port) responseLines = wait(self.client.queueStringCommand(cmd)) downloader = wait(deferred) return downloader
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 testPASV(self): # Login self._anonymousLogin() # Issue a PASV command, and extract the host and port from the response responseLines = wait(self.client.queueStringCommand('PASV')) host, port = ftp.decodeHostPort(responseLines[-1][4:]) # Make sure the server is listening on the port it claims to be self.assertEqual(port, self.serverProtocol.dtpPort.getHost().port) # Semi-reasonable way to force cleanup self.serverProtocol.connectionLost(error.ConnectionDone())
def testStackUsage(self): # Make sure we don't blow the stack when yielding immediately # available values def _loop(): for x in range(5000): # Test with yielding a deferred x = waitForDeferred(defer.succeed(1)) yield x x = x.getResult() yield 0 _loop = deferredGenerator(_loop) self.assertEquals(util.wait(_loop()), 0)
def test_callStartupAndConnecting(self): lapp = TestDougApplication(SimpleListenApp) lapp.boot(args=['--listenport', '0']) # Now get the port number we actually listened on port = lapp.sipListener.getHost().port lapp._voiceappArgs = {} d1 = lapp._trial_def = defer.Deferred() s1 = Saver() d1.addCallback(s1.save) capp = TestDougApplication(SimpleCallApp) capp.boot(args=['--listenport', '0']) capp._voiceappArgs = {'callURL': 'sip:[email protected]:%d' % port} d2 = capp._trial_def = defer.Deferred() s2 = Saver() d2.addCallback(s2.save) reactor.callLater(0, capp.startVoiceApp) util.wait(d1) util.wait(d2) self.assertEquals(s1.val, 'hello world') self.assertEquals(s2.val, 'completed') lapp.stopSIP() capp.stopSIP()
def _bail(self): from twisted.internet import reactor, utils d = defer.Deferred() reactor.addSystemEventTrigger('after', 'shutdown', lambda: d.callback(None)) reactor.fireSystemEvent('shutdown') # radix's suggestion treactor = interfaces.IReactorThreads(reactor, None) if treactor is not None: treactor.suggestThreadPoolSize(0) # As long as TestCase does crap stuff with the reactor we need to # manually shutdown the reactor here, and that requires util.wait # :( # so that the shutdown event completes utils.suppressWarnings(lambda: util.wait(d), (['ignore', 'Do NOT use wait.*'], {}))