Example #1
0
def test_connection_is_aborted_when_not_authorised(router):
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'not-an-expected-user',
    }

    client = Client(
        url=router.url, roles=roles, name="unauthenticated-client-one")

    with pytest.raises(WampyError) as exc_info:
        client.start()

    client.stop()

    exception = exc_info.value

    message = str(exception)

    assert (
        "no principal with authid \"not-an-expected-user\" exists"
        in message
    )
    assert "wamp.error.not_authorized" in message
Example #2
0
def test_incorrect_secret(router):
    os.environ['WAMPYSECRET'] = "incorrect-password"
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'peter',
    }

    client = Client(
        url=router.url,
        roles=roles,
        name="bad-client"
    )

    with pytest.raises(WampyError) as exc_info:
        client.start()

    exception = exc_info.value

    message = str(exception)

    assert (
        "WAMP-CRA signature is invalid"
        in message
    )
    assert "wamp.error.not_authorized" in message
Example #3
0
 def setup(self):
     self.config_path = self.container.config[
         WAMP_CONFIG_KEY]['config_path']
     self.router = Router(config_path=self.config_path)
     self.client = Client(
         router=self.router, name="nameko-wamp client proxy"
     )
Example #4
0
def test_incorrect_ticket(router):
    os.environ['WAMPYSECRET'] = "incorrect-ticket"
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['ticket'],
        'authid': 'martin',
    }

    client = Client(
        url=router.url,
        roles=roles,
        name="bad-client"
    )

    with pytest.raises(WampyError) as exc_info:
        client.start()

    exception = exc_info.value

    message = str(exception)

    assert (
        "ticket in static WAMP-Ticket authentication is invalid"
        in message
    )
    assert "wamp.error.not_authorized" in message
Example #5
0
def test_incorrect_ticket(router):
    os.environ['WAMPYSECRET'] = "incorrect-ticket"
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['ticket'],
        'authid': 'martin',
    }

    client = Client(url=router.url, roles=roles, name="bad-client")

    with pytest.raises(WampyError) as exc_info:
        client.start()

    exception = exc_info.value

    message = str(exception)

    assert ("ticket in static WAMP-Ticket authentication is invalid"
            in message)
    assert "wamp.error.not_authorized" in message
Example #6
0
def test_kwargs_are_received(router):
    class SubscribingClient(Client):
        received_kwargs = None

        @subscribe(topic="foo")
        def foo_topic_handler(self, **kwargs):
            SubscribingClient.received_kwargs = kwargs

    reader = SubscribingClient(url=router.url)

    assert SubscribingClient.received_kwargs is None

    with reader:
        assert SubscribingClient.received_kwargs is None

        publisher = Client(url=router.url)

        assert SubscribingClient.received_kwargs is None

        with publisher:
            publisher.publish(topic="foo", message="foobar", spam="eggs")

            def check_kwargs():
                assert SubscribingClient.received_kwargs == {
                    'message': 'foobar',
                    'spam': 'eggs',
                    'meta': {
                        'topic': 'foo',
                        'subscription_id': ANY,
                    },
                }

            assert_stops_raising(check_kwargs)
Example #7
0
def test_connection_is_ticket_challenged(router):
    os.environ['WAMPYSECRET'] = "wEx9TPFtHdRr2Zg7rtRE"
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['ticket'],
        'authid': 'martin',
    }

    client = Client(
        url=router.url,
        roles=roles,
        message_handler_cls=CollectingMessageHandler,
        name="unauthenticated-client"
    )

    client.start()
    messages = wait_for_messages(client, 2)

    # expect a Challenge and Welcome message
    assert messages[0][0] == Challenge.WAMP_CODE
    assert messages[1][0] == Welcome.WAMP_CODE

    client.stop()

    # now also expect a Goodbye message
    assert len(messages) == 3
    assert messages[0][0] == Challenge.WAMP_CODE
    assert messages[1][0] == Welcome.WAMP_CODE
    assert messages[2][0] == Goodbye.WAMP_CODE
Example #8
0
def test_kwargs_are_received(router):

    class SubscribingClient(Client):
        received_kwargs = None

        @subscribe(topic="foo")
        def foo_topic_handler(self, **kwargs):
            SubscribingClient.received_kwargs = kwargs

    reader = SubscribingClient(url=router.url)

    assert SubscribingClient.received_kwargs is None

    with reader:
        assert SubscribingClient.received_kwargs is None

        publisher = Client(url=router.url)

        assert SubscribingClient.received_kwargs is None

        with publisher:
            publisher.publish(
                topic="foo", message="foobar", spam="eggs")

            def check_kwargs():
                assert SubscribingClient.received_kwargs == {
                    'message': 'foobar',
                    'spam': 'eggs',
                    'meta': {
                        'topic': 'foo',
                        'subscription_id': ANY,
                    },
                }

            assert_stops_raising(check_kwargs)
