示例#1
0
 async def start(self, ctx: Context):
     registry = WAMPRegistry()
     registry.add_from(topics)
     registry.add_from(procedures)
     self.add_component('wamp', registry=registry)
     await super().start(ctx)
     await ctx.wamp.connect()
def test_add_from(prefix):
    child_registry = WAMPRegistry('child', procedure_defaults=RegisterOptions(invoke='roundrobin'),
                                  subscription_defaults=SubscribeOptions(match='prefix'))
    child_registry.add_procedure(dummyhandler, 'procedure', RegisterOptions(match='exact'))
    child_registry.add_subscriber(dummyhandler, 'topic', SubscribeOptions(match='exact'))
    child_registry.map_exception(RuntimeError, 'x.y.z')

    parent_registry = WAMPRegistry(
        'parent', procedure_defaults=RegisterOptions(match='prefix', invoke='first',
                                                     concurrency=2),
        subscription_defaults=SubscribeOptions(match='wildcard', get_retained=True)
    )
    parent_registry.add_from(child_registry, prefix)

    procedure_name = 'parent.{}child.procedure'.format((prefix + '.') if prefix else '')
    assert len(parent_registry.procedures) == 1
    assert parent_registry.procedures[procedure_name].options.match == 'exact'
    assert parent_registry.procedures[procedure_name].options.invoke == 'roundrobin'
    assert parent_registry.procedures[procedure_name].options.concurrency == 2

    expected_topic = 'parent.{}child.topic'.format((prefix + '.') if prefix else '')
    assert len(parent_registry.subscriptions) == 1
    assert parent_registry.subscriptions[0].topic == expected_topic
    assert parent_registry.subscriptions[0].options.match == 'exact'

    exception_name = 'parent.{}child.x.y.z'.format((prefix + '.') if prefix else '')
    assert parent_registry.exceptions == {exception_name: RuntimeError}
def test_exception_decorator(registry: WAMPRegistry, use_decorator):
    if use_decorator:
        registry.exception('x.y.z')(RuntimeError)
    else:
        registry.map_exception(RuntimeError, 'x.y.z')

    assert registry.exceptions == {'x.y.z': RuntimeError}
示例#4
0
def test_exception_decorator(registry: WAMPRegistry, use_decorator):
    if use_decorator:
        registry.exception('x.y.z')(RuntimeError)
    else:
        registry.map_exception(RuntimeError, 'x.y.z')

    assert registry.exceptions == {'x.y.z': RuntimeError}
示例#5
0
def test_subscriber(registry: WAMPRegistry, use_decorator):
    options = {'match': 'prefix'}
    if use_decorator:
        registry.subscriber('topic', **options)(dummyhandler)
    else:
        registry.add_subscriber(dummyhandler, 'topic', **options)

    assert registry.subscriptions == [Subscriber('topic', dummyhandler, options)]
示例#6
0
def test_procedure(registry: WAMPRegistry, use_decorator):
    options = {'match': 'prefix', 'invoke': 'roundrobin'}
    if use_decorator:
        registry.procedure(name='procedurename', **options)(dummyhandler)
    else:
        registry.add_procedure(dummyhandler, 'procedurename', **options)

    expected = Procedure('procedurename', dummyhandler, options)
    assert registry.procedures == {'procedurename': expected}
def test_procedure(registry: WAMPRegistry, use_dict, use_decorator):
    options = dict(match='prefix', invoke='roundrobin')
    if not use_dict:
        options = RegisterOptions(**options)

    if use_decorator:
        registry.procedure('procedurename', options)(dummyhandler)
    else:
        registry.add_procedure(dummyhandler, 'procedurename', options)

    assert list(registry.procedures.keys()) == ['procedurename']
    procedure = registry.procedures['procedurename']
    assert procedure.handler is dummyhandler
    assert procedure.name == 'procedurename'
    assert procedure.options.concurrency == 1
示例#8
0
    def __init__(self,
                 host: str = 'localhost',
                 port: int = 8080,
                 path: str = '/',
                 realm: str = 'default',
                 *,
                 reconnect_delay: int = 5,
                 max_reconnection_attempts: int = None,
                 registry: Union[WAMPRegistry, str] = None,
                 ssl: Union[bool, str, SSLContext] = False,
                 serializer: Union[Serializer, str] = None,
                 auth_method: str = 'anonymous',
                 auth_id: str = None,
                 auth_secret: str = None):
        """
        The following parameters are also available as instance attributes:

        :param host: host address of the WAMP router
        :param port: port to connect to
        :param path: HTTP path on the router
        :param realm: the WAMP realm to join the application session to (defaults to the resource
            name if not specified)
        :param reconnect_delay: delay between connection attempts (in seconds)
        :param max_reconnection_attempts: maximum number of connection attempts before giving up
        :param registry: a WAMP registry or a string reference to one (defaults to creating a new
            instance if omitted)
        :param ssl: one of the following:

            * ``False`` to disable SSL
            * ``True`` to enable SSL using the default context
            * an :class:`ssl.SSLContext` instance
            * a ``module:varname`` reference to an :class:`~ssl.SSLContext` instance
            * name of an :class:`ssl.SSLContext` resource
        :param serializer: a serializer instance or the name of a
            :class:`asphalt.serialization.api.Serializer` resource (defaults to creating a new
            :class:`~asphalt.serialization.json.JSONSerializer` if omitted)
        :param auth_method: authentication method to use (valid values are currently ``anonymous``,
            ``wampcra`` and ``ticket``)
        :param auth_id: authentication ID (username)
        :param auth_secret: secret to use for authentication (ticket or password)

        """
        assert check_argument_types()
        self.host = host
        self.port = port
        self.path = path
        self.reconnect_delay = reconnect_delay
        self.max_reconnection_attempts = max_reconnection_attempts
        self.realm = realm
        self.registry = resolve_reference(registry) or WAMPRegistry()
        self.ssl = resolve_reference(ssl)
        self.serializer = resolve_reference(serializer) or JSONSerializer()
        self.auth_method = auth_method
        self.auth_id = auth_id
        self.auth_secret = auth_secret

        self._context = None
        self._session = None  # type: AsphaltSession
        self._session_details = None  # type: SessionDetails
        self._connect_task = None  # type: Task
