本文整理汇总了Python中crossbar.router.session.RouterSessionFactory.add方法的典型用法代码示例。如果您正苦于以下问题:Python RouterSessionFactory.add方法的具体用法?Python RouterSessionFactory.add怎么用?Python RouterSessionFactory.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类crossbar.router.session.RouterSessionFactory
的用法示例。
在下文中一共展示了RouterSessionFactory.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_router
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
def make_router(realm_name=u'default'):
"""
Make a router, and return it and a RawSocket factory.
"""
# create a router factory
router_factory = RouterFactory()
# start a realm
realm = RouterRealm(None, {u'name': realm_name})
router = router_factory.start_realm(realm)
extra = {}
session_config = ComponentConfig(realm_name, extra)
realm.session = RouterServiceSession(session_config, router)
# allow everything
default_permissions = {
u'uri': u'',
u'match': u'prefix',
u'allow': {
u'call': True,
u'register': True,
u'publish': True,
u'subscribe': True
}
}
router = router_factory.get(realm_name)
router.add_role(RouterRoleStaticAuth(router, 'anonymous', default_permissions=default_permissions))
# create a router session factory
session_factory = RouterSessionFactory(router_factory)
session_factory.add(realm.session, authrole=u'trusted')
# Create a new RawSocket factory
server_factory = WampRawSocketServerFactory(session_factory, {})
return router, server_factory
示例2: RouterWorkerSession
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
#.........这里部分代码省略.........
if self.debug:
log.msg("{}.get_router_realms".format(self.__class__.__name__))
raise Exception("not implemented")
def start_router_realm(self, id, config, schemas=None, details=None):
"""
Starts a realm managed by this router.
:param id: The ID of the realm to start.
:type id: str
:param config: The realm configuration.
:type config: dict
:param schemas: An (optional) initial schema dictionary to load.
:type schemas: dict
"""
if self.debug:
log.msg("{}.start_router_realm".format(self.__class__.__name__), id, config, schemas)
# URI of the realm to start
realm = config['name']
# track realm
rlm = RouterRealm(id, config)
self.realms[id] = rlm
self.realm_to_id[realm] = id
# create a new router for the realm
router = self._router_factory.start_realm(rlm)
# add a router/realm service session
cfg = ComponentConfig(realm)
rlm.session = RouterServiceSession(cfg, router, schemas)
self._router_session_factory.add(rlm.session, authrole=u'trusted')
def stop_router_realm(self, id, close_sessions=False, details=None):
"""
Stop a router realm.
When a realm has stopped, no new session will be allowed to attach to the realm.
Optionally, close all sessions currently attached to the realm.
:param id: ID of the realm to stop.
:type id: str
:param close_sessions: If `True`, close all session currently attached.
:type close_sessions: bool
"""
if self.debug:
log.msg("{}.stop_router_realm".format(self.__class__.__name__), id, close_sessions)
# FIXME
raise NotImplementedError()
def get_router_realm_roles(self, id, details=None):
"""
:param id: The ID of the router realm to list roles for.
:type id: str
:returns: list -- A list of roles.
"""
if self.debug:
log.msg("{}.get_router_realm_roles".format(self.__class__.__name__), id)
if id not in self.realms:
raise ApplicationError("crossbar.error.no_such_object", "No realm with ID '{}'".format(id))
示例3: Node
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
#.........这里部分代码省略.........
self.log.info("Connected to Crossbar.io DevOps Center (CDC)! Your node runs in managed mode.")
else:
self._manager = None
# in standalone mode, a node - by default - is immediately shutting down whenever
# a worker exits (successfully or with error)
self._node_shutdown_triggers = [checkconfig.NODE_SHUTDOWN_ON_WORKER_EXIT]
# allow to override node shutdown triggers
#
if 'shutdown' in controller_options:
self.log.info("Overriding default node shutdown triggers with {} from node config".format(controller_options['shutdown']))
self._node_shutdown_triggers = controller_options['shutdown']
else:
self.log.info("Using default node shutdown triggers {}".format(self._node_shutdown_triggers))
# router and factory that creates router sessions
#
self._router_factory = RouterFactory(self._node_id)
self._router_session_factory = RouterSessionFactory(self._router_factory)
rlm_config = {
'name': self._realm
}
rlm = RouterRealm(None, rlm_config)
# create a new router for the realm
router = self._router_factory.start_realm(rlm)
# add a router/realm service session
cfg = ComponentConfig(self._realm)
rlm.session = RouterServiceSession(cfg, router)
self._router_session_factory.add(rlm.session, authrole=u'trusted')
if self._manager:
self._bridge_session = NodeManagementBridgeSession(cfg, self, self._manager)
self._router_session_factory.add(self._bridge_session, authrole=u'trusted')
else:
self._bridge_session = None
# the node controller singleton WAMP application session
#
self._controller = NodeControllerSession(self)
# add the node controller singleton session to the router
#
self._router_session_factory.add(self._controller, authrole=u'trusted')
# Detect WAMPlets
#
wamplets = self._controller._get_wamplets()
if len(wamplets) > 0:
self.log.info("Detected {wamplets} WAMPlets in environment:",
wamplets=len(wamplets))
for wpl in wamplets:
self.log.info("WAMPlet {dist}.{name}",
dist=wpl['dist'], name=wpl['name'])
else:
self.log.debug("No WAMPlets detected in enviroment.")
panic = False
try:
yield self._startup(self._config)
示例4: Node
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
#.........这里部分代码省略.........
def load_keys(self, cbdir):
"""
"""
self._node_key = _maybe_generate_key(cbdir)
def load_config(self, configfile=None):
"""
Check and load the node configuration (usually, from ".crossbar/config.json")
or load built-in empty config.
"""
if configfile:
configpath = os.path.abspath(os.path.join(self._cbdir, configfile))
self.log.debug('Loading node configuration from "{configpath}" ..',
configpath=configpath)
# the following will read the config, check the config and replace
# environment variable references in configuration values ("${MYVAR}") and
# finally return the parsed configuration object
self._config = self.personality.check_config_file(self.personality, configpath)
self.log.info('Node configuration loaded from {configpath}',
configpath=hlid(configpath))
else:
self._config = {
u'version': 2,
u'controller': {},
u'workers': []
}
self.personality.check_config(self.personality, self._config)
self.log.info('Node configuration loaded from built-in config.')
def _add_global_roles(self):
self.log.info('No extra node router roles')
def _add_worker_role(self, worker_auth_role, options):
worker_role_config = {
u"name": worker_auth_role,
u"permissions": [
# the worker requires these permissions to work:
{
# worker_auth_role: "crossbar.worker.worker-001"
u"uri": worker_auth_role,
u"match": u"prefix",
u"allow": {
u"call": False,
u"register": True,
u"publish": True,
u"subscribe": False
},
u"disclose": {
u"caller": False,
u"publisher": False
},
u"cache": True
},
{
u"uri": u"crossbar.get_status",
u"match": u"exact",
u"allow": {
u"call": True,
u"register": False,
u"publish": False,
u"subscribe": False
},
示例5: CallerTestCase
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
class CallerTestCase(TestCase):
"""
Unit tests for L{CallerResource}.
"""
def setUp(self):
# create a router factory
self.router_factory = RouterFactory(None, None)
# start a realm
self.realm = RouterRealm(None, {u'name': u'realm1'})
self.router_factory.start_realm(self.realm)
# allow everything
self.router = self.router_factory.get(u'realm1')
self.router.add_role(
RouterRoleStaticAuth(
self.router,
u'test_role',
default_permissions={
u'uri': u'com.myapp.',
u'match': u'prefix',
u'allow': {
u'call': True,
u'register': True,
u'publish': True,
u'subscribe': True,
}
}
)
)
# create a router session factory
self.session_factory = RouterSessionFactory(self.router_factory)
@inlineCallbacks
def test_add2(self):
"""
Test a very basic call where you square root a number. This has one
arg, no kwargs, and no authorisation.
"""
session = TestSession(types.ComponentConfig(u'realm1'))
self.session_factory.add(session, authrole=u"test_role")
session2 = ApplicationSession(types.ComponentConfig(u'realm1'))
self.session_factory.add(session2, authrole=u"test_role")
resource = CallerResource({}, session2)
with LogCapturer() as l:
request = yield renderResource(
resource, b"/",
method=b"POST",
headers={b"Content-Type": [b"application/json"]},
body=b'{"procedure": "com.myapp.sqrt", "args": [2]}')
self.assertEqual(request.code, 200)
self.assertEqual(json.loads(native_string(request.get_written_data())),
{"args": [1.4142135623730951]})
logs = l.get_category("AR202")
self.assertEqual(len(logs), 1)
self.assertEqual(logs[0]["code"], 200)
@inlineCallbacks
def test_failure(self):
"""
A failed call returns the error to the client.
"""
session = TestSession(types.ComponentConfig(u'realm1'))
self.session_factory.add(session, authrole=u"test_role")
session2 = ApplicationSession(types.ComponentConfig(u'realm1'))
self.session_factory.add(session2, authrole=u"test_role")
resource = CallerResource({}, session2)
tests = [
(u"com.myapp.sqrt", (0,),
{u"error": u"wamp.error.runtime_error", u"args": [u"don't ask foolish questions ;)"], u"kwargs": {}}),
(u"com.myapp.checkname", ("foo",),
{u"error": u"com.myapp.error.reserved", u"args": [], u"kwargs": {}}),
(u"com.myapp.checkname", ("*",),
{u"error": u"com.myapp.error.invalid_length", u"args": [], u"kwargs": {"min": 3, "max": 10}}),
(u"com.myapp.checkname", ("hello",),
{u"error": u"com.myapp.error.mixed_case", u"args": ["hello", "HELLO"], u"kwargs": {}}),
(u"com.myapp.compare", (1, 10),
{u"error": u"com.myapp.error1", u"args": [9], u"kwargs": {}}),
]
for procedure, args, err in tests:
with LogCapturer() as l:
request = yield renderResource(
resource, b"/",
method=b"POST",
headers={b"Content-Type": [b"application/json"]},
body=dump_json({"procedure": procedure, "args": args}).encode('utf8'))
self.assertEqual(request.code, 200)
self.assertEqual(json.loads(native_string(request.get_written_data())),
err)
#.........这里部分代码省略.........
示例6: RouterWorkerSession
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
#.........这里部分代码省略.........
raise ApplicationError(u'crossbar.error.already_running', emsg)
# check configuration
#
try:
checkconfig.check_router_realm(config)
except Exception as e:
emsg = "Invalid router realm configuration: {}".format(e)
self.log.error(emsg)
raise ApplicationError(u"crossbar.error.invalid_configuration", emsg)
# URI of the realm to start
realm = config['name']
# track realm
rlm = RouterRealm(id, config)
self.realms[id] = rlm
self.realm_to_id[realm] = id
# create a new router for the realm
router = self._router_factory.start_realm(rlm)
if enable_trace:
router._trace_traffic = True
router._trace_traffic_roles_include = None
router._trace_traffic_roles_exclude = [u'trusted']
self.log.info(">>> Traffic tracing enabled! <<<")
# add a router/realm service session
extra = {
'onready': Deferred()
}
cfg = ComponentConfig(realm, extra)
rlm.session = RouterServiceSession(cfg, router, schemas=schemas)
self._router_session_factory.add(rlm.session, authrole=u'trusted')
yield extra['onready']
self.log.info("Realm '{realm}' started", realm=realm)
def stop_router_realm(self, id, close_sessions=False, details=None):
"""
Stop a realm currently running on this router worker.
When a realm has stopped, no new session will be allowed to attach to the realm.
Optionally, close all sessions currently attached to the realm.
:param id: ID of the realm to stop.
:type id: str
:param close_sessions: If `True`, close all session currently attached.
:type close_sessions: bool
"""
self.log.debug("{}.stop_router_realm".format(self.__class__.__name__),
id=id, close_sessions=close_sessions)
# FIXME
raise NotImplementedError()
def get_router_realm_roles(self, id, details=None):
"""
Get roles currently running on a realm running on this router worker.
:param id: The ID of the realm to list roles for.
:type id: str
:returns: A list of roles.
:rtype: list of dicts
示例7: Node
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
#.........这里部分代码省略.........
return
# get controller config/options
#
controller_config = self._config.get('controller', {})
controller_options = controller_config.get('options', {})
# set controller process title
#
try:
import setproctitle
except ImportError:
self.log.warn("Warning, could not set process title (setproctitle not installed)")
else:
setproctitle.setproctitle(controller_options.get('title', 'crossbar-controller'))
# router and factory that creates router sessions
#
self._router_factory = RouterFactory()
self._router_session_factory = RouterSessionFactory(self._router_factory)
# create a new router for the realm
#
rlm_config = {
'name': self._realm
}
rlm = RouterRealm(None, rlm_config)
router = self._router_factory.start_realm(rlm)
# always add a realm service session
#
cfg = ComponentConfig(self._realm)
rlm.session = RouterServiceSession(cfg, router)
self._router_session_factory.add(rlm.session, authrole=u'trusted')
# add a router bridge session when running in managed mode
#
if cdc_mode:
self._bridge_session = NodeManagementBridgeSession(cfg)
self._router_session_factory.add(self._bridge_session, authrole=u'trusted')
else:
self._bridge_session = None
# Node shutdown mode
#
if cdc_mode:
# in managed mode, a node - by default - only shuts down when explicitly asked to,
# or upon a fatal error in the node controller
self._node_shutdown_triggers = [checkconfig.NODE_SHUTDOWN_ON_SHUTDOWN_REQUESTED]
else:
# in standalone mode, a node - by default - is immediately shutting down whenever
# a worker exits (successfully or with error)
self._node_shutdown_triggers = [checkconfig.NODE_SHUTDOWN_ON_WORKER_EXIT]
# allow to override node shutdown triggers
#
if 'shutdown' in controller_options:
self.log.info("Overriding default node shutdown triggers with {triggers} from node config", triggers=controller_options['shutdown'])
self._node_shutdown_triggers = controller_options['shutdown']
else:
self.log.info("Using default node shutdown triggers {triggers}", triggers=self._node_shutdown_triggers)
# add the node controller singleton session
#
self._controller = NodeControllerSession(self)
self._router_session_factory.add(self._controller, authrole=u'trusted')
示例8: TestEmbeddedSessions
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
class TestEmbeddedSessions(unittest.TestCase):
"""
Test cases for application session running embedded in router.
"""
def setUp(self):
"""
Setup router and router session factories.
"""
# create a router factory
self.router_factory = RouterFactory(u'mynode')
# start a realm
self.router_factory.start_realm(RouterRealm(None, {u'name': u'realm1'}))
# allow everything
default_permissions = {
u'uri': u'',
u'match': u'prefix',
u'call': True,
u'register': True,
u'publish': True,
u'subscribe': True
}
router = self.router_factory.get(u'realm1')
router.add_role(RouterRoleStaticAuth(router, None, default_permissions=default_permissions))
# create a router session factory
self.session_factory = RouterSessionFactory(self.router_factory)
def tearDown(self):
pass
def test_add(self):
"""
Create an application session and add it to a router to
run embedded.
"""
d = txaio.create_future()
class TestSession(ApplicationSession):
def onJoin(self, details):
txaio.resolve(d, None)
session = TestSession(types.ComponentConfig(u'realm1'))
self.session_factory.add(session)
return d
def test_application_session_internal_error(self):
"""
simulate an internal error triggering the 'onJoin' error-case from
_RouterApplicationSession's send() method (from the Hello msg)
"""
# setup
the_exception = RuntimeError("sadness")
errors = []
class TestSession(ApplicationSession):
def onJoin(self, *args, **kw):
raise the_exception
def onUserError(self, *args, **kw):
errors.append((args, kw))
session = TestSession(types.ComponentConfig(u'realm1'))
# in this test, we are just looking for onUserError to get
# called so we don't need to patch the logger. this should
# call onJoin, triggering our error
self.session_factory.add(session)
# check we got the right log.failure() call
self.assertTrue(len(errors) > 0, "expected onUserError call")
fail = errors[0][0][0]
self.assertTrue(fail.value == the_exception)
def test_router_session_internal_error_onHello(self):
"""
similar to above, but during _RouterSession's onMessage handling,
where it calls self.onHello
"""
# setup
transport = mock.MagicMock()
transport.get_channel_id = mock.MagicMock(return_value=b'deadbeef')
the_exception = RuntimeError("kerblam")
def boom(*args, **kw):
raise the_exception
session = self.session_factory() # __call__ on the _RouterSessionFactory
session.onHello = boom
session.onOpen(transport)
msg = message.Hello(u'realm1', dict(caller=role.RoleCallerFeatures()))
# XXX think: why isn't this using _RouterSession.log?
from crossbar.router.session import RouterSession
with mock.patch.object(RouterSession, 'log') as logger:
#.........这里部分代码省略.........
示例9: RouterController
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
#.........这里部分代码省略.........
"""
Called when worker process has joined the node's management realm.
"""
self.log.info('Router worker session for "{worker_id}" joined realm "{realm}" on node router {method}',
realm=self._realm,
worker_id=self._worker_id,
session_id=details.session,
method=hltype(RouterController.onJoin))
yield WorkerController.onJoin(self, details, publish_ready=False)
# WorkerController.publish_ready()
self.publish_ready()
self.log.info('Router worker session for "{worker_id}" ready',
worker_id=self._worker_id)
def onLeave(self, details):
# when this router is shutting down, we disconnect all our
# components so that they have a chance to shutdown properly
# -- e.g. on a ctrl-C of the router.
leaves = []
if self.components:
for component in self.components.values():
if component.session.is_connected():
d = maybeDeferred(component.session.leave)
def done(_):
self.log.info(
"component '{id}' disconnected",
id=component.id,
)
component.session.disconnect()
d.addCallback(done)
leaves.append(d)
dl = DeferredList(leaves, consumeErrors=True)
# we want our default behavior, which disconnects this
# router-worker, effectively shutting it down .. but only
# *after* the components got a chance to shutdown.
dl.addBoth(lambda _: super(RouterController, self).onLeave(details))
@wamp.register(None)
def get_router_realms(self, details=None):
"""
Get realms currently running on this router worker.
:param details: Call details.
:type details: autobahn.wamp.types.CallDetails
:returns: List of realms currently running.
:rtype: list of str
"""
self.log.debug("{name}.get_router_realms", name=self.__class__.__name__)
return sorted(self.realms.keys())
@wamp.register(None)
def get_router_realm(self, realm_id, details=None):
"""
Return realm detail information.
:param details: Call details.
:type details: autobahn.wamp.types.CallDetails
:returns: realm information object
:rtype: dict
示例10: __init__
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
class Node:
"""
A Crossbar.io node is the running a controller process
and one or multiple worker processes.
A single Crossbar.io node runs exactly one instance of
this class, hence this class can be considered a system
singleton.
"""
def __init__(self, reactor, options):
"""
Ctor.
:param reactor: Reactor to run on.
:type reactor: obj
:param options: Options from command line.
:type options: obj
"""
self.debug = False
self.options = options
# the reactor under which we run
self._reactor = reactor
# shortname for reactor to run (when given via explicit option) or None
self._reactor_shortname = options.reactor
# node directory
self._cbdir = options.cbdir
# the node's name (must be unique within the management realm)
self._node_id = None
# the node's management realm
self._realm = None
# node controller session (a singleton ApplicationSession embedded
# in the node's management router)
self._controller = None
def start(self):
"""
Starts this node. This will start a node controller and then spawn new worker
processes as needed.
"""
# for now, a node is always started from a local configuration
#
configfile = os.path.join(self.options.cbdir, self.options.config)
log.msg("Starting from local configuration '{}'".format(configfile))
config = check_config_file(configfile, silence=True)
self.start_from_config(config)
def start_from_config(self, config):
controller_config = config.get('controller', {})
controller_options = controller_config.get('options', {})
controller_title = controller_options.get('title', 'crossbar-controller')
try:
import setproctitle
except ImportError:
log.msg("Warning, could not set process title (setproctitle not installed)")
else:
setproctitle.setproctitle(controller_title)
# the node's name (must be unique within the management realm)
if 'id' in controller_config:
self._node_id = controller_config['id']
else:
self._node_id = socket.gethostname()
# the node's management realm
self._realm = controller_config.get('realm', 'crossbar')
# the node controller singleton WAMP application session
#
# session_config = ComponentConfig(realm = options.realm, extra = options)
self._controller = NodeControllerSession(self)
# router and factory that creates router sessions
#
self._router_factory = RouterFactory(
options=RouterOptions(uri_check=RouterOptions.URI_CHECK_LOOSE),
debug=True)
self._router_session_factory = RouterSessionFactory(self._router_factory)
# add the node controller singleton session to the router
#
self._router_session_factory.add(self._controller)
# Detect WAMPlets
#
wamplets = self._controller._get_wamplets()
if len(wamplets) > 0:
#.........这里部分代码省略.........
示例11: TestBrokerPublish
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
class TestBrokerPublish(unittest.TestCase):
"""
Tests for crossbar.router.broker.Broker
"""
def setUp(self):
"""
Setup router and router session factories.
"""
# create a router factory
self.router_factory = RouterFactory(None, None)
# start a realm
self.realm = RouterRealm(None, {u'name': u'realm1'})
self.router_factory.start_realm(self.realm)
# allow everything
self.router = self.router_factory.get(u'realm1')
self.router.add_role(
RouterRoleStaticAuth(
self.router,
u'test_role',
default_permissions={
u'uri': u'com.example.',
u'match': u'prefix',
u'allow': {
u'call': True,
u'register': True,
u'publish': True,
u'subscribe': True,
}
}
)
)
# create a router session factory
self.session_factory = RouterSessionFactory(self.router_factory)
def tearDown(self):
pass
def test_add(self):
"""
Create an application session and add it to a router to
run embedded.
"""
d = txaio.create_future()
class TestSession(ApplicationSession):
def onJoin(self, details):
txaio.resolve(d, None)
session = TestSession(types.ComponentConfig(u'realm1'))
self.session_factory.add(session)
return d
def test_application_session_internal_error(self):
"""
simulate an internal error triggering the 'onJoin' error-case from
RouterApplicationSession's send() method (from the Hello msg)
"""
# setup
the_exception = RuntimeError("sadness")
errors = []
class TestSession(ApplicationSession):
def onJoin(self, *args, **kw):
raise the_exception
def onUserError(self, fail, msg):
errors.append((fail, msg))
session = TestSession(types.ComponentConfig(u'realm1'))
from crossbar.router.session import RouterApplicationSession
# Note to self: original code was logging directly in
# RouterApplicationSession -- which *may* actually be better?
# or not...
with mock.patch.object(RouterApplicationSession, 'log') as logger:
# this should call onJoin, triggering our error
self.session_factory.add(session)
if True:
self.assertEqual(1, len(errors), "Didn't see our error")
self.assertEqual(the_exception, errors[0][0].value)
else:
# check we got the right log.failure() call
self.assertTrue(len(logger.method_calls) > 0)
call = logger.method_calls[0]
# for a MagicMock call-object, 0th thing is the method-name, 1st
# thing is the arg-tuple, 2nd thing is the kwargs.
self.assertEqual(call[0], 'failure')
self.assertEqual(call[1][0].value, the_exception)
def test_router_session_internal_error_onHello(self):
#.........这里部分代码省略.........
示例12: TestEmbeddedSessions
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
class TestEmbeddedSessions(unittest.TestCase):
"""
Test cases for application session running embedded in router.
"""
def setUp(self):
"""
Setup router and router session factories.
"""
# create a router factory
self.router_factory = RouterFactory()
# start a realm
self.router_factory.start_realm(RouterRealm(None, {u'name': u'realm1'}))
# allow everything
permissions = RouterPermissions('', True, True, True, True, True)
router = self.router_factory.get(u'realm1')
router.add_role(RouterRoleStaticAuth(router, None, default_permissions=permissions))
# create a router session factory
self.session_factory = RouterSessionFactory(self.router_factory)
def tearDown(self):
pass
def test_add(self):
"""
Create an application session and add it to a router to
run embedded.
"""
d = txaio.create_future()
class TestSession(ApplicationSession):
def onJoin(self, details):
txaio.resolve(d, None)
session = TestSession(types.ComponentConfig(u'realm1'))
self.session_factory.add(session)
return d
def test_add_and_subscribe(self):
"""
Create an application session that subscribes to some
topic and add it to a router to run embedded.
"""
d = txaio.create_future()
class TestSession(ApplicationSession):
def onJoin(self, details):
# noinspection PyUnusedLocal
def on_event(*arg, **kwargs):
pass
d2 = self.subscribe(on_event, u'com.example.topic1')
def ok(_):
txaio.resolve(d, None)
def error(err):
txaio.reject(d, err)
txaio.add_callbacks(d2, ok, error)
session = TestSession(types.ComponentConfig(u'realm1'))
self.session_factory.add(session)
return d
示例13: TestEmbeddedSessions
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
class TestEmbeddedSessions(unittest.TestCase):
"""
Test cases for application session running embedded in router.
"""
def setUp(self):
"""
Setup router and router session factories.
"""
# create a router factory
self.router_factory = RouterFactory()
# start a realm
self.router_factory.start_realm(RouterRealm(None, {u"name": u"realm1"}))
# allow everything
permissions = RouterPermissions("", True, True, True, True, True)
router = self.router_factory.get(u"realm1")
router.add_role(RouterRoleStaticAuth(router, None, default_permissions=permissions))
# create a router session factory
self.session_factory = RouterSessionFactory(self.router_factory)
def tearDown(self):
pass
def test_add(self):
"""
Create an application session and add it to a router to
run embedded.
"""
d = txaio.create_future()
class TestSession(ApplicationSession):
def onJoin(self, details):
txaio.resolve(d, None)
session = TestSession(types.ComponentConfig(u"realm1"))
self.session_factory.add(session)
return d
def test_application_session_internal_error(self):
"""
simulate an internal error triggering the 'onJoin' error-case from
_RouterApplicationSession's send() method (from the Hello msg)
"""
# setup
the_exception = RuntimeError("sadness")
class TestSession(ApplicationSession):
def onJoin(self, *args, **kw):
raise the_exception
session = TestSession(types.ComponentConfig(u"realm1"))
from crossbar.router.session import _RouterApplicationSession
# execute, first patching-out the logger so we can see that
# log.failure() was called when our exception triggers.
with mock.patch.object(_RouterApplicationSession, "log") as logger:
# this should call onJoin, triggering our error
self.session_factory.add(session)
# check we got the right log.failure() call
self.assertTrue(len(logger.method_calls) > 0)
call = logger.method_calls[0]
# for a MagicMock call-object, 0th thing is the method-name, 1st
# thing is the arg-tuple, 2nd thing is the kwargs.
self.assertEqual(call[0], "failure")
self.assertTrue("failure" in call[2])
self.assertEqual(call[2]["failure"].value, the_exception)
def test_router_session_internal_error_onHello(self):
"""
similar to above, but during _RouterSession's onMessage handling,
where it calls self.onHello
"""
# setup
transport = mock.MagicMock()
the_exception = RuntimeError("kerblam")
def boom(*args, **kw):
raise the_exception
session = self.session_factory() # __call__ on the _RouterSessionFactory
session.onHello = boom
session.onOpen(transport)
msg = message.Hello(u"realm1", dict(caller=role.RoleCallerFeatures()))
# XXX think: why isn't this using _RouterSession.log?
from crossbar.router.session import RouterSession
with mock.patch.object(RouterSession, "log") as logger:
# do the test; should call onHello which is now "boom", above
session.onMessage(msg)
# check we got the right log.failure() call
#.........这里部分代码省略.........
示例14: RouterWorkerSession
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
#.........这里部分代码省略.........
List realms currently managed by this router.
"""
self.log.debug("{}.get_router_realms".format(self.__class__.__name__))
raise Exception("not implemented")
def start_router_realm(self, id, config, schemas=None, details=None):
"""
Starts a realm managed by this router.
:param id: The ID of the realm to start.
:type id: str
:param config: The realm configuration.
:type config: dict
:param schemas: An (optional) initial schema dictionary to load.
:type schemas: dict
"""
self.log.debug("{}.start_router_realm".format(self.__class__.__name__), id=id, config=config, schemas=schemas)
# URI of the realm to start
realm = config["name"]
# track realm
rlm = RouterRealm(id, config)
self.realms[id] = rlm
self.realm_to_id[realm] = id
# create a new router for the realm
router = self._router_factory.start_realm(rlm)
# add a router/realm service session
cfg = ComponentConfig(realm)
rlm.session = RouterServiceSession(cfg, router, schemas)
self._router_session_factory.add(rlm.session, authrole=u"trusted")
def stop_router_realm(self, id, close_sessions=False, details=None):
"""
Stop a router realm.
When a realm has stopped, no new session will be allowed to attach to the realm.
Optionally, close all sessions currently attached to the realm.
:param id: ID of the realm to stop.
:type id: str
:param close_sessions: If `True`, close all session currently attached.
:type close_sessions: bool
"""
self.log.debug("{}.stop_router_realm".format(self.__class__.__name__), id=id, close_sessions=close_sessions)
# FIXME
raise NotImplementedError()
def get_router_realm_roles(self, id, details=None):
"""
:param id: The ID of the router realm to list roles for.
:type id: str
:returns: list -- A list of roles.
"""
self.log.debug("{}.get_router_realm_roles".format(self.__class__.__name__), id=id)
if id not in self.realms:
raise ApplicationError(u"crossbar.error.no_such_object", "No realm with ID '{}'".format(id))
return self.realms[id].roles.values()
示例15: TestEmbeddedSessions
# 需要导入模块: from crossbar.router.session import RouterSessionFactory [as 别名]
# 或者: from crossbar.router.session.RouterSessionFactory import add [as 别名]
class TestEmbeddedSessions(unittest.TestCase):
"""
Test cases for application session running embedded in router.
"""
def setUp(self):
"""
Setup router and router session factories.
"""
self.router_factory = RouterFactory()
self.session_factory = RouterSessionFactory(self.router_factory)
def tearDown(self):
pass
def test_add(self):
"""
Create an application session and add it to a router to
run embedded.
"""
d = FutureMixin._create_future()
class TestSession(ApplicationSession):
def onJoin(self, details):
FutureMixin._resolve_future(d, None)
session = TestSession(types.ComponentConfig(u"realm1"))
self.session_factory.add(session)
return d
def test_add_and_subscribe(self):
"""
Create an application session that subscribes to some
topic and add it to a router to run embedded.
"""
d = FutureMixin._create_future()
class TestSession(ApplicationSession):
def onJoin(self, details):
# noinspection PyUnusedLocal
def on_event(*arg, **kwargs):
pass
d2 = self.subscribe(on_event, u"com.example.topic1")
def ok(_):
FutureMixin._resolve_future(d, None)
def error(err):
FutureMixin._reject_future(d, err)
FutureMixin._add_future_callbacks(d2, ok, error)
session = TestSession(types.ComponentConfig(u"realm1"))
self.session_factory.add(session)
return d