Example #9
0
    def test_call_with_no_args_or_kwargs(self, date_service, router):
        client = Client(router=router)
        with client:
            response = client.call("get_todays_date")

        today = date.today()

        assert response == today.isoformat()
Example #10
0
    def test_call_with_no_args_or_kwargs(self, date_service, router):
        client = Client(url=router.url)
        with client:
            response = client.call("get_todays_date")

        today = date.today()

        assert response == today.isoformat()
Example #11
0
def test_cannot_publish_nothing_to_topic(foo_subscriber, router):
    assert foo_subscriber.call_count == 0

    client = Client(url=router.url)

    with client:
        with pytest.raises(WampyError):
            client.publish(topic="foo")

        assert foo_subscriber.call_count == 0
Example #12
0
def test_cannot_publish_nothing_to_topic(foo_subscriber, router):
    assert foo_subscriber.call_count == 0

    client = Client(url=router.url)

    with client:
        with pytest.raises(WampyError):
            client.publish(topic="foo")

        assert foo_subscriber.call_count == 0
Example #13
0
 def __init__(self, component):
     self.host = os.environ.get("TEP_WAMP_HOST", "127.0.0.1")
     self.port = int(os.environ.get("TEP_WAMP_PORT", 8080))
     Client.__init__(self, realm="tuxeatpi", url="ws://{}:{}".format(self.host, self.port))
     self.component = component
     self.logger = logging.getLogger(name="tep").getChild(component.name).getChild('wampclient')
     self._must_run = True
     self.topics = {}
     self.rpc_funcs = {}
     self._get_topics()
Example #14
0
    def setup_class(self):
        intents_folder = "tests/daemon_test/intents"
        dialogs_folder = "tests/daemon_test/dialogs"
        workdir = "tests/daemon_test/workdir"
        self.fake_daemon = FakeDaemon("fake_daemon", workdir, intents_folder,
                                      dialogs_folder)
        self.fake_daemon.settings.delete("/config/global")
        self.fake_daemon.settings.delete()

        self.wamp_client = Client(realm="tuxeatpi")
        self.wamp_client.start()
Example #15
0
def test_nameko_service_can_subscribe_to_wamp_topic(
    runner_factory, router, config_path
):
    wamp_client = Client(router=router)

    config = {
        WAMP_CONFIG_KEY: {
            'config_path': config_path,
        }
    }

    runner = runner_factory(config, WampSubscriber)
    runner.start()

    container = get_container(runner, WampSubscriber)

    with wamp_client as client:
        wait_for_session(client)
        wait_for_subscriptions(container, number_of_subscriptions=2)

        client.publish(topic="foo", message="hello foo")
        client.publish(topic="bar", message="hello bar")

    def waiting_for_the_message():
        assert len(WampSubscriber.messages) == 2
        assert sorted(WampSubscriber.messages) == sorted([
            ((u'hello foo',), {}),
            ((u'hello bar',), {})
        ])

    assert_stops_raising(waiting_for_the_message)
    WampSubscriber.messages = []
Example #16
0
    def test_ipv4_secure_websocket_connection_by_router_url(
            self, config_path, router):
        assert router.url == "wss://localhost:9443"

        try:
            ssl.PROTOCOL_TLSv1_2
        except AttributeError:
            pytest.skip('Python Environment does not support TLS')

        with DateService(
                url="wss://localhost:9443",
                cert_path="./wampy/testing/keys/server_cert.pem",
        ) as service:
            wait_for_registrations(service, 1)

            client = Client(
                url="wss://localhost:9443",
                cert_path="./wampy/testing/keys/server_cert.pem",
            )
            with client:
                wait_for_session(client)
                result = client.rpc.get_todays_date()

        today = date.today()

        assert result == today.isoformat()
Example #17
0
class WampClientProxy(Extension):

    def setup(self):
        self.config_path = self.container.config[
            WAMP_CONFIG_KEY]['config_path']
        self.router = Router(config_path=self.config_path)
        self.client = Client(
            router=self.router, name="nameko-wamp client proxy"
        )

    def start(self):
        self.client.start()

    def stop(self):
        try:
            self.client.stop()
        except AttributeError:
            pass
