def _start_run(self, config, app, stdout_expected, stderr_expected, end_on): with open(self.config, "wb") as f: f.write(json.dumps(config, ensure_ascii=False).encode('utf8')) with open(self.code_location + "/myapp.py", "w") as f: f.write(app) reactor = SelectReactor() make_lc(self, reactor, end_on) # In case it hard-locks reactor.callLater(self._subprocess_timeout, reactor.stop) cli.run("crossbar", ["start", "--cbdir={}".format(self.cbdir), "--logformat=syslogd"], reactor=reactor) for i in stdout_expected: self.assertIn(i, self.stdout.getvalue()) for i in stderr_expected: self.assertIn(i, self.stderr.getvalue())
def _start_run(self, config, app, stdout_expected, stderr_expected, end_on): with open(self.config, "wb") as f: f.write(json.dumps(config, ensure_ascii=False).encode("utf8")) with open(self.code_location + "/myapp.py", "w") as f: f.write(app) reactor = SelectReactor() make_lc(self, reactor, end_on) # In case it hard-locks reactor.callLater(self._subprocess_timeout, reactor.stop) cli.run("crossbar", ["start", "--cbdir={}".format(self.cbdir), "--logformat=syslogd"], reactor=reactor) out = self.stdout.getvalue() err = self.stderr.getvalue() for i in stdout_expected: if i not in out: self.fail(u"Error: '{}' not in:\n{}".format(i, out)) for i in stderr_expected: if i not in err: self.fail(u"Error: '{}' not in:\n{}".format(i, err))
def test_hello(self): def _check(lc, reactor): if "published to 'oncounter'" in self.stdout.getvalue(): lc.stop() try: reactor.stop() except: pass appdir = self.mktemp() cbdir = os.path.join(appdir, ".crossbar") reactor = SelectReactor() cli.run("crossbar", ["init", "--appdir={}".format(appdir), "--template=hello:python"], reactor=reactor) self.assertIn("Application template initialized", self.stdout.getvalue()) reactor = SelectReactor() make_lc(self, reactor, _check) # In case it hard-locks reactor.callLater(self._subprocess_timeout, reactor.stop) cli.run("crossbar", ["start", "--cbdir={}".format(cbdir.path), "--logformat=syslogd"], reactor=reactor) stdout_expected = ["published to 'oncounter'"] for i in stdout_expected: self.assertIn(i, self.stdout.getvalue())
def _start_run(self, config, app, stdout_expected, stderr_expected, end_on): with open(self.config, "wb") as f: f.write(json.dumps(config, ensure_ascii=False).encode('utf8')) with open(self.code_location + "/myapp.py", "w") as f: f.write(app) reactor = SelectReactor() make_lc(self, reactor, end_on) # In case it hard-locks reactor.callLater(self._subprocess_timeout, reactor.stop) main.main("crossbar", ["start", "--cbdir={}".format(self.cbdir), "--logformat=syslogd"], reactor=reactor) out = self.stdout.getvalue() err = self.stderr.getvalue() for i in stdout_expected: if i not in out: self.fail("Error: '{}' not in:\n{}".format(i, out)) for i in stderr_expected: if i not in err: self.fail("Error: '{}' not in:\n{}".format(i, err))
def test_threads(self): """ A basic WSGI app can be ran, with subresources """ temp_reactor = SelectReactor() r = router.RouterWorkerSession(config=self.config, reactor=temp_reactor) # Open the transport transport = FakeWAMPTransport(r) r.onOpen(transport) realm_config = {u"name": u"realm1", u'roles': []} threads = 20 r.start_router_realm("realm1", realm_config) r.start_router_transport( "component1", { u"type": u"web", u"endpoint": { u"type": u"tcp", u"port": 8080 }, u"paths": { u"/": { "module": u"crossbar.worker.test.test_router", "object": u"sleep", "type": u"wsgi", "maxthreads": threads, } } }) deferreds = [] results = [] for i in range(threads): d = treq.get("http://localhost:8080/", reactor=temp_reactor) d.addCallback(treq.content) d.addCallback(results.append) deferreds.append(d) def done(_): max_concurrency = max([int(x) for x in results]) assert max_concurrency == threads, "Maximum concurrency was %s, not %s" % ( max_concurrency, threads) temp_reactor.stop() defer.DeferredList(deferreds).addCallback(done) def escape(): if temp_reactor.running: temp_reactor.stop() temp_reactor.callLater(1, escape) temp_reactor.run()
def test_root_not_required(self): """ Not including a '/' path will mean that path has a 404, but children will still be routed correctly. """ temp_reactor = SelectReactor() r = router.RouterWorkerSession(config=self.config, reactor=temp_reactor) # Open the transport transport = FakeWAMPTransport(r) r.onOpen(transport) realm_config = {u"name": u"realm1", u'roles': []} # Make a file self.cbdir.child('file.txt').setContent(b"hello!") r.start_router_realm("realm1", realm_config) r.start_router_transport( "component1", { u"type": u"web", u"endpoint": { u"type": u"tcp", u"port": 8080 }, u"paths": { u"static": { "directory": self.cbdir.asTextMode().path, "type": u"static" } } }) # Make a request to the WSGI app. d1 = treq.get("http://localhost:8080/", reactor=temp_reactor) d1.addCallback(lambda resp: self.assertEqual(resp.code, 404)) d2 = treq.get("http://localhost:8080/static/file.txt", reactor=temp_reactor) d2.addCallback(treq.content) d2.addCallback(self.assertEqual, b"hello!") def done(results): for item in results: if not item[0]: raise item[1] d = defer.DeferredList([d1, d2]) d.addCallback(done) d.addCallback(lambda _: temp_reactor.stop()) def escape(): if temp_reactor.running: temp_reactor.stop() temp_reactor.callLater(1, escape) temp_reactor.run()
def test_basic_subresources(self): """ A basic WSGI app can be ran, with subresources """ temp_reactor = SelectReactor() r = router.RouterWorkerSession(config=self.config, reactor=temp_reactor) # Open the transport transport = FakeWAMPTransport(r) r.onOpen(transport) realm_config = { u"name": u"realm1", u'roles': [] } r.start_router_realm(u"realm1", realm_config) r.start_router_transport( "component1", { u"type": u"web", u"endpoint": { u"type": u"tcp", u"port": 8080 }, u"paths": { u"/": { "module": u"crossbar.worker.test.test_router", "object": u"hello", "type": u"wsgi" }, u"json": { "type": u"json", "value": {} } } }) # Make a request to the /json endpoint, which is technically a child of # the WSGI app, but is not served by WSGI. d = treq.get("http://localhost:8080/json", reactor=temp_reactor) d.addCallback(treq.content) d.addCallback(self.assertEqual, b"{}") d.addCallback(lambda _: temp_reactor.stop()) def escape(): if temp_reactor.running: temp_reactor.stop() temp_reactor.callLater(1, escape) temp_reactor.run() return d
def test_basic(self): """ A basic WSGI app can be ran. """ temp_reactor = SelectReactor() r = router.RouterController(config=self.config, reactor=temp_reactor) # Open the transport transport = FakeWAMPTransport(r) r.onOpen(transport) realm_config = { u"name": u"realm1", u'roles': [] } r.start_router_realm(u"realm1", realm_config) r.start_router_transport( u"component1", { u"type": u"web", u"endpoint": { u"type": u"tcp", u"port": 8080 }, u"paths": { u"/": { "module": u"crossbar.worker.test.test_router", "object": u"hello", "type": u"wsgi" } } }) # Make a request to the WSGI app. d = treq.get("http://localhost:8080/", reactor=temp_reactor) d.addCallback(treq.content) d.addCallback(self.assertEqual, b"hello!") d.addCallback(lambda _: temp_reactor.stop()) def escape(): if temp_reactor.running: temp_reactor.stop() temp_reactor.callLater(1, escape) temp_reactor.run() return d
def reactor(): timeout_secs = 3 # We want a reactor that works on all platforms. from twisted.internet.selectreactor import SelectReactor r = SelectReactor() d = {'forced': False} # No `nonlocal` in Python 2 def force_stop(): d['forced'] = True r.stop() r.callLater(timeout_secs, force_stop) yield r if d['forced']: pytest.fail( 'Test did not stop reactor within {} secs'.format(timeout_secs))
class ReactorSlaveController(object): def __init__(self): self.keepGoing = True self.reactor = SelectReactor() installReactor(self.reactor) connection = self.reactor.connectTCP('localhost', 8000, factory) self.reactor.startRunning() self.futureCall = None self.futureCallTimeout = None pygame_test.prepare() def iterate(self): print 'in iterate' self.reactor.runUntilCurrent() self.reactor.doIteration(0) #t2 = self.reactor.timeout() #print 'timeout', t2 #t = self.reactor.running and t2 #self.reactor.doIteration(t) def run(self): clock = pygame.time.Clock() self.reactor.callLater(20, stupidTest) while self.keepGoing: timeChange = clock.tick(FRAMES_PER_SECOND) if self.futureCall: self.futureCallTimeout -= timeChange print 'future call in', self.futureCallTimeout if self.futureCallTimeout <= 0: self.futureCall() self.futureCallTimeout = None self.futureCall= None retval = pygame_test.iterate() if retval == False: thingInControl.stop() self.iterate() def stop(self): print 'stopping' self.reactor.stop() self.keepGoing = False def callLater(self, when, fn): self.futureCallTimeout = when*1000 self.futureCall = fn print 'future call in', self.futureCallTimeout
def test_basic(self): """ A basic WSGI app can be ran. """ temp_reactor = SelectReactor() r = router.RouterWorkerSession(config=self.config, reactor=temp_reactor) # Open the transport transport = FakeWAMPTransport(r) r.onOpen(transport) realm_config = {u"name": u"realm1", u'roles': []} r.start_router_realm("realm1", realm_config) r.start_router_transport( "component1", { u"type": u"web", u"endpoint": { u"type": u"tcp", u"port": 8080 }, u"paths": { u"/": { "module": u"crossbar.worker.test.test_router", "object": u"hello", "type": u"wsgi" } } }) # Make a request to the WSGI app. d = treq.get("http://localhost:8080/", reactor=temp_reactor) d.addCallback(treq.content) d.addCallback(self.assertEqual, b"hello!") d.addCallback(lambda _: temp_reactor.stop()) def escape(): if temp_reactor.running: temp_reactor.stop() temp_reactor.callLater(1, escape) temp_reactor.run() return d
def test_hello(self): def _check(lc, reactor): if "published to 'oncounter'" in self.stdout.getvalue(): lc.stop() try: reactor.stop() except: pass appdir = self.mktemp() cbdir = os.path.join(appdir, ".crossbar") reactor = SelectReactor() main.main("crossbar", ["init", "--appdir={}".format(appdir), "--template=hello:python"], reactor=reactor) self.assertIn("Application template initialized", self.stdout.getvalue()) reactor = SelectReactor() make_lc(self, reactor, _check) # In case it hard-locks reactor.callLater(self._subprocess_timeout, reactor.stop) main.main("crossbar", ["start", "--cbdir={}".format(cbdir.path), "--logformat=syslogd"], reactor=reactor) stdout_expected = ["published to 'oncounter'"] for i in stdout_expected: self.assertIn(i, self.stdout.getvalue())
def _test_start_run(self): """ A basic start, that enters the reactor. """ code_location = os.path.abspath(self.mktemp()) os.mkdir(code_location) with open(self.config, "w") as f: f.write("""{ "controller": { }, "workers": [ { "type": "router", "options": { "pythonpath": ["."] }, "realms": [ { "name": "realm1", "roles": [ { "name": "anonymous", "permissions": [ { "uri": "*", "publish": true, "subscribe": true, "call": true, "register": true } ] } ] } ], "transports": [ { "type": "web", "endpoint": { "type": "tcp", "port": 8080 }, "paths": { "/": { "directory": ".", "type": "static" }, "ws": { "type": "websocket" } } } ] }, { "type": "container", "options": { "pythonpath": ["%s"] }, "components": [ { "type": "class", "classname": "test.AppSession", "realm": "realm1", "transport": { "type": "websocket", "endpoint": { "type": "tcp", "host": "127.0.0.1", "port": 8080 }, "url": "ws://127.0.0.1:8080/ws" } } ] } ] } """ % ("/".join(code_location.split(os.sep), ))) with open(code_location + "/test.py", "w") as f: f.write("""#!/usr/bin/env python from twisted.internet.defer import inlineCallbacks from twisted.logger import Logger from autobahn.twisted.wamp import ApplicationSession from autobahn.wamp.exception import ApplicationError class AppSession(ApplicationSession): log = Logger() @inlineCallbacks def onJoin(self, details): self.log.info("Loaded the component!") yield self.publish("com.bar", "test") """) reactor = SelectReactor() def _check(lc): if "Loaded the component!" in self.stdout.getvalue(): if reactor.running: reactor.stop() lc.stop() lc = LoopingCall(_check) lc.a = (lc, ) lc.clock = reactor # In case it hard-locks reactor.callLater(self._subprocess_timeout, reactor.stop) lc.start(0.1) cli.run( "crossbar", ["start", "--cbdir={}".format(self.cbdir), "--logformat=syslogd"], reactor=reactor) self.assertIn("Entering reactor event loop", self.stdout.getvalue()) self.assertIn("Loaded the component!", self.stdout.getvalue())
def test_root_not_required(self): """ Not including a '/' path will mean that path has a 404, but children will still be routed correctly. """ temp_reactor = SelectReactor() r = router.RouterWorkerSession(config=self.config, reactor=temp_reactor) # Open the transport transport = FakeWAMPTransport(r) r.onOpen(transport) realm_config = { u"name": u"realm1", u'roles': [] } # Make a file with open(os.path.join(self.cbdir, 'file.txt'), "wb") as f: f.write(b"hello!") r.start_router_realm(u"realm1", realm_config) r.start_router_transport( u"component1", { u"type": u"web", u"endpoint": { u"type": u"tcp", u"port": 8080 }, u"paths": { u"static": { u"directory": u".", u"type": u"static" } } }) d1 = treq.get("http://localhost:8080/", reactor=temp_reactor) d1.addCallback(lambda resp: self.assertEqual(resp.code, 404)) d2 = treq.get("http://localhost:8080/static/file.txt", reactor=temp_reactor) d2.addCallback(treq.content) d2.addCallback(self.assertEqual, b"hello!") def done(results): for item in results: if not item[0]: return item[1] d = defer.DeferredList([d1, d2]) d.addCallback(done) d.addCallback(lambda _: temp_reactor.stop()) def escape(): if temp_reactor.running: temp_reactor.stop() temp_reactor.callLater(1, escape) temp_reactor.run()
def _test_start_run(self): """ A basic start, that enters the reactor. """ code_location = os.path.abspath(self.mktemp()) os.mkdir(code_location) with open(self.config, "w") as f: f.write("""{ "controller": { }, "workers": [ { "type": "router", "options": { "pythonpath": ["."] }, "realms": [ { "name": "realm1", "roles": [ { "name": "anonymous", "permissions": [ { "uri": "*", "publish": true, "subscribe": true, "call": true, "register": true } ] } ] } ], "transports": [ { "type": "web", "endpoint": { "type": "tcp", "port": 8080 }, "paths": { "/": { "directory": ".", "type": "static" }, "ws": { "type": "websocket" } } } ] }, { "type": "container", "options": { "pythonpath": ["%s"] }, "components": [ { "type": "class", "classname": "test.AppSession", "realm": "realm1", "transport": { "type": "websocket", "endpoint": { "type": "tcp", "host": "127.0.0.1", "port": 8080 }, "url": "ws://127.0.0.1:8080/ws" } } ] } ] } """ % ("/".join(code_location.split(os.sep),))) with open(code_location + "/test.py", "w") as f: f.write("""#!/usr/bin/env python from twisted.internet.defer import inlineCallbacks from twisted.logger import Logger from autobahn.twisted.wamp import ApplicationSession from autobahn.wamp.exception import ApplicationError class AppSession(ApplicationSession): log = Logger() @inlineCallbacks def onJoin(self, details): self.log.info("Loaded the component!") yield self.publish("com.bar", "test") """) reactor = SelectReactor() def _check(lc): if "Loaded the component!" in self.stdout.getvalue(): if reactor.running: reactor.stop() lc.stop() lc = LoopingCall(_check) lc.a = (lc,) lc.clock = reactor # In case it hard-locks reactor.callLater(self._subprocess_timeout, reactor.stop) lc.start(0.1) cli.run("crossbar", ["start", "--cbdir={}".format(self.cbdir), "--logformat=syslogd"], reactor=reactor) self.assertIn("Entering reactor event loop", self.stdout.getvalue()) self.assertIn("Loaded the component!", self.stdout.getvalue())
def test_threads(self): """ A basic WSGI app can be ran, with subresources """ temp_reactor = SelectReactor() r = router.RouterWorkerSession(config=self.config, reactor=temp_reactor) # Open the transport transport = FakeWAMPTransport(r) r.onOpen(transport) realm_config = { u"name": u"realm1", u'roles': [] } threads = 20 r.start_router_realm("realm1", realm_config) r.start_router_transport( "component1", { u"type": u"web", u"endpoint": { u"type": u"tcp", u"port": 8080 }, u"paths": { u"/": { "module": u"crossbar.worker.test.test_router", "object": u"sleep", "type": u"wsgi", "maxthreads": threads, } } }) deferreds = [] results = [] for i in range(threads): d = treq.get("http://localhost:8080/", reactor=temp_reactor) d.addCallback(treq.content) d.addCallback(results.append) deferreds.append(d) def done(_): max_concurrency = max([int(x) for x in results]) assert max_concurrency == threads, "Maximum concurrency was %s, not %s" % (max_concurrency, threads) temp_reactor.stop() defer.DeferredList(deferreds).addCallback(done) def escape(): if temp_reactor.running: temp_reactor.stop() temp_reactor.callLater(1, escape) temp_reactor.run()