示例#9
0
    async def start(self, ctx: Context):
        self._parent_context = ctx
        self._loop = ctx.loop

        if isinstance(self.tls_context, str):
            self.tls_context = await ctx.request_resource(SSLContext, self.tls_context)
        if isinstance(self.serializer, str):
            self.serializer = await ctx.request_resource(Serializer, self.serializer)
        if isinstance(self._registry, str):
            self._registry = await ctx.request_resource(WAMPRegistry, self._registry)

        registry = WAMPRegistry()
        if self._registry:
            registry.add_from(self._registry)

        self._registry = registry
def test_subscriber(registry: WAMPRegistry, use_dict, use_decorator):
    options = dict(match='prefix')
    if not use_dict:
        options = SubscribeOptions(**options)

    if use_decorator:
        registry.subscriber('topic', options)(dummyhandler)
    else:
        registry.add_subscriber(dummyhandler, 'topic', options)

    assert len(registry.subscriptions) == 1
    subscription = registry.subscriptions[0]
    assert subscription.handler is dummyhandler
    assert subscription.topic == 'topic'
    assert subscription.options.match == 'prefix'
    assert subscription.options.get_retained
示例#11
0
def test_add_from(prefix):
    child_registry = WAMPRegistry('child')
    child_registry.add_procedure(dummyhandler, 'procedure')
    child_registry.add_subscriber(dummyhandler, 'topic')
    child_registry.map_exception(RuntimeError, 'x.y.z')

    parent_registry = WAMPRegistry('parent')
    parent_registry.add_from(child_registry, prefix)
    procedure_name = 'parent.{}child.procedure'.format((prefix + '.') if prefix else '')
    assert parent_registry.procedures == {
        procedure_name: Procedure(procedure_name, dummyhandler, parent_registry.procedure_defaults)
    }
    assert parent_registry.subscriptions == [Subscriber('topic', dummyhandler, {'match': 'exact'})]
    assert parent_registry.exceptions == {'x.y.z': RuntimeError}
示例#12
0
def registry():
    return WAMPRegistry()
示例#13
0
def test_duplicate_procedure(registry: WAMPRegistry):
    registry.add_procedure(dummyhandler, 'handler')

    exc = pytest.raises(ValueError, registry.add_procedure, dummyhandler, 'handler')
    assert str(exc.value) == 'duplicate registration of procedure "handler"'
示例#14
0
def test_procedure_simple_decorator(registry: WAMPRegistry):
    registry.procedure(dummyhandler)
    expected = Procedure('dummyhandler', dummyhandler, registry.procedure_defaults)
    assert registry.procedures == {'dummyhandler': expected}
示例#15
0
"""
This example demonstrates the use of a WAMP registry to register a procedure handler and an event
subscriber.
"""

from pathlib import Path
import logging

from asphalt.core import ContainerComponent, Context, run_application
from asphalt.wamp.context import CallContext, EventContext
from asphalt.wamp.registry import WAMPRegistry
from asphalt.wamp.utils import launch_crossbar

registry = WAMPRegistry()
subregistry = WAMPRegistry('test')
registry.add_from(subregistry)


@subregistry.procedure
async def reverse(ctx: CallContext, message: str):
    return message[::-1]


@subregistry.subscriber('topic.subtopic')
async def subtopic(ctx: EventContext, message):
    print('message received from topic.subtopic: %s' % message)


class RPCServerComponent(ContainerComponent):
    async def start(self, ctx: Context):
        crossbar_dir = Path(__name__).parent / '.crossbar'
def test_subscriber_no_options(registry: WAMPRegistry):
    registry.add_subscriber(dummyhandler, 'topic')
    assert len(registry.subscriptions) == 1
    assert type(registry.subscriptions[0].options) is SubscribeOptions
def test_duplicate_procedure(registry: WAMPRegistry):
    registry.add_procedure(dummyhandler, 'handler')

    exc = pytest.raises(ValueError, registry.add_procedure, dummyhandler, 'handler')
    exc.match('duplicate registration of procedure "handler"')
def test_procedure_simple_decorator(registry: WAMPRegistry):
    registry.procedure(dummyhandler)
    assert list(registry.procedures.keys()) == ['dummyhandler']
    assert registry.procedures['dummyhandler'].handler is dummyhandler
    assert type(registry.procedures['dummyhandler'].options) is RegisterOptions