Example #18
0
def test_pinging(router):
    with patch('wampy.transports.websocket.connection.heartbeat', 1):
        with patch(
            'wampy.transports.websocket.connection.heartbeat_timeout', 2
        ):
            client = Client(router.url)
            client.start()
            wait_for_session(client)

            assert client.is_pinging

            ws = client.session.connection
            assert ws.missed_pongs == 0

            async_adapter.sleep(10)

            assert ws.missed_pongs == 0

    client.stop()
Example #19
0
def test_connection_is_ticket_challenged(router):
    os.environ['WAMPYSECRET'] = "wEx9TPFtHdRr2Zg7rtRE"
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['ticket'],
        'authid': 'martin',
    }

    client = Client(url=router.url,
                    roles=roles,
                    message_handler_cls=CollectingMessageHandler,
                    name="unauthenticated-client")

    client.start()
    messages = wait_for_messages(client, 2)

    # expect a Challenge and Welcome message
    assert messages[0][0] == Challenge.WAMP_CODE
    assert messages[1][0] == Welcome.WAMP_CODE

    client.stop()

    # now also expect a Goodbye message
    assert len(messages) == 3
    assert messages[0][0] == Challenge.WAMP_CODE
    assert messages[1][0] == Welcome.WAMP_CODE
    assert messages[2][0] == Goodbye.WAMP_CODE
Example #20
0
def test_connection_is_aborted_when_not_authorised(router):
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'not-an-expected-user',
    }

    client = Client(router=router,
                    roles=roles,
                    name="unauthenticated-client-one")

    with pytest.raises(WelcomeAbortedError) as exc_info:
        client.start()

    client.stop()

    exception = exc_info.value

    message = str(exception)

    assert ("no principal with authid \"not-an-expected-user\" exists"
            in message)
    assert "wamp.error.not_authorized" in message
Example #21
0
def test_connection_is_challenged(router):
    os.environ['WAMPYSECRET'] = "prq7+YkJ1/KlW1X0YczMHw=="
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'peter',
    }

    message_handler = CollectingMessageHandler()
    client = Client(router=router,
                    roles=roles,
                    message_handler=message_handler,
                    name="unauthenticated-client")

    client.start()
    messages = wait_for_messages(client, 2)

    # expect a Challenge and Welcome message
    assert messages[0][0] == Challenge.WAMP_CODE
    assert messages[1][0] == Welcome.WAMP_CODE

    client.stop()

    # now also expect a Goodbye message
    assert len(messages) == 3
    assert messages[0][0] == Challenge.WAMP_CODE
    assert messages[1][0] == Welcome.WAMP_CODE
    assert messages[2][0] == Goodbye.WAMP_CODE
Example #22
0
    def test_ipv6_websocket_connection(self, config_path, router):
        service = DateService(url=router.url)
        with service:
            wait_for_registrations(service, 1)

            client = Client(url=router.url)

            with client:
                result = client.rpc.get_todays_date()

        today = date.today()

        assert result == today.isoformat()
Example #23
0
def test_connection_exits_if_missing_client_secret(router):
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'peter',
    }

    client = Client(
        url=router.url, roles=roles, name="unauthenticated-client-two")

    with pytest.raises(WampyError) as exc_info:
        client.start()

    exception = exc_info.value

    message = str(exception)
    assert "WAMPYSECRET" in message
Example #24
0
def test_connection_exits_if_missing_client_secret(router):
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'peter',
    }

    client = Client(router=router,
                    roles=roles,
                    name="unauthenticated-client-two")

    with pytest.raises(WampyError) as exc_info:
        client.start()

    exception = exc_info.value

    message = str(exception)
    assert "WAMPYSECRET" in message
Example #25
0
def test_handle_value_error(unreliable_callee, router):
    with Client(url=router.url, name="caller") as client:

        with pytest.raises(WampyError) as exc_info:
            client.rpc.get_foo(1, 2, three=3)

        exception = exc_info.value
        assert type(exception) is WampyError

        message = str(exception)

        assert "i do not like any of your values" in message
        assert "(1, 2)" in message
        assert "three" in message
Example #26
0
def test_peter_cannot_call_get_foo(router, foo_service):
    # `get_foo` can be registered but not called over the wampy role
    os.environ['WAMPYSECRET'] = "prq7+YkJ1/KlW1X0YczMHw=="
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'peter',
    }

    client = Client(
        url=router.url,
        roles=roles,
        message_handler_cls=CollectingMessageHandler,
        name="unauthenticated-client-three",
    )

    client.start()

    with pytest.raises(WampyError):
        client.rpc.get_foo()

    client.stop()

    messages = wait_for_messages(client, 4)

    # now also expect a Goodbye message
    assert len(messages) == 4
    assert messages[0][0] == Challenge.WAMP_CODE
    assert messages[1][0] == Welcome.WAMP_CODE
    assert messages[2][0] == Error.WAMP_CODE
    assert messages[3][0] == Goodbye.WAMP_CODE
