Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_as_future_immediate(framework):
'''
Returning an immediate value from as_future
'''
errors = []
results = []
calls = []
def method(*args, **kw):
calls.append((args, kw))
return 42
f = txaio.as_future(method, 1, 2, 3, key='word')
def cb(x):
results.append(x)
def errback(f):
errors.append(f)
txaio.add_callbacks(f, cb, errback)
run_once()
assert len(results) == 1
assert len(errors) == 0
assert results[0] == 42
assert calls[0] == ((1, 2, 3), dict(key='word'))
def foo():
def codependant(*args, **kw):
calls.append((args, kw))
return 42
return txaio.as_future(codependant)
u" session before"),
)
d = txaio.as_future(self.onLeave, details)
def success(arg):
# XXX also: handle async
self.fire('leave', self, details)
return arg
def _error(e):
return self._swallow_error(e, "While firing onLeave")
txaio.add_callbacks(d, success, _error)
self._session_id = None
d = txaio.as_future(self.onDisconnect)
def success(arg):
# XXX do we care about returning 'arg' properly?
return self.fire('disconnect', self, was_clean=wasClean)
def _error(e):
return self._swallow_error(e, "While firing onDisconnect")
txaio.add_callbacks(d, success, _error)
def component_start(comp):
# the future from start() errbacks if we fail, or callbacks
# when the component is considered "done" (so maybe never)
d = txaio.as_future(comp.start, reactor)
txaio.add_callbacks(
d,
partial(component_success, comp),
partial(component_failure, comp),
)
return d
lambda _: txaio.as_future(self.onJoin, details),
None
def return_arg(_):
return arg
def _error(e):
return self._swallow_error(e, "While firing 'leave' event")
txaio.add_callbacks(d, return_arg, _error)
return d
def _error(e):
return self._swallow_error(e, "While firing onLeave")
txaio.add_callbacks(d, success, _error)
elif isinstance(msg, message.Challenge):
challenge = types.Challenge(msg.method, msg.extra)
d = txaio.as_future(self.onChallenge, challenge)
def success(signature):
if signature is None:
raise Exception('onChallenge user callback did not return a signature')
if type(signature) == six.binary_type:
signature = signature.decode('utf8')
if type(signature) != six.text_type:
raise Exception('signature must be unicode (was {})'.format(type(signature)))
reply = message.Authenticate(signature)
self._transport.send(reply)
def error(err):
self.onUserError(err, "Authentication failed")
reply = message.Abort(u"wamp.error.cannot_authenticate", u"{0}".format(err.value))
self._transport.send(reply)
# fire callback and close the transport
def _success(_):
# Acknowledged Events -- only if we got the details header and
# the broker advertised it
if msg.x_acknowledged_delivery and self._router_roles["broker"].x_acknowledged_event_delivery:
if self._transport:
response = message.EventReceived(msg.publication)
self._transport.send(response)
else:
self.log.warn("successfully processed event with acknowledged delivery, but could not send ACK, since the transport was lost in the meantime")
def _error(e):
errmsg = 'While firing {0} subscribed under {1}.'.format(
handler.fn, msg.subscription)
return self._swallow_error(e, errmsg)
future = txaio.as_future(handler.fn, *invoke_args, **invoke_kwargs)
txaio.add_callbacks(future, _success, _error)
else:
raise ProtocolError("EVENT received for non-subscribed subscription ID {0}".format(msg.subscription))
elif isinstance(msg, message.Published):
if msg.request in self._publish_reqs:
# get and pop outstanding publish request
publish_request = self._publish_reqs.pop(msg.request)
# create a new publication object
publication = Publication(msg.publication, was_encrypted=publish_request.was_encrypted)
# resolve deferred/future for publishing successfully
if not was_clean:
self.log.warn(
u"Session disconnected uncleanly"
)
else:
# eg the session has left the realm, and the transport was properly
# shut down. successfully finish the connection
txaio.resolve(done, None)
session.on('disconnect', on_disconnect)
# return the fresh session object
return session
transport.connect_attempts += 1
d = txaio.as_future(
self._connect_transport,
reactor, transport, create_session, done,
)
def on_error(err):
"""
this may seem redundant after looking at _connect_transport, but
it will handle a case where something goes wrong in
_connect_transport itself -- as the only connect our
caller has is the 'done' future
"""
transport.connect_failures += 1
# something bad has happened, and maybe didn't get caught
# upstream yet
if not txaio.is_called(done):
txaio.reject(done, err)
Fire a particular event.
:param event: the event to fire. All other args and kwargs are
passed on to the handler(s) for the event.
:return: a Deferred/Future gathering all async results from
all handlers and/or parent handlers.
"""
# print("firing '{}' from '{}'".format(event, hash(self)))
if self._listeners is None:
return txaio.create_future(result=[])
self._check_event(event)
res = []
for handler in self._listeners.get(event, []):
future = txaio.as_future(handler, *args, **kwargs)
res.append(future)
if self._parent is not None:
res.append(self._parent.fire(event, *args, **kwargs))
return txaio.gather(res, consume_exceptions=False)
if self._config.get('expose_controller', None):
from crossbar.worker.controller import WorkerController
if not isinstance(self._realm_container, WorkerController):
excp = Exception(
"Internal Error: Our container '{}' is not a WorkerController".format(
self._realm_container,
)
)
self.log.failure('{klass} could not expose controller',
klass=self.__class__.__name__, failure=excp)
raise excp
controller = self._realm_container
else:
controller = None
create_d = txaio.as_future(_authenticator_for_name, self._config, controller=controller)
def got_authenticator(authenticator):
self._authenticator = authenticator
create_d.addCallback(got_authenticator)
return create_d