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_container_doesnt_exhaust_max_workers(container):
spam_called = Event()
spam_continue = Event()
class Service(object):
name = 'max-workers'
@foobar
def spam(self, a):
spam_called.send(a)
spam_continue.wait()
container = ServiceContainer(Service, config={MAX_WORKERS_CONFIG_KEY: 1})
dep = get_extension(container, Entrypoint)
# start the first worker, which should wait for spam_continue
container.spawn_worker(dep, ['ham'], {})
# start the next worker in a speparate thread,
# because it should block until the first one completed
gt = spawn(container.spawn_worker, dep, ['eggs'], {})
with Timeout(1):
assert spam_called.wait() == 'ham'
# if the container had spawned the second worker, we would see
# an error indicating that spam_called was fired twice, and the
# greenthread would now be dead.
assert not gt.dead
# reset the calls and allow the waiting worker to complete.
spam_called.reset()
def test_entrypoint_str():
container = Mock()
container.service_name = "sérvice"
ext = Entrypoint()
assert str(ext).startswith('
def __eq__(self, other):
return isinstance(self.cls, type) and isinstance(other, self.cls)
def __ne__(self, other):
return not (self == other)
def __repr__(self):
obj = getattr(self.cls, '__name__', self.cls)
return ''.format(obj)
ANY_PARTIAL = AnyInstanceOf(partial)
class DummyProvider(Entrypoint):
def __init__(self, method_name=None):
self.method_name = method_name
def get_rabbit_connections(vhost, rabbit_manager):
connections = rabbit_manager.get_connections()
if connections is not None:
return [connection for connection in connections
if connection['vhost'] == vhost]
return []
def reset_rabbit_connections(vhost, rabbit_manager):
for connection in get_rabbit_connections(vhost, rabbit_manager):
import pytest
from nameko.extensions import (
Extension, SharedExtension, Entrypoint, InjectionProvider,
ProviderCollector)
class SharedProvider(SharedExtension):
pass
class NestedProvider(Extension):
pass
class FooProvider(Entrypoint):
shared_provider = SharedProvider()
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
foobar = FooProvider.entrypoint
class BarProvider(InjectionProvider):
nested_provider = NestedProvider()
shared_provider = SharedProvider()
def __init__(self, *args, **kwargs):
res = result.get()
# with custom timeout
with entrypoint_waiter(container, 'handle_event', timeout=5):
... # action that dispatches event
# with `callback` that waits until entrypoint stops raising
def callback(args, kwargs, result, exc_info):
if exc_info is None:
return True
with entrypoint_waiter(container, 'handle_event', callback=callback):
... # action that dispatches event
"""
if not get_extension(container, Entrypoint, method_name=method_name):
raise RuntimeError("{} has no entrypoint `{}`".format(
container.service_name, method_name))
class Result(WaitResult):
worker_ctx = None
def send(self, worker_ctx, res, exc_info):
self.worker_ctx = worker_ctx
super(Result, self).send(res, exc_info)
result = Result()
def on_worker_result(worker_ctx, res, exc_info):
complete = False
if worker_ctx.entrypoint.method_name == method_name:
if callable(worker_callback):
self.args = args
self.kwargs = kwargs
super(Once, self).__init__(
expected_exceptions=expected_exceptions,
sensitive_arguments=sensitive_arguments,
sensitive_variables=sensitive_variables
)
def start(self):
self.container.spawn_worker(self, self.args, self.kwargs)
once = Once.decorator
# dummy entrypoint
dummy = Entrypoint.decorator
from logging import getLogger
import six
from eventlet.event import Event
from werkzeug.routing import Rule
from werkzeug.wrappers import Response
from nameko.exceptions import BadRequest, serialize
from nameko.extensions import Entrypoint
from nameko.web.server import WebServer
_log = getLogger(__name__)
class HttpRequestHandler(Entrypoint):
server = WebServer()
def __init__(self, method, url, **kwargs):
self.method = method
self.url = url
super(HttpRequestHandler, self).__init__(**kwargs)
def get_url_rule(self):
return Rule(self.url, methods=self.method.split(','))
def setup(self):
self.server.register_provider(self)
def stop(self):
self.server.unregister_provider(self)
super(HttpRequestHandler, self).stop()
SERIALIZER_CONFIG_KEY, DEFAULT_SERIALIZER
)
exchange = get_rpc_exchange(self.container.config)
ssl = self.container.config.get(AMQP_SSL_CONFIG_KEY)
responder = Responder(amqp_uri, exchange, serializer, message, ssl=ssl)
result, exc_info = responder.send_response(result, exc_info)
self.queue_consumer.ack_message(message)
return result, exc_info
def requeue_message(self, message):
self.queue_consumer.requeue_message(message)
class Rpc(Entrypoint, HeaderDecoder):
rpc_consumer = RpcConsumer()
def setup(self):
self.rpc_consumer.register_provider(self)
def stop(self):
self.rpc_consumer.unregister_provider(self)
def handle_message(self, body, message):
try:
args = body['args']
kwargs = body['kwargs']
except KeyError:
raise MalformedRequest('Message missing `args` or `kwargs`')
assert conn.connected
self.conn = conn
print('setup WampWebSocketServer complete')
def stop(self):
print('stop WampWebSocketServer')
super(WampWebSocketServer, self).stop()
self.conn.close()
def handle_request(self, request):
print('handle request')
print request
class WampRpc(Entrypoint):
server = WampWebSocketServer()
def setup(self):
print('setup WampRpc')
# how to register this with Crossbar instead???
# https://github.com/crossbario/autobahn-python/blob/8f0c54eccaed2a4008a41d6bcd5573a674c22b6c/autobahn/wamp/uri.py#L228
self.server.register_provider(self)
def stop(self):
print('stop')
self.server.unregister_provider(self)
super(WampRpc, self).stop()
def handle_message(self, socket_id, data, context_data):
from __future__ import absolute_import
import time
from logging import getLogger
from eventlet import Timeout
from eventlet.event import Event
from nameko.extensions import Entrypoint
_log = getLogger(__name__)
class Timer(Entrypoint):
def __init__(self, interval, eager=False, **kwargs):
"""
Timer entrypoint. Fires every `interval` seconds or as soon as
the previous worker completes if that took longer.
The default behaviour is to wait `interval` seconds
before firing for the first time. If you want the entrypoint
to fire as soon as the service starts, pass `eager=True`.
Example::
timer = Timer.decorator
class Service(object):
name = "service"