Example #27
0
def test_incorrect_secret(router):
    os.environ['WAMPYSECRET'] = "incorrect-password"
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'peter',
    }

    client = Client(router=router, roles=roles, name="bad-client")

    with pytest.raises(WelcomeAbortedError) as exc_info:
        client.start()

    exception = exc_info.value

    message = str(exception)

    assert ("WAMP-CRA signature is invalid" in message)
    assert "wamp.error.not_authorized" in message
Example #28
0
    def test_timeout_values(
        self,
        call_timeout,
        wait,
        reward,
        router,
        really_slow_service,
    ):
        with Client(url=router.url, call_timeout=call_timeout) as client:
            try:
                resp = client.rpc.requires_patience(wait_in_seconds=wait)
            except WampyTimeOutError:
                resp = None

        assert resp == reward
Example #29
0
    def test_ipv4_secure_websocket_connection_by_router_instance(
            self, config_path, router):
        try:
            ssl.PROTOCOL_TLSv1_2
        except AttributeError:
            pytest.skip('Python Environment does not support TLS')

        with DateService(router=router) as service:
            wait_for_registrations(service, 1)

            client = Client(router=router)
            with client:
                wait_for_session(client)
                result = client.rpc.get_todays_date()

        today = date.today()

        assert result == today.isoformat()
def main():
    port = config('PORT')
    url = f'ws://*****:*****@example.com', 'blebs')
    if isinstance(x, Error):
        print('Error:', x.message)
    else:
        print(x)

    x = client.call('authenticate', '*****@*****.**', 'blebs')
    if isinstance(x, Error):
        print('Error:', x.message)
    else:
        print(x)

    client.stop()
Example #31
0
def test_pings_and_missed_pongs(router, heartbeat, heartbeat_timeout, sleep,
                                expected_missed_pongs):
    with patch('wampy.transports.websocket.connection.heartbeat', heartbeat):
        with patch('wampy.transports.websocket.connection.heartbeat_timeout',
                   heartbeat_timeout):
            with Client(url=router.url) as client:
                wait_for_session(client)

                assert client.is_pinging is True

                ws = client.session.connection
                assert ws.missed_pongs == 0

                # this prevents Pongs being put into the shared queue
                with patch.object(ws, 'handle_pong'):
                    async_adapter.sleep(sleep)

            assert client.is_pinging is False

    assert ws.missed_pongs == expected_missed_pongs
Example #32
0
def test_cannot_publish_args_to_topic(foo_subscriber, router):
    assert foo_subscriber.call_count == 0

    client = Client(url=router.url)

    with client:

        with pytest.raises(WampyError):
            client.publish("foo", )

        assert foo_subscriber.call_count == 0

        with pytest.raises(WampyError):
            client.publish("foo", "foobar")

        assert foo_subscriber.call_count == 0

        even_more_args = range(100)

        with pytest.raises(WampyError):
            client.publish(even_more_args)

        assert foo_subscriber.call_count == 0
Example #33
0
def test_nameko_service_rpc_methods_are_called_by_any_wampy_client(
        runner_factory, router, config_path):

    wamp_client = Client(router=router)

    config = {
        WAMP_CONFIG_KEY: {
            'config_path': config_path,
        }
    }

    runner = runner_factory(config, WampServiceA)
    runner.start()

    assert WampServiceA.messages == []

    container = get_container(runner, WampServiceA)

    with wamp_client as client:
        wait_for_session(client)
        wait_for_registrations(container, number_of_registrations=1)
        wait_for_subscriptions(container, number_of_subscriptions=2)

        result = client.rpc.spam_call(cheese="cheddar", eggs="ducks")

    assert result == "spam"

    def waiting_for_the_message():
        assert len(WampServiceA.messages) == 1
        assert WampServiceA.messages == [((), {
            u'cheese': u'cheddar',
            u'eggs': u'ducks'
        })]

    assert_stops_raising(waiting_for_the_message)

    container.stop()
    WampServiceA.messages = []
Example #34
0
    def test_app_runner(self, router, config_path):
        apps = [
            'docs.examples.services:DateService',
            'docs.examples.services:BinaryNumberService',
            'docs.examples.services:FooService',
        ]

        runner = run(apps, config_path=config_path, router=router)

        # now check we can call these wonderful services
        client = Client(router=router)
        with client:
            date = client.rpc.get_todays_date()
            binary_number = client.rpc.get_binary_number(46)
            foo = client.rpc.get_foo()

        print("stopping all services gracefully")
        runner.stop()
        print("services have stopped")

        assert date == datetime.date.today().isoformat()
        assert binary_number == '0b101110'
        assert foo == 'foo'
Example #35
0
def test_pinging(router):
    with patch('wampy.transports.websocket.connection.heartbeat', 1):
        with patch('wampy.transports.websocket.connection.heartbeat_timeout',
                   2):
            client = Client(router.url)
            client.start()
            wait_for_session(client)

            assert client.is_pinging

            ws = client.session.connection
            assert ws.missed_pongs == 0

            async_adapter.sleep(10)

            assert ws.missed_pongs == 0

    client.stop()
Example #36
0
def test_cannot_publish_args_to_topic(foo_subscriber, router):
    assert foo_subscriber.call_count == 0

    client = Client(url=router.url)

    with client:

        with pytest.raises(WampyError):
            client.publish("foo",)

        assert foo_subscriber.call_count == 0

        with pytest.raises(WampyError):
            client.publish("foo", "foobar")

        assert foo_subscriber.call_count == 0

        even_more_args = range(100)

        with pytest.raises(WampyError):
            client.publish(even_more_args)

        assert foo_subscriber.call_count == 0
Example #37
0
def test_peter_cannot_call_get_foo(router, foo_service):
    # `get_foo` can be registered but not called over the wampy role
    os.environ['WAMPYSECRET'] = "prq7+YkJ1/KlW1X0YczMHw=="
    roles = {
        'roles': {
            'subscriber': {},
            'publisher': {},
            'callee': {},
            'caller': {},
        },
        'authmethods': ['wampcra'],
        'authid': 'peter',
    }

    message_handler = CollectingMessageHandler()
    client = Client(
        router=router,
        roles=roles,
        message_handler=message_handler,
        name="unauthenticated-client-three",
    )

    client.start()

    with pytest.raises(NotAuthorisedError):
        client.rpc.get_foo()

    client.stop()

    messages = wait_for_messages(client, 4)

    # now also expect a Goodbye message
    assert len(messages) == 4
    assert messages[0][0] == Challenge.WAMP_CODE
    assert messages[1][0] == Welcome.WAMP_CODE
    assert messages[2][0] == Error.WAMP_CODE
    assert messages[3][0] == Goodbye.WAMP_CODE
Example #38
0
    def test_rpc_with_args_but_no_kwargs(self, hello_service, router):
        caller = Client(router=router)
        with caller:
            response = caller.rpc.say_hello("Simon")

        assert response == "Hello Simon"
Example #39
0
    def test_rpc_with_no_args_but_a_default_kwarg(self, hello_service, router):
        caller = Client(router=router)
        with caller:
            response = caller.rpc.say_greeting("Simon")

        assert response == "hola to Simon"
Example #40
0
    def test_call_with_args_and_kwargs(self, hello_service, router):
        caller = Client(router=router)
        with caller:
            response = caller.call("say_greeting", "Simon", greeting="watcha")

        assert response == "watcha to Simon"
Example #41
0
    def test_call_with_args_but_no_kwargs(self, hello_service, router):
        caller = Client(url=router.url)
        with caller:
            response = caller.call("say_hello", "Simon")

        assert response == "Hello Simon"
Example #42
0
    def test_call_with_args_and_kwargs(self, hello_service, router):
        caller = Client(url=router.url)
        with caller:
            response = caller.call("say_greeting", "Simon", greeting="watcha")

        assert response == "watcha to Simon"
Example #43
0
def test_publish_kwargs_to_topic(foo_subscriber, router):
    assert foo_subscriber.call_count == 0

    client = Client(url=router.url)

    client.start()
    client.publish(topic="foo", message="foobar")

    def check_call_count():
        assert foo_subscriber.call_count == 1

    assert_stops_raising(check_call_count)

    client.publish(topic="foo", message="foobar")
    client.publish(topic="foo", message="spam")
    client.publish(topic="foo", message="ham")

    def check_call_count():
        assert foo_subscriber.call_count == 4

    assert_stops_raising(check_call_count)

    client.stop()
Example #44
0
def client(router):
    with Client(router=router) as client:
        yield client