From d3f674a09cd0ee2dbfb2eeb8d7f325af82db7606 Mon Sep 17 00:00:00 2001 From: Omer Akram Date: Fri, 10 Jan 2020 20:09:17 +0500 Subject: [PATCH] More py2 removal (#1286) * Replace unicode with string done by following command: find . -name '*.py' -type f -exec sed -i 's/u"/"/g' {} \; * Replace all instances of unicode with strings * remove all instances of 'from __future__ import...' * trollius is no more * setup.py: drop py2 --- DEVELOPERS.md | 7 +- autobahn/__init__.py | 2 - autobahn/__main__.py | 4 - autobahn/_version.py | 2 +- autobahn/asyncio/__init__.py | 4 +- autobahn/asyncio/component.py | 47 +- autobahn/asyncio/rawsocket.py | 12 +- .../asyncio/test/test_asyncio_rawsocket.py | 6 +- autobahn/asyncio/util.py | 10 +- autobahn/asyncio/wamp.py | 12 +- autobahn/asyncio/websocket.py | 53 +- autobahn/exception.py | 2 - autobahn/nvx/__init__.py | 2 - autobahn/nvx/_utf8validator.py | 2 - autobahn/nvx/test/test_utf8validator.py | 4 +- autobahn/rawsocket/test/test_rawsocket_url.py | 2 - autobahn/rawsocket/util.py | 18 +- autobahn/test/__init__.py | 2 - autobahn/test/test_rng.py | 2 - autobahn/test/test_util.py | 2 - autobahn/twisted/__init__.py | 4 +- autobahn/twisted/choosereactor.py | 2 - autobahn/twisted/component.py | 34 +- autobahn/twisted/cryptosign.py | 4 +- autobahn/twisted/forwarder.py | 2 - autobahn/twisted/rawsocket.py | 8 +- autobahn/twisted/resource.py | 4 +- .../twisted/test/test_application_runner.py | 16 +- autobahn/twisted/test/test_choosereactor.py | 2 - autobahn/twisted/test/test_component.py | 32 +- .../twisted/test/test_endpoint_plugins.py | 2 - autobahn/twisted/test/test_protocol.py | 6 +- autobahn/twisted/test/test_rawsocket.py | 2 - autobahn/twisted/test/test_websocket_agent.py | 4 +- autobahn/twisted/testing/__init__.py | 2 - autobahn/twisted/util.py | 14 +- autobahn/twisted/wamp.py | 30 +- autobahn/twisted/websocket.py | 34 +- autobahn/util.py | 32 +- autobahn/wamp/__init__.py | 2 - autobahn/wamp/auth.py | 84 +- autobahn/wamp/component.py | 34 +- autobahn/wamp/cryptobox.py | 22 +- autobahn/wamp/cryptosign.py | 29 +- autobahn/wamp/exception.py | 66 +- autobahn/wamp/interfaces.py | 4 +- autobahn/wamp/message.py | 886 +++++++++--------- autobahn/wamp/message_fbs.py | 2 - autobahn/wamp/protocol.py | 68 +- autobahn/wamp/request.py | 2 - autobahn/wamp/role.py | 34 +- autobahn/wamp/serializer.py | 52 +- autobahn/wamp/test/test_auth.py | 78 +- autobahn/wamp/test/test_component.py | 44 +- autobahn/wamp/test/test_component_aio.py | 14 +- autobahn/wamp/test/test_cryptobox.py | 2 - autobahn/wamp/test/test_cryptosign.py | 12 +- autobahn/wamp/test/test_exception.py | 10 +- autobahn/wamp/test/test_message.py | 438 +++++---- autobahn/wamp/test/test_protocol.py | 198 ++-- autobahn/wamp/test/test_protocol_peer.py | 33 +- autobahn/wamp/test/test_runner.py | 26 +- autobahn/wamp/test/test_serializer.py | 54 +- autobahn/wamp/test/test_uri_pattern.py | 206 ++-- .../wamp/test/test_user_handler_errors.py | 16 +- autobahn/wamp/test/test_websocket.py | 2 - autobahn/wamp/types.py | 128 ++- autobahn/wamp/uri.py | 16 +- autobahn/wamp/websocket.py | 30 +- autobahn/websocket/__init__.py | 2 - autobahn/websocket/compress.py | 2 - autobahn/websocket/compress_bzip2.py | 2 - autobahn/websocket/compress_deflate.py | 2 - autobahn/websocket/compress_snappy.py | 2 - autobahn/websocket/protocol.py | 68 +- autobahn/websocket/test/test_protocol.py | 10 +- autobahn/websocket/test/test_websocket.py | 2 - autobahn/websocket/test/test_websocket_url.py | 2 - autobahn/websocket/types.py | 4 +- autobahn/websocket/util.py | 18 +- autobahn/xbr/__init__.py | 2 - autobahn/xbr/test/test_mnemonic.py | 2 - docker/aarch64/app/client_aio.py | 17 +- docker/aarch64/app/client_publish.py | 10 +- docker/aarch64/app/client_rpc_callee.py | 8 +- docker/aarch64/app/client_rpc_caller.py | 8 +- docker/aarch64/app/client_subscribe.py | 12 +- docker/aarch64/app/client_tx.py | 8 +- docker/armhf/app/client_aio.py | 17 +- docker/armhf/app/client_publish.py | 10 +- docker/armhf/app/client_rpc_callee.py | 8 +- docker/armhf/app/client_rpc_caller.py | 8 +- docker/armhf/app/client_subscribe.py | 12 +- docker/armhf/app/client_tx.py | 8 +- docker/x86_64/app/client_aio.py | 17 +- .../x86_64/app/client_appsession_publish.py | 10 +- .../app/client_appsession_rpc_callee.py | 8 +- .../app/client_appsession_rpc_caller.py | 8 +- .../x86_64/app/client_appsession_subscribe.py | 8 +- docker/x86_64/app/client_component_publish.py | 6 +- .../x86_64/app/client_component_rpc_callee.py | 6 +- .../x86_64/app/client_component_rpc_caller.py | 6 +- .../x86_64/app/client_component_subscribe.py | 6 +- docker/x86_64/app/client_tx.py | 8 +- docs/conf.py | 14 +- docs/listings/aio_complete.py | 28 +- docs/listings/index.py | 8 +- docs/listings/programming.py | 28 +- docs/listings/tx_complete.py | 28 +- docs/listings/webapp.py | 8 +- docs/websocket/programming.rst | 13 +- examples/asciinema-autobahn-demo.py | 2 +- examples/asyncio/wamp/component/backend.py | 6 +- examples/asyncio/wamp/component/frontend.py | 24 +- examples/asyncio/wamp/overview/backend.py | 8 +- examples/asyncio/wamp/overview/frontend.py | 8 +- examples/asyncio/wamp/pubsub/basic/backend.py | 6 +- .../asyncio/wamp/pubsub/basic/frontend.py | 6 +- .../asyncio/wamp/pubsub/complex/backend.py | 8 +- .../asyncio/wamp/pubsub/complex/frontend.py | 8 +- .../asyncio/wamp/pubsub/decorators/backend.py | 8 +- .../wamp/pubsub/decorators/frontend.py | 8 +- .../asyncio/wamp/pubsub/options/backend.py | 8 +- .../asyncio/wamp/pubsub/options/frontend.py | 6 +- .../wamp/pubsub/tls/backend_selfsigned.py | 8 +- .../wamp/pubsub/unsubscribe/backend.py | 2 +- .../wamp/pubsub/unsubscribe/frontend.py | 6 +- examples/asyncio/wamp/rawsocket/backend.py | 6 +- examples/asyncio/wamp/rawsocket/frontend.py | 6 +- .../asyncio/wamp/rpc/arguments/backend.py | 18 +- .../asyncio/wamp/rpc/arguments/frontend.py | 28 +- examples/asyncio/wamp/rpc/complex/backend.py | 8 +- examples/asyncio/wamp/rpc/complex/frontend.py | 8 +- .../asyncio/wamp/rpc/decorators/backend.py | 10 +- .../asyncio/wamp/rpc/decorators/frontend.py | 10 +- examples/asyncio/wamp/rpc/errors/backend.py | 18 +- examples/asyncio/wamp/rpc/errors/frontend.py | 12 +- examples/asyncio/wamp/rpc/options/backend.py | 10 +- examples/asyncio/wamp/rpc/options/frontend.py | 8 +- examples/asyncio/wamp/rpc/progress/backend.py | 6 +- .../asyncio/wamp/rpc/progress/frontend.py | 6 +- .../asyncio/wamp/rpc/slowsquare/backend.py | 8 +- .../asyncio/wamp/rpc/slowsquare/frontend.py | 8 +- .../asyncio/wamp/rpc/timeservice/backend.py | 6 +- .../asyncio/wamp/rpc/timeservice/frontend.py | 6 +- .../asyncio/wamp/session/series/backend.py | 2 +- .../asyncio/wamp/session/series/frontend.py | 4 +- examples/asyncio/websocket/echo/client.py | 13 +- .../websocket/echo/client_coroutines.py | 11 +- .../websocket/echo/client_coroutines_py2.py | 67 -- examples/asyncio/websocket/echo/server.py | 6 +- .../asyncio/websocket/slowsquare/client.py | 6 +- .../asyncio/websocket/slowsquare/server.py | 7 +- .../websocket/slowsquare/server_py2.py | 71 -- examples/run-all-examples.py | 2 - .../twisted/wamp/app/calculator/calculator.py | 8 +- .../wamp/app/crochet/example1/server.py | 4 +- .../wamp/app/crochet/example2/server.py | 10 +- examples/twisted/wamp/app/dbus/bridge.py | 6 +- examples/twisted/wamp/app/hello/hello.py | 10 +- examples/twisted/wamp/app/keyvalue/store.py | 10 +- .../wamp/app/klein/example1/server_wamp.py | 4 +- .../wamp/app/klein/example1/server_web.py | 4 +- .../twisted/wamp/app/klein/example2/server.py | 8 +- .../twisted/wamp/app/serial2ws/serial2ws.py | 12 +- .../subscribe_upon_call.py | 6 +- examples/twisted/wamp/auth/backend.py | 6 +- examples/twisted/wamp/auth/backend_salted.py | 10 +- examples/twisted/wamp/auth/frontend.py | 10 +- .../wamp/basic/client_using_apprunner.py | 16 +- .../wamp/basic/client_using_clientservice.py | 8 +- examples/twisted/wamp/component/backend.py | 26 +- examples/twisted/wamp/component/frontend.py | 24 +- .../twisted/wamp/component/frontend_cancel.py | 6 +- .../twisted/wamp/component/frontend_scram.py | 14 +- examples/twisted/wamp/meta/backend.py | 12 +- examples/twisted/wamp/meta/meta_listener.py | 10 +- examples/twisted/wamp/overview/backend.py | 8 +- examples/twisted/wamp/overview/frontend.py | 8 +- examples/twisted/wamp/pubsub/basic/backend.py | 7 +- .../twisted/wamp/pubsub/basic/frontend.py | 7 +- .../twisted/wamp/pubsub/complex/backend.py | 10 +- .../twisted/wamp/pubsub/complex/frontend.py | 8 +- .../twisted/wamp/pubsub/decorators/backend.py | 10 +- .../wamp/pubsub/decorators/frontend.py | 10 +- .../twisted/wamp/pubsub/options/backend.py | 10 +- .../twisted/wamp/pubsub/options/frontend.py | 8 +- .../twisted/wamp/pubsub/retained/backend.py | 6 +- .../twisted/wamp/pubsub/retained/frontend.py | 8 +- .../wamp/pubsub/tls/backend_selfsigned.py | 8 +- .../wamp/pubsub/unsubscribe/backend.py | 8 +- .../wamp/pubsub/unsubscribe/frontend.py | 8 +- .../twisted/wamp/rpc/arguments/backend.py | 18 +- .../twisted/wamp/rpc/arguments/frontend.py | 28 +- .../twisted/wamp/rpc/authorize/authorizer.py | 20 +- .../twisted/wamp/rpc/authorize/backend.py | 14 +- examples/twisted/wamp/rpc/cancel/backend.py | 14 +- examples/twisted/wamp/rpc/cancel/frontend.py | 24 +- examples/twisted/wamp/rpc/complex/backend.py | 8 +- examples/twisted/wamp/rpc/complex/frontend.py | 8 +- .../twisted/wamp/rpc/decorators/backend.py | 12 +- .../twisted/wamp/rpc/decorators/frontend.py | 12 +- examples/twisted/wamp/rpc/errors/backend.py | 18 +- examples/twisted/wamp/rpc/errors/frontend.py | 12 +- examples/twisted/wamp/rpc/options/backend.py | 10 +- examples/twisted/wamp/rpc/options/frontend.py | 8 +- examples/twisted/wamp/rpc/progress/backend.py | 6 +- .../twisted/wamp/rpc/progress/frontend.py | 6 +- .../twisted/wamp/rpc/slowsquare/backend.py | 8 +- .../twisted/wamp/rpc/slowsquare/frontend.py | 8 +- .../twisted/wamp/rpc/timeservice/backend.py | 6 +- .../twisted/wamp/rpc/timeservice/frontend.py | 6 +- .../twisted/wamp/work/newapi/test_newapi.py | 4 +- .../twisted/wamp/work/newapi/test_newapi10.py | 14 +- .../twisted/wamp/work/newapi/test_newapi11.py | 28 +- .../twisted/wamp/work/newapi/test_newapi12.py | 14 +- .../wamp/work/newapi/test_newapi12b.py | 16 +- .../twisted/wamp/work/newapi/test_newapi13.py | 10 +- .../twisted/wamp/work/newapi/test_newapi2.py | 6 +- .../twisted/wamp/work/newapi/test_newapi3.py | 4 +- .../twisted/wamp/work/newapi/test_newapi4.py | 4 +- .../twisted/wamp/work/newapi/test_newapi5.py | 4 +- .../twisted/wamp/work/newapi/test_newapi6.py | 4 +- .../twisted/wamp/work/newapi/test_newapi7.py | 6 +- .../twisted/wamp/work/newapi/test_newapi8.py | 8 +- .../twisted/wamp/work/newapi/test_newapi9.py | 6 +- .../work/newapi/test_newapi_cryptosign.py | 12 +- .../test_newapi_multiple_connections.py | 4 +- .../newapi/test_newapi_pubreg_decorator.py | 24 +- .../wamp/work/newapi/test_newapi_short.py | 2 +- .../wamp/work/newapi/test_newapi_twisted.py | 14 +- .../wamp/work/newapi/test_newapi_wampcra.py | 12 +- .../twisted/websocket/auth_persona/server.py | 2 +- .../twisted/websocket/broadcast/server.py | 2 +- examples/twisted/websocket/echo/client.py | 4 +- .../websocket/echo/client_coroutines.py | 4 +- examples/twisted/websocket/echo/server.py | 2 +- .../websocket/echo_compressed/server.py | 2 +- .../echo_compressed/server_advanced.py | 2 +- .../websocket/echo_endpoints/client.py | 2 +- .../websocket/echo_endpoints/server.py | 2 +- .../websocket/echo_httpheaders/server.py | 2 +- .../websocket/echo_multicore/server.py | 4 +- .../echo_multicore/server_reuseport.py | 2 +- .../echo_service/echows/echoservice.py | 2 +- .../twisted/websocket/echo_site/server.py | 2 +- .../twisted/websocket/echo_site_tls/server.py | 2 +- examples/twisted/websocket/echo_tls/client.py | 2 +- examples/twisted/websocket/echo_tls/server.py | 2 +- .../twisted/websocket/echo_variants/server.py | 2 +- .../websocket/echo_wsfallbacks/server.py | 2 +- .../twisted/websocket/echo_wsgi/server.py | 2 +- .../twisted/websocket/multiproto/server1.py | 2 +- examples/twisted/websocket/ping/server.py | 2 +- .../websocket/pingpong_keepalive/server.py | 2 +- .../twisted/websocket/reconnecting/client.py | 4 +- .../twisted/websocket/reconnecting/server.py | 2 +- .../twisted/websocket/slowsquare/client.py | 2 +- .../twisted/websocket/slowsquare/server.py | 2 +- .../websocket/streaming/frame_based_client.py | 2 +- .../websocket/streaming/frame_based_server.py | 2 +- .../streaming/message_based_client.py | 2 +- .../streaming/message_based_server.py | 2 +- .../websocket/streaming/streaming_client.py | 2 +- .../streaming/streaming_producer_client.py | 2 +- .../websocket/streaming/streaming_server.py | 2 +- examples/twisted/websocket/wrapping/client.py | 2 +- examples/twisted/websocket/wrapping/server.py | 2 +- examples/twisted/websocket/wxpython/client.py | 2 +- examples/twisted/websocket/wxpython/server.py | 2 +- requirements-rtd.txt | 2 - setup.py | 56 +- twisted/plugins/autobahn_endpoints.py | 2 - wstest/testee_client_aio.py | 16 +- wstest/testee_client_tx.py | 4 +- wstest/testee_server_aio.py | 10 +- wstest/testee_server_tx.py | 4 +- 277 files changed, 2247 insertions(+), 2689 deletions(-) delete mode 100644 examples/asyncio/websocket/echo/client_coroutines_py2.py delete mode 100644 examples/asyncio/websocket/slowsquare/server_py2.py diff --git a/DEVELOPERS.md b/DEVELOPERS.md index 23866bf03..9adb9ffe4 100644 --- a/DEVELOPERS.md +++ b/DEVELOPERS.md @@ -130,21 +130,18 @@ That is, **use an assert if the following holds true: if the assert fails, it me In contrast, to check e.g. for user errors, such as application code using the wrong type when calling into the library, use Exceptions: ```python -import six - def foo(uri): - if type(uri) != six.text_type: + if type(uri) != str: raise RuntimeError(u"URIs for foo() must be unicode - got {} instead".format(type(uri))) ``` In this specific example, we also have a WAMP defined error (which would be preferred compared to the generic exception used above): ```python -import six from autobahn.wamp import ApplicationError def foo(uri): - if type(uri) != six.text_type: + if type(uri) != str: raise ApplicationError(ApplicationError.INVALID_URI, u"URIs for foo() must be unicode - got {} instead".format(type(uri))) ``` diff --git a/autobahn/__init__.py b/autobahn/__init__.py index d186d94d5..6f4af3b2d 100644 --- a/autobahn/__init__.py +++ b/autobahn/__init__.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn._version import __version__ version = __version__ diff --git a/autobahn/__main__.py b/autobahn/__main__.py index 49fc90e91..27efc28b1 100644 --- a/autobahn/__main__.py +++ b/autobahn/__main__.py @@ -24,10 +24,6 @@ # ############################################################################### -from __future__ import absolute_import -from __future__ import print_function - - # this module is available as the 'wamp' command-line tool or as # 'python -m autobahn' diff --git a/autobahn/_version.py b/autobahn/_version.py index a3cc22c3c..a0215147c 100644 --- a/autobahn/_version.py +++ b/autobahn/_version.py @@ -24,4 +24,4 @@ # ############################################################################### -__version__ = u'20.1.1' +__version__ = '20.1.1' diff --git a/autobahn/asyncio/__init__.py b/autobahn/asyncio/__init__.py index a35c6bb7e..d0911d24b 100644 --- a/autobahn/asyncio/__init__.py +++ b/autobahn/asyncio/__init__.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import - import sys import platform @@ -51,7 +49,7 @@ 'ApplicationSession', ) -__ident__ = u'Autobahn/{}-asyncio-{}/{}'.format(autobahn.__version__, platform.python_implementation(), '.'.join([str(x) for x in list(sys.version_info[:3])])) +__ident__ = 'Autobahn/{}-asyncio-{}/{}'.format(autobahn.__version__, platform.python_implementation(), '.'.join([str(x) for x in list(sys.version_info[:3])])) """ AutobahnPython library implementation (eg. "Autobahn/0.13.0-asyncio-CPython/3.5.1") """ diff --git a/autobahn/asyncio/component.py b/autobahn/asyncio/component.py index 8c4e6b82e..886dc4b43 100644 --- a/autobahn/asyncio/component.py +++ b/autobahn/asyncio/component.py @@ -24,20 +24,11 @@ # ############################################################################### - -from __future__ import absolute_import, print_function - -import ssl # XXX what Python version is this always available at? +import asyncio +import ssl import signal from functools import wraps -try: - import asyncio -except ImportError: - # Trollius >= 0.3 was renamed to asyncio - # noinspection PyUnresolvedReferences - import trollius as asyncio - import txaio txaio.use_asyncio() # noqa @@ -71,7 +62,7 @@ def _create_transport_factory(loop, transport, session_factory): """ Create a WAMP-over-XXX transport factory. """ - if transport.type == u'websocket': + if transport.type == 'websocket': serializers = create_transport_serializers(transport) factory = WampWebSocketClientFactory( session_factory, @@ -80,7 +71,7 @@ def _create_transport_factory(loop, transport, session_factory): proxy=transport.proxy, # either None or a dict with host, port ) - elif transport.type == u'rawsocket': + elif transport.type == 'rawsocket': serializer = create_transport_serializer(transport.serializers[0]) factory = WampRawSocketClientFactory(session_factory, serializer=serializer) @@ -130,8 +121,8 @@ def _is_ssl_error(self, e): def _check_native_endpoint(self, endpoint): if isinstance(endpoint, dict): - if u'tls' in endpoint: - tls = endpoint[u'tls'] + if 'tls' in endpoint: + tls = endpoint['tls'] if isinstance(tls, (dict, bool)): pass elif isinstance(tls, ssl.SSLContext): @@ -158,7 +149,7 @@ def _connect_transport(self, loop, transport, session_factory, done): # own method (or three!)... if transport.proxy: - timeout = transport.endpoint.get(u'timeout', 10) # in seconds + timeout = transport.endpoint.get('timeout', 10) # in seconds if type(timeout) != int: raise ValueError('invalid type {} for timeout in client endpoint configuration'.format(type(timeout))) # do we support HTTPS proxies? @@ -171,37 +162,37 @@ def _connect_transport(self, loop, transport, session_factory, done): time_f = asyncio.ensure_future(asyncio.wait_for(f, timeout=timeout)) return self._wrap_connection_future(transport, done, time_f) - elif transport.endpoint[u'type'] == u'tcp': + elif transport.endpoint['type'] == 'tcp': - version = transport.endpoint.get(u'version', 4) + version = transport.endpoint.get('version', 4) if version not in [4, 6]: raise ValueError('invalid IP version {} in client endpoint configuration'.format(version)) - host = transport.endpoint[u'host'] + host = transport.endpoint['host'] if type(host) != str: raise ValueError('invalid type {} for host in client endpoint configuration'.format(type(host))) - port = transport.endpoint[u'port'] + port = transport.endpoint['port'] if type(port) != int: raise ValueError('invalid type {} for port in client endpoint configuration'.format(type(port))) - timeout = transport.endpoint.get(u'timeout', 10) # in seconds + timeout = transport.endpoint.get('timeout', 10) # in seconds if type(timeout) != int: raise ValueError('invalid type {} for timeout in client endpoint configuration'.format(type(timeout))) - tls = transport.endpoint.get(u'tls', None) + tls = transport.endpoint.get('tls', None) tls_hostname = None # create a TLS enabled connecting TCP socket if tls: if isinstance(tls, dict): for k in tls.keys(): - if k not in [u"hostname", u"trust_root"]: + if k not in ["hostname", "trust_root"]: raise ValueError("Invalid key '{}' in 'tls' config".format(k)) - hostname = tls.get(u'hostname', host) + hostname = tls.get('hostname', host) if type(hostname) != str: raise ValueError('invalid type {} for hostname in TLS client endpoint configuration'.format(hostname)) - cert_fname = tls.get(u'trust_root', None) + cert_fname = tls.get('trust_root', None) tls_hostname = hostname tls = True @@ -232,9 +223,9 @@ def _connect_transport(self, loop, transport, session_factory, done): time_f = asyncio.ensure_future(asyncio.wait_for(f, timeout=timeout)) return self._wrap_connection_future(transport, done, time_f) - elif transport.endpoint[u'type'] == u'unix': - path = transport.endpoint[u'path'] - timeout = int(transport.endpoint.get(u'timeout', 10)) # in seconds + elif transport.endpoint['type'] == 'unix': + path = transport.endpoint['path'] + timeout = int(transport.endpoint.get('timeout', 10)) # in seconds f = loop.create_unix_connection( protocol_factory=factory, diff --git a/autobahn/asyncio/rawsocket.py b/autobahn/asyncio/rawsocket.py index f5dd72bfa..25ca4168e 100644 --- a/autobahn/asyncio/rawsocket.py +++ b/autobahn/asyncio/rawsocket.py @@ -24,13 +24,7 @@ # ############################################################################### -from __future__ import absolute_import - -try: - import asyncio -except ImportError: - # trollious for py2 support - however it has been deprecated - import trollius as asyncio +import asyncio import struct import math import copy @@ -388,7 +382,7 @@ def supports_serializer(self, ser_id): self.abort() return False - def get_channel_id(self, channel_id_type=u'tls-unique'): + def get_channel_id(self, channel_id_type='tls-unique'): """ Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id` """ @@ -412,7 +406,7 @@ def serializer_id(self): self._serializer = copy.copy(self.factory._serializer) return self._serializer.RAWSOCKET_SERIALIZER_ID - def get_channel_id(self, channel_id_type=u'tls-unique'): + def get_channel_id(self, channel_id_type='tls-unique'): """ Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id` """ diff --git a/autobahn/asyncio/test/test_asyncio_rawsocket.py b/autobahn/asyncio/test/test_asyncio_rawsocket.py index b9b50df41..2b6385fcf 100644 --- a/autobahn/asyncio/test/test_asyncio_rawsocket.py +++ b/autobahn/asyncio/test/test_asyncio_rawsocket.py @@ -19,7 +19,7 @@ class Test(TestCase): def test_sers(self): serializers = get_serializers() self.assertTrue(len(serializers) > 0) - m = serializers[0]().serialize(message.Abort(u'close')) + m = serializers[0]().serialize(message.Abort('close')) print(m) self.assertTrue(m) @@ -187,7 +187,7 @@ def fact(): s = proto._serializer.RAWSOCKET_SERIALIZER_ID proto.data_received(bytes(bytearray([0x7F, 0xF0 | s, 0, 0]))) client.onOpen.assert_called_once_with(proto) - proto.send(message.Abort(u'close')) + proto.send(message.Abort('close')) for d in messages[1:]: proto.data_received(d) self.assertTrue(client.onMessage.called) @@ -210,7 +210,7 @@ def fact_server(): proto.data_received(bytes(bytearray([0x7F, 0xF0 | s, 0, 0]))) self.assertTrue(proto._serializer) server.onOpen.assert_called_once_with(proto) - proto.send(message.Abort(u'close')) + proto.send(message.Abort('close')) for d in messages[1:]: proto.data_received(d) self.assertTrue(server.onMessage.called) diff --git a/autobahn/asyncio/util.py b/autobahn/asyncio/util.py index 41f66a153..8113d57ec 100644 --- a/autobahn/asyncio/util.py +++ b/autobahn/asyncio/util.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - try: from asyncio import sleep # noqa except ImportError: @@ -52,7 +50,7 @@ def transport_channel_id(transport, is_server, channel_id_type): received on one TLS channel cannot be forwarded on another. """ - if channel_id_type not in [u'tls-unique']: + if channel_id_type not in ['tls-unique']: raise Exception("invalid channel ID type {}".format(channel_id_type)) ssl_obj = transport.get_extra_info('ssl_object') @@ -67,11 +65,11 @@ def transport_channel_id(transport, is_server, channel_id_type): def peer2str(peer): if isinstance(peer, tuple): ip_ver = 4 if len(peer) == 2 else 6 - return u"tcp{2}:{0}:{1}".format(peer[0], peer[1], ip_ver) + return "tcp{2}:{0}:{1}".format(peer[0], peer[1], ip_ver) elif isinstance(peer, str): - return u"unix:{0}".format(peer) + return "unix:{0}".format(peer) else: - return u"?:{0}".format(peer) + return "?:{0}".format(peer) def get_serializers(): diff --git a/autobahn/asyncio/wamp.py b/autobahn/asyncio/wamp.py index 0f7f6c2c1..9ce1291d9 100644 --- a/autobahn/asyncio/wamp.py +++ b/autobahn/asyncio/wamp.py @@ -24,17 +24,9 @@ # ############################################################################### -from __future__ import absolute_import +import asyncio import signal - -try: - import asyncio -except ImportError: - # Trollius >= 0.3 was renamed to asyncio - # noinspection PyUnresolvedReferences - import trollius as asyncio - import txaio txaio.use_asyncio() # noqa @@ -189,7 +181,7 @@ def create(): else: create = make - if self.url.startswith(u'rs'): + if self.url.startswith('rs'): # try to parse RawSocket URL .. isSecure, host, port = parse_rs_url(self.url) diff --git a/autobahn/asyncio/websocket.py b/autobahn/asyncio/websocket.py index 97a494c43..fb5352fe0 100644 --- a/autobahn/asyncio/websocket.py +++ b/autobahn/asyncio/websocket.py @@ -24,8 +24,9 @@ # ############################################################################### -from __future__ import absolute_import - +import asyncio +from asyncio import iscoroutine +from asyncio import Future from collections import deque import txaio @@ -37,22 +38,6 @@ from autobahn.websocket import protocol from autobahn.websocket.types import TransportDetails -try: - import asyncio - from asyncio import iscoroutine - from asyncio import Future -except ImportError: - # Trollius >= 0.3 was renamed - # noinspection PyUnresolvedReferences - import trollius as asyncio - from trollius import iscoroutine - from trollius import Future - -if hasattr(asyncio, 'ensure_future'): - ensure_future = asyncio.ensure_future -else: # Deprecated since Python 3.4.4 - ensure_future = getattr(asyncio, 'async') - __all__ = ( 'WebSocketServerProtocol', 'WebSocketClientProtocol', @@ -88,7 +73,7 @@ def connection_made(self, transport): try: self.peer = peer2str(transport.get_extra_info('peername')) except: - self.peer = u"?" + self.peer = "?" self._connectionMade() @@ -126,57 +111,57 @@ def _closeConnection(self, abort=False): def _onOpen(self): res = self.onOpen() if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onMessageBegin(self, isBinary): res = self.onMessageBegin(isBinary) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onMessageFrameBegin(self, length): res = self.onMessageFrameBegin(length) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onMessageFrameData(self, payload): res = self.onMessageFrameData(payload) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onMessageFrameEnd(self): res = self.onMessageFrameEnd() if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onMessageFrame(self, payload): res = self.onMessageFrame(payload) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onMessageEnd(self): res = self.onMessageEnd() if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onMessage(self, payload, isBinary): res = self.onMessage(payload, isBinary) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onPing(self, payload): res = self.onPing(payload) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onPong(self, payload): res = self.onPong(payload) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def _onClose(self, wasClean, code, reason): res = self.onClose(wasClean, code, reason) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def registerProducer(self, producer, streaming): raise Exception("not implemented") @@ -202,7 +187,7 @@ class WebSocketServerProtocol(WebSocketAdapterProtocol, protocol.WebSocketServer log = txaio.make_logger() - def get_channel_id(self, channel_id_type=u'tls-unique'): + def get_channel_id(self, channel_id_type='tls-unique'): """ Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id` """ @@ -224,12 +209,12 @@ class WebSocketClientProtocol(WebSocketAdapterProtocol, protocol.WebSocketClient def _onConnect(self, response): res = self.onConnect(response) if yields(res): - ensure_future(res) + asyncio.ensure_future(res) def startTLS(self): raise Exception("WSS over explicit proxies not implemented") - def get_channel_id(self, channel_id_type=u'tls-unique'): + def get_channel_id(self, channel_id_type='tls-unique'): """ Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id` """ @@ -243,7 +228,7 @@ def _create_transport_details(self): is_secure = self.transport.get_extra_info('peercert', None) is not None if is_secure: secure_channel_id = { - u'tls-unique': transport_channel_id(self.transport, False, 'tls-unique'), + 'tls-unique': transport_channel_id(self.transport, False, 'tls-unique'), } else: secure_channel_id = {} diff --git a/autobahn/exception.py b/autobahn/exception.py index 5d6432cee..22bdbc811 100644 --- a/autobahn/exception.py +++ b/autobahn/exception.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.util import public __all__ = ( diff --git a/autobahn/nvx/__init__.py b/autobahn/nvx/__init__.py index e64e1aa5e..670824bce 100644 --- a/autobahn/nvx/__init__.py +++ b/autobahn/nvx/__init__.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.nvx._utf8validator import Utf8Validator # noqa __all__ = ('Utf8Validator',) diff --git a/autobahn/nvx/_utf8validator.py b/autobahn/nvx/_utf8validator.py index f5ca3d0dd..e72fc872e 100644 --- a/autobahn/nvx/_utf8validator.py +++ b/autobahn/nvx/_utf8validator.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os from cffi import FFI diff --git a/autobahn/nvx/test/test_utf8validator.py b/autobahn/nvx/test/test_utf8validator.py index 28af7db2d..eea857cd9 100644 --- a/autobahn/nvx/test/test_utf8validator.py +++ b/autobahn/nvx/test/test_utf8validator.py @@ -26,8 +26,6 @@ # ############################################################################### -from __future__ import absolute_import - import struct import unittest @@ -337,7 +335,7 @@ def _test_utf8_incremental(self, validator, withPositions=True): k = 2 validator.reset() - self.assertEqual((True, True, 15, 15)[:k], validator.validate(u'µ@ßöäüàá'.encode('utf8'))[:k]) + self.assertEqual((True, True, 15, 15)[:k], validator.validate('µ@ßöäüàá'.encode('utf8'))[:k]) validator.reset() self.assertEqual((False, False, 0, 0)[:k], validator.validate(b"\xF5")[:k]) diff --git a/autobahn/rawsocket/test/test_rawsocket_url.py b/autobahn/rawsocket/test/test_rawsocket_url.py index 6b11fa87f..544db9fca 100644 --- a/autobahn/rawsocket/test/test_rawsocket_url.py +++ b/autobahn/rawsocket/test/test_rawsocket_url.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import unittest from autobahn.rawsocket.util import create_url, parse_url diff --git a/autobahn/rawsocket/util.py b/autobahn/rawsocket/util.py index d031e011d..b4569adc6 100644 --- a/autobahn/rawsocket/util.py +++ b/autobahn/rawsocket/util.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.util import public @@ -75,24 +73,24 @@ def create_url(hostname, port=None, isSecure=False): if hostname == 'unix': - netloc = u"unix:%s" % port + netloc = "unix:%s" % port else: assert port is None or (type(port) == int and port in range(0, 65535)) if port is not None: - netloc = u"%s:%d" % (hostname, port) + netloc = "%s:%d" % (hostname, port) else: if isSecure: - netloc = u"{}:443".format(hostname) + netloc = "{}:443".format(hostname) else: - netloc = u"{}:80".format(hostname) + netloc = "{}:80".format(hostname) if isSecure: - scheme = u"rss" + scheme = "rss" else: - scheme = u"rs" + scheme = "rs" - return u"{}://{}".format(scheme, netloc) + return "{}://{}".format(scheme, netloc) @public @@ -133,7 +131,7 @@ def parse_url(url): if parsed.fragment is not None and parsed.fragment != "": raise Exception("invalid RawSocket URL: non-empty fragment '{}'".format(parsed.fragment)) - if parsed.hostname == u"unix": + if parsed.hostname == "unix": # Unix domain sockets sockets # rs://unix:/tmp/file.sock => unix:/tmp/file.sock => /tmp/file.sock diff --git a/autobahn/test/__init__.py b/autobahn/test/__init__.py index e850c8687..c7f657ba4 100644 --- a/autobahn/test/__init__.py +++ b/autobahn/test/__init__.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import, print_function - class FakeTransport(object): _written = b"" diff --git a/autobahn/test/test_rng.py b/autobahn/test/test_rng.py index 5bf728c4a..b387ef996 100644 --- a/autobahn/test/test_rng.py +++ b/autobahn/test/test_rng.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import sys import unittest diff --git a/autobahn/test/test_util.py b/autobahn/test/test_util.py index bf0652b12..b12e83e14 100644 --- a/autobahn/test/test_util.py +++ b/autobahn/test/test_util.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import unittest from autobahn.util import IdGenerator diff --git a/autobahn/twisted/__init__.py b/autobahn/twisted/__init__.py index 80e24ad2d..bf7fdfd6d 100644 --- a/autobahn/twisted/__init__.py +++ b/autobahn/twisted/__init__.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import - import sys import platform @@ -83,7 +81,7 @@ 'ApplicationSession', ) -__ident__ = u'Autobahn/{}-Twisted/{}-{}/{}'.format(autobahn.__version__, twisted.__version__, platform.python_implementation(), '.'.join([str(x) for x in list(sys.version_info[:3])])) +__ident__ = 'Autobahn/{}-Twisted/{}-{}/{}'.format(autobahn.__version__, twisted.__version__, platform.python_implementation(), '.'.join([str(x) for x in list(sys.version_info[:3])])) """ AutobahnPython library implementation (eg. "Autobahn/0.13.0-Twisted/15.5.0-CPython/3.5.1") """ diff --git a/autobahn/twisted/choosereactor.py b/autobahn/twisted/choosereactor.py index 470159a87..bed57d1ac 100644 --- a/autobahn/twisted/choosereactor.py +++ b/autobahn/twisted/choosereactor.py @@ -24,8 +24,6 @@ # ######################################## -from __future__ import absolute_import - import sys import traceback diff --git a/autobahn/twisted/component.py b/autobahn/twisted/component.py index a9c62b2ea..6c1294ff6 100644 --- a/autobahn/twisted/component.py +++ b/autobahn/twisted/component.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import, print_function - from functools import wraps from twisted.internet.interfaces import IStreamClientEndpoint @@ -76,7 +74,7 @@ def _create_transport_factory(reactor, transport, session_factory): """ Create a WAMP-over-XXX transport factory. """ - if transport.type == u'websocket': + if transport.type == 'websocket': serializers = create_transport_serializers(transport) factory = WampWebSocketClientFactory( session_factory, @@ -85,7 +83,7 @@ def _create_transport_factory(reactor, transport, session_factory): proxy=transport.proxy, # either None or a dict with host, port ) - elif transport.type == u'rawsocket': + elif transport.type == 'rawsocket': serializer = create_transport_serializer(transport.serializers[0]) factory = WampRawSocketClientFactory(session_factory, serializer=serializer) @@ -119,25 +117,25 @@ def _create_transport_endpoint(reactor, endpoint_config): endpoint = IStreamClientEndpoint(endpoint_config) else: # create a connecting TCP socket - if endpoint_config[u'type'] == u'tcp': + if endpoint_config['type'] == 'tcp': - version = endpoint_config.get(u'version', 4) + version = endpoint_config.get('version', 4) if version not in [4, 6]: raise ValueError('invalid IP version {} in client endpoint configuration'.format(version)) - host = endpoint_config[u'host'] + host = endpoint_config['host'] if type(host) != str: raise ValueError('invalid type {} for host in client endpoint configuration'.format(type(host))) - port = endpoint_config[u'port'] + port = endpoint_config['port'] if type(port) != int: raise ValueError('invalid type {} for port in client endpoint configuration'.format(type(port))) - timeout = endpoint_config.get(u'timeout', 10) # in seconds + timeout = endpoint_config.get('timeout', 10) # in seconds if type(timeout) != int: raise ValueError('invalid type {} for timeout in client endpoint configuration'.format(type(timeout))) - tls = endpoint_config.get(u'tls', None) + tls = endpoint_config.get('tls', None) # create a TLS enabled connecting TCP socket if tls: @@ -151,13 +149,13 @@ def _create_transport_endpoint(reactor, endpoint_config): elif isinstance(tls, dict): for k in tls.keys(): - if k not in [u"hostname", u"trust_root"]: + if k not in ["hostname", "trust_root"]: raise ValueError("Invalid key '{}' in 'tls' config".format(k)) - hostname = tls.get(u'hostname', host) + hostname = tls.get('hostname', host) if type(hostname) != str: raise ValueError('invalid type {} for hostname in TLS client endpoint configuration'.format(hostname)) trust_root = None - cert_fname = tls.get(u"trust_root", None) + cert_fname = tls.get("trust_root", None) if cert_fname is not None: trust_root = Certificate.loadPEM(open(cert_fname, 'r').read()) context = optionsForClientTLS(hostname, trustRoot=trust_root) @@ -205,9 +203,9 @@ def _create_transport_endpoint(reactor, endpoint_config): assert(False), 'should not arrive here' # create a connecting Unix domain socket - elif endpoint_config[u'type'] == u'unix': - path = endpoint_config[u'path'] - timeout = int(endpoint_config.get(u'timeout', 10)) # in seconds + elif endpoint_config['type'] == 'unix': + path = endpoint_config['path'] + timeout = int(endpoint_config.get('timeout', 10)) # in seconds endpoint = UNIXClientEndpoint(reactor, path, timeout=timeout) else: @@ -248,8 +246,8 @@ def _check_native_endpoint(self, endpoint): if IStreamClientEndpoint.providedBy(endpoint): pass elif isinstance(endpoint, dict): - if u'tls' in endpoint: - tls = endpoint[u'tls'] + if 'tls' in endpoint: + tls = endpoint['tls'] if isinstance(tls, (dict, bool)): pass elif IOpenSSLClientConnectionCreator.providedBy(tls): diff --git a/autobahn/twisted/cryptosign.py b/autobahn/twisted/cryptosign.py index c9ef36843..36d6b9c02 100644 --- a/autobahn/twisted/cryptosign.py +++ b/autobahn/twisted/cryptosign.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import, print_function - from autobahn.wamp.cryptosign import HAS_CRYPTOSIGN, SigningKey from twisted.internet.defer import inlineCallbacks, returnValue @@ -109,7 +107,7 @@ def on_connect(agent): for blob, comment in keys: raw = _unpack(blob) algo = raw[0] - if algo == u'ssh-ed25519': + if algo == 'ssh-ed25519': algo, _pubkey = raw if _pubkey == pubkey: key_data = _pubkey diff --git a/autobahn/twisted/forwarder.py b/autobahn/twisted/forwarder.py index fab716e8c..d7f2dbda6 100644 --- a/autobahn/twisted/forwarder.py +++ b/autobahn/twisted/forwarder.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import txaio txaio.use_twisted() diff --git a/autobahn/twisted/rawsocket.py b/autobahn/twisted/rawsocket.py index 7601580d9..96481daf0 100644 --- a/autobahn/twisted/rawsocket.py +++ b/autobahn/twisted/rawsocket.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import copy import math import txaio @@ -187,7 +185,7 @@ def send(self, msg): else: payload_len = len(payload) if 0 < self._max_len_send < payload_len: - emsg = u'tried to send RawSocket message with size {} exceeding payload limit of {} octets'.format( + emsg = 'tried to send RawSocket message with size {} exceeding payload limit of {} octets'.format( payload_len, self._max_len_send) self.log.warn(emsg) raise PayloadExceededError(emsg) @@ -316,7 +314,7 @@ def dataReceived(self, data): if data: self.dataReceived(data) - def get_channel_id(self, channel_id_type=u'tls-unique'): + def get_channel_id(self, channel_id_type='tls-unique'): """ Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id` """ @@ -408,7 +406,7 @@ def dataReceived(self, data): if data: self.dataReceived(data) - def get_channel_id(self, channel_id_type=u'tls-unique'): + def get_channel_id(self, channel_id_type='tls-unique'): """ Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id` """ diff --git a/autobahn/twisted/resource.py b/autobahn/twisted/resource.py index ac221fbd9..5a24906fd 100644 --- a/autobahn/twisted/resource.py +++ b/autobahn/twisted/resource.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import - from zope.interface import implementer from twisted.protocols.policies import ProtocolWrapper @@ -119,7 +117,7 @@ def render(self, request): # request is over HTTP2. request.channel.getPeer() is valid at # this point however if request.channel.transport is None: - # render an "error, you're doing HTTPS over WSS" webpage + # render an "error, yo're doing HTTPS over WSS" webpage from autobahn.websocket import protocol request.setResponseCode(426, b"Upgrade required") # RFC says MUST set upgrade along with 426 code: diff --git a/autobahn/twisted/test/test_application_runner.py b/autobahn/twisted/test/test_application_runner.py index c7408ed2c..6c4621fb5 100644 --- a/autobahn/twisted/test/test_application_runner.py +++ b/autobahn/twisted/test/test_application_runner.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - # t.i.reactor doesn't exist until we've imported it once, but we # need it to exist so we can @patch it out in the tests ... from twisted.internet import reactor # noqa @@ -45,7 +43,7 @@ class TestApplicationRunner(unittest.TestCase): @patch('twisted.internet.reactor') def test_runner_default(self, fakereactor): fakereactor.connectTCP = Mock(side_effect=raise_error) - runner = ApplicationRunner(u'ws://fake:1234/ws', u'dummy realm') + runner = ApplicationRunner('ws://fake:1234/ws', 'dummy realm') # we should get "our" RuntimeError when we call run self.assertRaises(RuntimeError, runner.run, raise_error) @@ -58,7 +56,7 @@ def test_runner_default(self, fakereactor): @inlineCallbacks def test_runner_no_run(self, fakereactor): fakereactor.connectTCP = Mock(side_effect=raise_error) - runner = ApplicationRunner(u'ws://fake:1234/ws', u'dummy realm') + runner = ApplicationRunner('ws://fake:1234/ws', 'dummy realm') try: yield runner.run(raise_error, start_reactor=False) @@ -77,7 +75,7 @@ def test_runner_no_run(self, fakereactor): def test_runner_no_run_happypath(self, fakereactor): proto = Mock() fakereactor.connectTCP = Mock(return_value=succeed(proto)) - runner = ApplicationRunner(u'ws://fake:1234/ws', u'dummy realm') + runner = ApplicationRunner('ws://fake:1234/ws', 'dummy realm') d = runner.run(Mock(), start_reactor=False) @@ -94,12 +92,12 @@ def test_runner_no_run_happypath(self, fakereactor): @patch('twisted.internet.reactor') def test_runner_bad_proxy(self, fakereactor): - proxy = u'myproxy' + proxy = 'myproxy' self.assertRaises( AssertionError, ApplicationRunner, - u'ws://fake:1234/ws', u'dummy realm', + 'ws://fake:1234/ws', 'dummy realm', proxy=proxy ) @@ -108,9 +106,9 @@ def test_runner_proxy(self, fakereactor): proto = Mock() fakereactor.connectTCP = Mock(return_value=succeed(proto)) - proxy = {'host': u'myproxy', 'port': 3128} + proxy = {'host': 'myproxy', 'port': 3128} - runner = ApplicationRunner(u'ws://fake:1234/ws', u'dummy realm', proxy=proxy) + runner = ApplicationRunner('ws://fake:1234/ws', 'dummy realm', proxy=proxy) d = runner.run(Mock(), start_reactor=False) diff --git a/autobahn/twisted/test/test_choosereactor.py b/autobahn/twisted/test/test_choosereactor.py index 36e2d78b0..c24675f22 100644 --- a/autobahn/twisted/test/test_choosereactor.py +++ b/autobahn/twisted/test/test_choosereactor.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import sys import twisted.internet diff --git a/autobahn/twisted/test/test_component.py b/autobahn/twisted/test/test_component.py index a5af6aee4..8d00cab31 100644 --- a/autobahn/twisted/test/test_component.py +++ b/autobahn/twisted/test/test_component.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os from mock import Mock, patch @@ -96,7 +94,7 @@ def connect(factory, **kw): payload_encryption_cryptobox=True, ) - msg = Welcome(123456, dict(broker=features), realm=u'realm') + msg = Welcome(123456, dict(broker=features), realm='realm') serializer = JsonSerializer() data, is_binary = serializer.serialize(msg) proto.onMessage(data, is_binary) @@ -125,14 +123,14 @@ def test_successful_proxy_connect(self, fake_sleep): directlyProvides(endpoint, IStreamClientEndpoint) component = Component( transports={ - u"type": u"websocket", - u"url": u"ws://127.0.0.1/ws", - u"endpoint": endpoint, - u"proxy": { - u"host": u"10.0.0.0", - u"port": 65000, + "type": "websocket", + "url": "ws://127.0.0.1/ws", + "endpoint": endpoint, + "proxy": { + "host": "10.0.0.0", + "port": 65000, }, - u"max_retries": 0, + "max_retries": 0, }, is_fatal=lambda _: True, ) @@ -216,9 +214,9 @@ def test_cancel_while_waiting(self): "type": "websocket", "url": "ws://127.0.0.1/ws", "endpoint": endpoint, - u"max_retries": 0, - u"max_retry_delay": 5, - u"initial_retry_delay": 5, + "max_retries": 0, + "max_retry_delay": 5, + "initial_retry_delay": 5, }, ) @@ -231,7 +229,7 @@ def test_cancel_while_waiting(self): def connect(factory, **kw): d = Deferred() - reactor.callLater(10, d.errback(RuntimeError("no connect for you"))) + reactor.callLater(10, d.errback(RuntimeError("no connect for yo"))) return d endpoint.connect = connect @@ -281,14 +279,14 @@ def connect(factory, **kw): from autobahn.wamp import role subrole = role.RoleSubscriberFeatures() - msg = Hello(u"realm", roles=dict(subscriber=subrole), authmethods=[u"anonymous"]) + msg = Hello("realm", roles=dict(subscriber=subrole), authmethods=["anonymous"]) serializer = JsonSerializer() data, is_binary = serializer.serialize(msg) proto.onMessage(data, is_binary) - msg = Abort(reason=u"wamp.error.no_auth_method") + msg = Abort(reason="wamp.error.no_auth_method") proto.onMessage(*serializer.serialize(msg)) - proto.onClose(False, 100, u"wamp.error.no_auth_method") + proto.onClose(False, 100, "wamp.error.no_auth_method") return succeed(proto) endpoint.connect = connect diff --git a/autobahn/twisted/test/test_endpoint_plugins.py b/autobahn/twisted/test/test_endpoint_plugins.py index 18dca859d..2e960221c 100644 --- a/autobahn/twisted/test/test_endpoint_plugins.py +++ b/autobahn/twisted/test/test_endpoint_plugins.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from twisted.trial.unittest import TestCase diff --git a/autobahn/twisted/test/test_protocol.py b/autobahn/twisted/test/test_protocol.py index e4ea59b94..554503450 100644 --- a/autobahn/twisted/test/test_protocol.py +++ b/autobahn/twisted/test/test_protocol.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import, print_function - from mock import Mock from autobahn.util import wildcards2patterns @@ -138,7 +136,7 @@ class WebSocketOriginMatching(unittest.TestCase): def setUp(self): self.factory = WebSocketServerFactory() self.factory.setProtocolOptions( - allowedOrigins=[u'127.0.0.1:*', u'*.example.com:*'] + allowedOrigins=['127.0.0.1:*', '*.example.com:*'] ) self.proto = WebSocketServerProtocol() self.proto.transport = StringTransport() @@ -178,7 +176,7 @@ def test_match_wrong_scheme_origin(self): # some monkey-business since we already did this in setUp, but # we want a different set of matching origins self.factory.setProtocolOptions( - allowedOrigins=[u'http://*.example.com:*'] + allowedOrigins=['http://*.example.com:*'] ) self.proto.allowedOriginsPatterns = self.factory.allowedOriginsPatterns self.proto.allowedOrigins = self.factory.allowedOrigins diff --git a/autobahn/twisted/test/test_rawsocket.py b/autobahn/twisted/test/test_rawsocket.py index b55128241..c0c72a947 100644 --- a/autobahn/twisted/test/test_rawsocket.py +++ b/autobahn/twisted/test/test_rawsocket.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import, print_function - import unittest from autobahn.twisted.rawsocket import (WampRawSocketServerFactory, diff --git a/autobahn/twisted/test/test_websocket_agent.py b/autobahn/twisted/test/test_websocket_agent.py index 511ad41e3..ea7b8d118 100644 --- a/autobahn/twisted/test/test_websocket_agent.py +++ b/autobahn/twisted/test/test_websocket_agent.py @@ -30,7 +30,7 @@ def onMessage(self, msg, is_binary): self.sendMessage(msg) agent = create_memory_agent(self.reactor, self.pumper, EchoServer) - proto = yield agent.open(u"ws://localhost:1234/ws", dict()) + proto = yield agent.open("ws://localhost:1234/ws", dict()) messages = [] @@ -57,7 +57,7 @@ def onMessage(self, msg, is_binary): self.sendMessage(msg) agent = create_memory_agent(self.reactor, self.pumper, EchoServer) - proto = yield agent.open(u"wss://localhost:1234/ws", dict()) + proto = yield agent.open("wss://localhost:1234/ws", dict()) messages = [] diff --git a/autobahn/twisted/testing/__init__.py b/autobahn/twisted/testing/__init__.py index ceb57102d..ba426a88c 100644 --- a/autobahn/twisted/testing/__init__.py +++ b/autobahn/twisted/testing/__init__.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - # IHostnameResolver et al. were added in Twisted 17.1.0 .. before # that, it was IResolverSimple only. diff --git a/autobahn/twisted/util.py b/autobahn/twisted/util.py index 6fecdb007..dca9a7150 100644 --- a/autobahn/twisted/util.py +++ b/autobahn/twisted/util.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import hashlib from twisted.internet.defer import Deferred @@ -77,16 +75,16 @@ def peer2str(addr): :rtype: unicode """ if isinstance(addr, IPv4Address): - res = u"tcp4:{0}:{1}".format(addr.host, addr.port) + res = "tcp4:{0}:{1}".format(addr.host, addr.port) elif _HAS_IPV6 and isinstance(addr, IPv6Address): - res = u"tcp6:{0}:{1}".format(addr.host, addr.port) + res = "tcp6:{0}:{1}".format(addr.host, addr.port) elif isinstance(addr, UNIXAddress): - res = u"unix:{0}".format(addr.name) + res = "unix:{0}".format(addr.name) elif isinstance(addr, PipeAddress): - res = u"" + res = "" else: # gracefully fallback if we can't map the peer's address - res = u"?:{0}".format(addr) + res = "?:{0}".format(addr) return res @@ -103,7 +101,7 @@ def transport_channel_id(transport, is_server, channel_id_type): received on one TLS channel cannot be forwarded on another. """ - if channel_id_type not in [u'tls-unique']: + if channel_id_type not in ['tls-unique']: raise Exception("invalid channel ID type {}".format(channel_id_type)) if hasattr(transport, '_tlsConnection'): diff --git a/autobahn/twisted/wamp.py b/autobahn/twisted/wamp.py index 2bdf0a81a..9b40b2ad6 100644 --- a/autobahn/twisted/wamp.py +++ b/autobahn/twisted/wamp.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import inspect import binascii import random @@ -245,7 +243,7 @@ def create(): else: create = make - if self.url.startswith(u'rs'): + if self.url.startswith('rs'): # try to parse RawSocket URL .. isSecure, host, port = parse_rs_url(self.url) @@ -518,7 +516,7 @@ def __call__(self, config): self.session = _ApplicationSession(config, self) return self.session - def run(self, url=u"ws://localhost:8080/ws", realm=u"realm1", start_reactor=True): + def run(self, url="ws://localhost:8080/ws", realm="realm1", start_reactor=True): """ Run the application. @@ -786,35 +784,35 @@ class AuthCryptoSign(object): def __init__(self, **kw): # should put in checkconfig or similar for key in kw.keys(): - if key not in [u'authextra', u'authid', u'authrole', u'privkey']: + if key not in ['authextra', 'authid', 'authrole', 'privkey']: raise ValueError( "Unexpected key '{}' for {}".format(key, self.__class__.__name__) ) - for key in [u'privkey', u'authid']: + for key in ['privkey', 'authid']: if key not in kw: raise ValueError( "Must provide '{}' for cryptosign".format(key) ) for key in kw.get('authextra', dict()): - if key not in [u'pubkey']: + if key not in ['pubkey']: raise ValueError( "Unexpected key '{}' in 'authextra'".format(key) ) from autobahn.wamp.cryptosign import SigningKey self._privkey = SigningKey.from_key_bytes( - binascii.a2b_hex(kw[u'privkey']) + binascii.a2b_hex(kw['privkey']) ) - if u'pubkey' in kw.get(u'authextra', dict()): - pubkey = kw[u'authextra'][u'pubkey'] + if 'pubkey' in kw.get('authextra', dict()): + pubkey = kw['authextra']['pubkey'] if pubkey != self._privkey.public_key(): raise ValueError( "Public key doesn't correspond to private key" ) else: - kw[u'authextra'] = kw.get(u'authextra', dict()) - kw[u'authextra'][u'pubkey'] = self._privkey.public_key() + kw['authextra'] = kw.get('authextra', dict()) + kw['authextra']['pubkey'] = self._privkey.public_key() self._args = kw def on_challenge(self, session, challenge): @@ -829,24 +827,24 @@ class AuthWampCra(object): def __init__(self, **kw): # should put in checkconfig or similar for key in kw.keys(): - if key not in [u'authextra', u'authid', u'authrole', u'secret']: + if key not in ['authextra', 'authid', 'authrole', 'secret']: raise ValueError( "Unexpected key '{}' for {}".format(key, self.__class__.__name__) ) - for key in [u'secret', u'authid']: + for key in ['secret', 'authid']: if key not in kw: raise ValueError( "Must provide '{}' for wampcra".format(key) ) self._args = kw - self._secret = kw.pop(u'secret') + self._secret = kw.pop('secret') if not isinstance(self._secret, str): self._secret = self._secret.decode('utf8') def on_challenge(self, session, challenge): key = self._secret.encode('utf8') - if u'salt' in challenge.extra: + if 'salt' in challenge.extra: key = auth.derive_key( key, challenge.extra['salt'], diff --git a/autobahn/twisted/websocket.py b/autobahn/twisted/websocket.py index 1c9b7cbb7..ba5d8a978 100644 --- a/autobahn/twisted/websocket.py +++ b/autobahn/twisted/websocket.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from base64 import b64encode, b64decode from zope.interface import implementer @@ -150,8 +148,8 @@ def _endpoint_from_config(reactor, factory, transport_config, options): factory.contextFactory = context_factory endpoint = endpoints.HostnameEndpoint( reactor, - factory.proxy[u'host'], - factory.proxy[u'port'], + factory.proxy['host'], + factory.proxy['port'], # timeout, option? ) else: @@ -235,7 +233,7 @@ class WebSocketAdapterProtocol(twisted.internet.protocol.Protocol): Adapter class for Twisted WebSocket client and server protocols. """ - peer = u'' + peer = '' log = txaio.make_logger() @@ -245,7 +243,7 @@ def connectionMade(self): self.peer = peer2str(self.transport.getPeer()) except AttributeError: # ProcessProtocols lack getPeer() - self.peer = u'process:{}'.format(self.transport.pid) + self.peer = 'process:{}'.format(self.transport.pid) self._connectionMade() self.log.debug('Connection made to {peer}', peer=self.peer) @@ -357,7 +355,7 @@ class WebSocketServerProtocol(WebSocketAdapterProtocol, protocol.WebSocketServer log = txaio.make_logger() - def get_channel_id(self, channel_id_type=u'tls-unique'): + def get_channel_id(self, channel_id_type='tls-unique'): """ Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id` """ @@ -381,7 +379,7 @@ def startTLS(self): self.log.debug("Starting TLS upgrade") self.transport.startTLS(self.factory.contextFactory) - def get_channel_id(self, channel_id_type=u'tls-unique'): + def get_channel_id(self, channel_id_type='tls-unique'): """ Implements :func:`autobahn.wamp.interfaces.ITransport.get_channel_id` """ @@ -401,7 +399,7 @@ def _create_transport_details(self): is_secure = ISSLTransport.providedBy(self.transport) if is_secure: secure_channel_id = { - u'tls-unique': transport_channel_id(self.transport, False, u'tls-unique'), + 'tls-unique': transport_channel_id(self.transport, False, 'tls-unique'), } else: secure_channel_id = {} @@ -507,14 +505,14 @@ def onConnect(self, requestOrResponse): request = requestOrResponse for p in request.protocols: if p in self.factory._subprotocols: - self._binaryMode = (p != u'base64') + self._binaryMode = (p != 'base64') return p - raise ConnectionDeny(ConnectionDeny.NOT_ACCEPTABLE, u'this server only speaks {0} WebSocket subprotocols'.format(self.factory._subprotocols)) + raise ConnectionDeny(ConnectionDeny.NOT_ACCEPTABLE, 'this server only speaks {0} WebSocket subprotocols'.format(self.factory._subprotocols)) elif isinstance(requestOrResponse, ConnectionResponse): response = requestOrResponse if response.protocol not in self.factory._subprotocols: - self._fail_connection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_PROTOCOL_ERROR, u'this client only speaks {0} WebSocket subprotocols'.format(self.factory._subprotocols)) - self._binaryMode = (response.protocol != u'base64') + self._fail_connection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_PROTOCOL_ERROR, 'this client only speaks {0} WebSocket subprotocols'.format(self.factory._subprotocols)) + self._binaryMode = (response.protocol != 'base64') else: # should not arrive here raise Exception("logic error") @@ -524,13 +522,13 @@ def onOpen(self): def onMessage(self, payload, isBinary): if isBinary != self._binaryMode: - self._fail_connection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_UNSUPPORTED_DATA, u'message payload type does not match the negotiated subprotocol') + self._fail_connection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_UNSUPPORTED_DATA, 'message payload type does not match the negotiated subprotocol') else: if not isBinary: try: payload = b64decode(payload) except Exception as e: - self._fail_connection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_INVALID_PAYLOAD, u'message payload base64 decoding error: {0}'.format(e)) + self._fail_connection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_INVALID_PAYLOAD, 'message payload base64 decoding error: {0}'.format(e)) self._proto.dataReceived(payload) # noinspection PyUnusedLocal @@ -596,7 +594,7 @@ def __init__(self, :type url: unicode """ self._factory = factory - self._subprotocols = [u'binary', u'base64'] + self._subprotocols = ['binary', 'base64'] if subprotocol: self._subprotocols.append(subprotocol) @@ -659,7 +657,7 @@ def __init__(self, :type url: unicode """ self._factory = factory - self._subprotocols = [u'binary', u'base64'] + self._subprotocols = ['binary', 'base64'] if subprotocol: self._subprotocols.append(subprotocol) @@ -732,7 +730,7 @@ def connectWS(factory, contextFactory=None, timeout=30, bindAddress=None): if factory.proxy is not None: factory.contextFactory = contextFactory - conn = reactor.connectTCP(factory.proxy[u'host'], factory.proxy[u'port'], factory, timeout, bindAddress) + conn = reactor.connectTCP(factory.proxy['host'], factory.proxy['port'], factory, timeout, bindAddress) else: if factory.isSecure: conn = reactor.connectSSL(factory.host, factory.port, factory, contextFactory, timeout, bindAddress) diff --git a/autobahn/util.py b/autobahn/util.py index e8a8fbd93..6025e056a 100644 --- a/autobahn/util.py +++ b/autobahn/util.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os import time import struct @@ -197,7 +195,7 @@ def utcstr(ts=None): assert(ts is None or isinstance(ts, datetime)) if ts is None: ts = datetime.utcnow() - return u"{0}Z".format(ts.strftime(u"%Y-%m-%dT%H:%M:%S.%f")[:-3]) + return "{0}Z".format(ts.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]) @public @@ -346,16 +344,16 @@ def newid(length=16): # we take out the following 9 chars (leaving 27), because there # is visual ambiguity: 0/O/D, 1/I, 8/B, 2/Z -DEFAULT_TOKEN_CHARS = u'345679ACEFGHJKLMNPQRSTUVWXY' +DEFAULT_TOKEN_CHARS = '345679ACEFGHJKLMNPQRSTUVWXY' """ Default set of characters to create rtokens from. """ -DEFAULT_ZBASE32_CHARS = u'13456789abcdefghijkmnopqrstuwxyz' +DEFAULT_ZBASE32_CHARS = '13456789abcdefghijkmnopqrstuwxyz' """ Our choice of confusing characters to eliminate is: `0', `l', `v', and `2'. Our reasoning is that `0' is potentially mistaken for `o', that `l' is potentially -mistaken for `1' or `i', that `v' is potentially mistaken for `u' or `r' +mistaken for `1' or `i', that `v' is potentially mistaken for `' or `r' (especially in handwriting) and that `2' is potentially mistaken for `z' (especially in handwriting). @@ -423,11 +421,11 @@ def generate_token(char_groups, chars_per_group, chars=None, sep=None, lower_cas chars = chars or DEFAULT_TOKEN_CHARS if lower_case: chars = chars.lower() - sep = sep or u'-' + sep = sep or '-' rng = random.SystemRandom() - token_value = u''.join(rng.choice(chars) for _ in range(char_groups * chars_per_group)) + token_value = ''.join(rng.choice(chars) for _ in range(char_groups * chars_per_group)) if chars_per_group > 1: - return sep.join(map(u''.join, zip(*[iter(token_value)] * chars_per_group))) + return sep.join(map(''.join, zip(*[iter(token_value)] * chars_per_group))) else: return token_value @@ -435,37 +433,37 @@ def generate_token(char_groups, chars_per_group, chars=None, sep=None, lower_cas @public def generate_activation_code(): """ - Generate a one-time activation code or token of the form ``u'W97F-96MJ-YGJL'``. + Generate a one-time activation code or token of the form ``'W97F-96MJ-YGJL'``. The generated value is cryptographically strong and has (at least) 57 bits of entropy. :returns: The generated activation code. :rtype: str """ - return generate_token(char_groups=3, chars_per_group=4, chars=DEFAULT_TOKEN_CHARS, sep=u'-', lower_case=False) + return generate_token(char_groups=3, chars_per_group=4, chars=DEFAULT_TOKEN_CHARS, sep='-', lower_case=False) @public def generate_user_password(): """ - Generate a secure, random user password of the form ``u'kgojzi61dn5dtb6d'``. + Generate a secure, random user password of the form ``'kgojzi61dn5dtb6d'``. The generated value is cryptographically strong and has (at least) 76 bits of entropy. :returns: The generated password. :rtype: str """ - return generate_token(char_groups=16, chars_per_group=1, chars=DEFAULT_ZBASE32_CHARS, sep=u'-', lower_case=True) + return generate_token(char_groups=16, chars_per_group=1, chars=DEFAULT_ZBASE32_CHARS, sep='-', lower_case=True) @public def generate_serial_number(): """ - Generate a globally unique serial / product code of the form ``u'YRAC-EL4X-FQQE-AW4T-WNUV-VN6T'``. + Generate a globally unique serial / product code of the form ``'YRAC-EL4X-FQQE-AW4T-WNUV-VN6T'``. The generated value is cryptographically strong and has (at least) 114 bits of entropy. :returns: The generated serial number / product code. :rtype: str """ - return generate_token(char_groups=6, chars_per_group=4, chars=DEFAULT_TOKEN_CHARS, sep=u'-', lower_case=False) + return generate_token(char_groups=6, chars_per_group=4, chars=DEFAULT_TOKEN_CHARS, sep='-', lower_case=False) # Select the most precise walltime measurement function available @@ -876,8 +874,8 @@ def _maybe_tls_reason(instance): """ if _is_tls_error(instance): ssl_error = instance.args[0][0] - return u"SSL error: {msg} (in {func})".format( + return "SSL error: {msg} (in {func})".format( func=ssl_error[1], msg=ssl_error[2], ) - return u"" + return "" diff --git a/autobahn/wamp/__init__.py b/autobahn/wamp/__init__.py index 3bd4d8504..79fff00bb 100644 --- a/autobahn/wamp/__init__.py +++ b/autobahn/wamp/__init__.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.wamp.types import \ ComponentConfig, \ SessionDetails, \ diff --git a/autobahn/wamp/auth.py b/autobahn/wamp/auth.py index 1c6796bbc..c1202c572 100644 --- a/autobahn/wamp/auth.py +++ b/autobahn/wamp/auth.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os import base64 import struct @@ -95,14 +93,14 @@ def create_authenticator(name, **kwargs): # experimental authentication API class AuthAnonymous(object): - name = u'anonymous' + name = 'anonymous' def __init__(self, **kw): self._args = kw @property def authextra(self): - return self._args.get(u'authextra', dict()) + return self._args.get('authextra', dict()) def on_challenge(self, session, challenge): raise RuntimeError( @@ -117,12 +115,12 @@ def on_welcome(self, msg, authextra): class AuthTicket(object): - name = u'ticket' + name = 'ticket' def __init__(self, **kw): self._args = kw try: - self._ticket = self._args.pop(u'ticket') + self._ticket = self._args.pop('ticket') except KeyError: raise ValueError( "ticket authentication requires 'ticket=' kwarg" @@ -130,10 +128,10 @@ def __init__(self, **kw): @property def authextra(self): - return self._args.get(u'authextra', dict()) + return self._args.get('authextra', dict()) def on_challenge(self, session, challenge): - assert challenge.method == u"ticket" + assert challenge.method == "ticket" return self._ticket def on_welcome(self, msg, authextra): @@ -144,45 +142,45 @@ def on_welcome(self, msg, authextra): class AuthCryptoSign(object): - name = u'cryptosign' + name = 'cryptosign' def __init__(self, **kw): # should put in checkconfig or similar for key in kw.keys(): - if key not in [u'authextra', u'authid', u'authrole', u'privkey']: + if key not in ['authextra', 'authid', 'authrole', 'privkey']: raise ValueError( "Unexpected key '{}' for {}".format(key, self.__class__.__name__) ) - for key in [u'privkey', u'authid']: + for key in ['privkey', 'authid']: if key not in kw: raise ValueError( "Must provide '{}' for cryptosign".format(key) ) for key in kw.get('authextra', dict()): - if key not in [u'pubkey']: + if key not in ['pubkey']: raise ValueError( "Unexpected key '{}' in 'authextra'".format(key) ) from autobahn.wamp.cryptosign import SigningKey self._privkey = SigningKey.from_key_bytes( - binascii.a2b_hex(kw[u'privkey']) + binascii.a2b_hex(kw['privkey']) ) - if u'pubkey' in kw.get(u'authextra', dict()): - pubkey = kw[u'authextra'][u'pubkey'] + if 'pubkey' in kw.get('authextra', dict()): + pubkey = kw['authextra']['pubkey'] if pubkey != self._privkey.public_key(): raise ValueError( "Public key doesn't correspond to private key" ) else: - kw[u'authextra'] = kw.get(u'authextra', dict()) - kw[u'authextra'][u'pubkey'] = self._privkey.public_key() + kw['authextra'] = kw.get('authextra', dict()) + kw['authextra']['pubkey'] = self._privkey.public_key() self._args = kw @property def authextra(self): - return self._args.get(u'authextra', dict()) + return self._args.get('authextra', dict()) def on_challenge(self, session, challenge): return self._privkey.sign_challenge(session, challenge) @@ -230,7 +228,7 @@ class AuthScram(object): NOTE: This is a prototype of a draft spec; see https://github.com/wamp-proto/wamp-proto/issues/135 """ - name = u'scram' + name = 'scram' def __init__(self, **kw): if not HAS_ARGON: @@ -247,11 +245,11 @@ def authextra(self): if self._client_nonce is None: self._client_nonce = base64.b64encode(os.urandom(16)).decode('ascii') return { - u"nonce": self._client_nonce, + "nonce": self._client_nonce, } def on_challenge(self, session, challenge): - assert challenge.method == u"scram" + assert challenge.method == "scram" assert self._client_nonce is not None required_args = ['nonce', 'kdf', 'salt', 'iterations'] optional_args = ['memory', 'channel_binding'] @@ -267,31 +265,31 @@ def on_challenge(self, session, challenge): "WAMP-SCRAM challenge has unknown attribute '{}'".format(k) ) - channel_binding = challenge.extra.get(u'channel_binding', u'') - server_nonce = challenge.extra[u'nonce'] # base64 - salt = challenge.extra[u'salt'] # base64 - iterations = int(challenge.extra[u'iterations']) - memory = int(challenge.extra.get(u'memory', -1)) + channel_binding = challenge.extra.get('channel_binding', '') + server_nonce = challenge.extra['nonce'] # base64 + salt = challenge.extra['salt'] # base64 + iterations = int(challenge.extra['iterations']) + memory = int(challenge.extra.get('memory', -1)) password = self._args['password'].encode('utf8') # supplied by user authid = saslprep(self._args['authid']) - algorithm = challenge.extra[u'kdf'] + algorithm = challenge.extra['kdf'] client_nonce = self._client_nonce self._auth_message = ( - u"{client_first_bare},{server_first},{client_final_no_proof}".format( - client_first_bare=u"n={},r={}".format(authid, client_nonce), - server_first=u"r={},s={},i={}".format(server_nonce, salt, iterations), - client_final_no_proof=u"c={},r={}".format(channel_binding, server_nonce), + "{client_first_bare},{server_first},{client_final_no_proof}".format( + client_first_bare="n={},r={}".format(authid, client_nonce), + server_first="r={},s={},i={}".format(server_nonce, salt, iterations), + client_final_no_proof="c={},r={}".format(channel_binding, server_nonce), ) ).encode('ascii') - if algorithm == u'argon2id-13': + if algorithm == 'argon2id-13': if memory == -1: raise ValueError( "WAMP-SCRAM 'argon2id-13' challenge requires 'memory' parameter" ) self._salted_password = _hash_argon2id13_secret(password, salt, iterations, memory) - elif algorithm == u'pbkdf2': + elif algorithm == 'pbkdf2': self._salted_password = _hash_pbkdf2_secret(password, salt, iterations) else: raise RuntimeError( @@ -330,33 +328,33 @@ def on_welcome(self, session, authextra): class AuthWampCra(object): - name = u'wampcra' + name = 'wampcra' def __init__(self, **kw): # should put in checkconfig or similar for key in kw.keys(): - if key not in [u'authextra', u'authid', u'authrole', u'secret']: + if key not in ['authextra', 'authid', 'authrole', 'secret']: raise ValueError( "Unexpected key '{}' for {}".format(key, self.__class__.__name__) ) - for key in [u'secret', u'authid']: + for key in ['secret', 'authid']: if key not in kw: raise ValueError( "Must provide '{}' for wampcra".format(key) ) self._args = kw - self._secret = kw.pop(u'secret') + self._secret = kw.pop('secret') if not isinstance(self._secret, str): self._secret = self._secret.decode('utf8') @property def authextra(self): - return self._args.get(u'authextra', dict()) + return self._args.get('authextra', dict()) def on_challenge(self, session, challenge): key = self._secret.encode('utf8') - if u'salt' in challenge.extra: + if 'salt' in challenge.extra: key = derive_key( key, challenge.extra['salt'], @@ -420,7 +418,7 @@ def compute_totp(secret, offset=0): digest = hmac.new(key, msg, hashlib.sha1).digest() o = 15 & (digest[19]) token = (struct.unpack('>I', digest[o:o + 4])[0] & 0x7fffffff) % 1000000 - return u'{0:06d}'.format(token) + return '{0:06d}'.format(token) @public @@ -465,7 +463,7 @@ def qrcode_from_totp(secret, label, issuer): import io buffer = io.BytesIO() - data = pyqrcode.create(u'otpauth://totp/{}?secret={}&issuer={}'.format(label, secret, issuer)) + data = pyqrcode.create('otpauth://totp/{}?secret={}&issuer={}'.format(label, secret, issuer)) data.svg(buffer, omithw=True) return buffer.getvalue() @@ -556,7 +554,7 @@ def derive_key(secret, salt, iterations=1000, keylen=32): return binascii.b2a_base64(key).strip() -WCS_SECRET_CHARSET = u"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" +WCS_SECRET_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" """ The characters from which :func:`autobahn.wamp.auth.generate_wcs` generates secrets. """ @@ -580,7 +578,7 @@ def generate_wcs(length=14): :rtype: bytes """ assert(type(length) == int) - return u"".join([random.choice(WCS_SECRET_CHARSET) for _ in range(length)]).encode('ascii') + return "".join([random.choice(WCS_SECRET_CHARSET) for _ in range(length)]).encode('ascii') @public diff --git a/autobahn/wamp/component.py b/autobahn/wamp/component.py index 9b29547ab..122f921ab 100644 --- a/autobahn/wamp/component.py +++ b/autobahn/wamp/component.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import - import itertools import random from functools import partial @@ -201,7 +199,7 @@ def _create_transport(index, transport, check_native_endpoint=None): ', '.join([repr(s) for s in valid_serializers]), ) ) - serializer_config = transport.get('serializers', [u'cbor', u'json']) + serializer_config = transport.get('serializers', ['cbor', 'json']) elif kind == 'rawsocket': if 'endpoint' not in transport: @@ -235,7 +233,7 @@ def _create_transport(index, transport, check_native_endpoint=None): raise ValueError("'serializer' must be a string") serializer_config = [transport['serializer']] else: - serializer_config = [u'cbor'] + serializer_config = ['cbor'] else: assert False, 'should not arrive here' @@ -367,8 +365,8 @@ def subscribe(self, topic, options=None): For example:: @component.subscribe( - u"some.topic", - options=SubscribeOptions(match=u'prefix'), + "some.topic", + options=SubscribeOptions(match='prefix'), ) def topic(*args, **kw): print("some.topic({}, {}): event received".format(args, kw)) @@ -390,7 +388,7 @@ def register(self, uri, options=None): For example:: @component.register( - u"com.example.add", + "com.example.add", options=RegisterOptions(invoke='round_robin'), ) def add(*args, **kw): @@ -406,7 +404,7 @@ def do_registration(session, details): return fn return decorator - def __init__(self, main=None, transports=None, config=None, realm=u'realm1', extra=None, + def __init__(self, main=None, transports=None, config=None, realm='realm1', extra=None, authentication=None, session_factory=None, is_fatal=None): """ :param main: After a transport has been connected and a session @@ -487,7 +485,7 @@ def __init__(self, main=None, transports=None, config=None, realm=u'realm1', ext # use WAMP-over-WebSocket to localhost when no transport is specified at all if transports is None: - transports = u'ws://127.0.0.1:8080/ws' + transports = 'ws://127.0.0.1:8080/ws' # allows to provide an URL instead of a list of transports if isinstance(transports, (str, str)): @@ -603,17 +601,17 @@ def handle_connect_error(fail): # if txaio.using_asyncio and isinstance(fail.value, asyncio.CancelledError): # unrecoverable_error = True - self.log.debug(u'component failed: {error}', error=txaio.failure_message(fail)) - self.log.debug(u'{tb}', tb=txaio.failure_format_traceback(fail)) + self.log.debug('component failed: {error}', error=txaio.failure_message(fail)) + self.log.debug('{tb}', tb=txaio.failure_format_traceback(fail)) # If this is a "fatal error" that will never work, # we bail out now if isinstance(fail.value, ApplicationError): - self.log.error(u"{msg}", msg=fail.value.error_message()) + self.log.error("{msg}", msg=fail.value.error_message()) elif isinstance(fail.value, OSError): # failed to connect entirely, like nobody # listening etc. - self.log.info(u"Connection failed: {msg}", msg=txaio.failure_message(fail)) + self.log.info("Connection failed: {msg}", msg=txaio.failure_message(fail)) elif self._is_ssl_error(fail.value): # Quoting pyOpenSSL docs: "Whenever @@ -627,10 +625,10 @@ def handle_connect_error(fail): # (and 'args' is a 1-tuple containing the above # 3-tuple...) ssl_lib, ssl_func, ssl_reason = fail.value.args[0][0] - self.log.error(u"TLS failure: {reason}", reason=ssl_reason) + self.log.error("TLS failure: {reason}", reason=ssl_reason) else: self.log.error( - u'Connection failed: {error}', + 'Connection failed: {error}', error=txaio.failure_message(fail), ) @@ -676,7 +674,7 @@ def transport_check(_): self.log.debug('Entering re-connect loop') if not self._can_reconnect(): - err_msg = u"Component failed: Exhausted all transport connect attempts" + err_msg = "Component failed: Exhausted all transport connect attempts" self.log.info(err_msg) try: raise RuntimeError(err_msg) @@ -769,7 +767,7 @@ def on_leave(session, details): details=details, ) if not txaio.is_called(done): - if details.reason in [u"wamp.close.normal"]: + if details.reason in ["wamp.close.normal"]: txaio.resolve(done, None) else: f = txaio.create_failure( @@ -817,7 +815,7 @@ def on_disconnect(session, was_clean): if not txaio.is_called(done): if not was_clean: self.log.warn( - u"Session disconnected uncleanly" + "Session disconnected uncleanly" ) else: # eg the session has left the realm, and the transport was properly diff --git a/autobahn/wamp/cryptobox.py b/autobahn/wamp/cryptobox.py index 2398c255d..1bc597668 100644 --- a/autobahn/wamp/cryptobox.py +++ b/autobahn/wamp/cryptobox.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.util import public from autobahn.wamp.interfaces import IPayloadCodec @@ -168,7 +166,7 @@ def set_key(self, uri, key): assert(key is None or isinstance(key, Key) or type(key) == str) if type(key) == str: key = Key(originator_priv=key, responder_priv=key) - if uri == u'': + if uri == '': self._default_key = key else: if key is None: @@ -221,9 +219,9 @@ def encode(self, is_originating, uri, args=None, kwargs=None): return None payload = { - u'uri': uri, - u'args': args, - u'kwargs': kwargs + 'uri': uri, + 'args': args, + 'kwargs': kwargs } nonce = random(Box.NONCE_SIZE) payload_ser = _json_dumps(payload).encode('utf8') @@ -236,7 +234,7 @@ def encode(self, is_originating, uri, args=None, kwargs=None): payload_bytes = bytes(payload_encr) payload_key = None - return EncodedPayload(payload_bytes, u'cryptobox', u'json', enc_key=payload_key) + return EncodedPayload(payload_bytes, 'cryptobox', 'json', enc_key=payload_key) @public def decode(self, is_originating, uri, encoded_payload): @@ -245,7 +243,7 @@ def decode(self, is_originating, uri, encoded_payload): """ assert(type(uri) == str) assert(isinstance(encoded_payload, EncodedPayload)) - assert(encoded_payload.enc_algo == u'cryptobox') + assert(encoded_payload.enc_algo == 'cryptobox') box = self._get_box(is_originating, uri) @@ -254,14 +252,14 @@ def decode(self, is_originating, uri, encoded_payload): payload_ser = box.decrypt(encoded_payload.payload, encoder=RawEncoder) - if encoded_payload.enc_serializer != u'json': + if encoded_payload.enc_serializer != 'json': raise Exception("received encrypted payload, but don't know how to process serializer '{}'".format(encoded_payload.enc_serializer)) payload = _json_loads(payload_ser.decode('utf8')) - uri = payload.get(u'uri', None) - args = payload.get(u'args', None) - kwargs = payload.get(u'kwargs', None) + uri = payload.get('uri', None) + args = payload.get('args', None) + kwargs = payload.get('kwargs', None) return uri, args, kwargs diff --git a/autobahn/wamp/cryptosign.py b/autobahn/wamp/cryptosign.py index dab93dec1..c13ef7f57 100644 --- a/autobahn/wamp/cryptosign.py +++ b/autobahn/wamp/cryptosign.py @@ -24,9 +24,6 @@ # ############################################################################### -from __future__ import absolute_import -from __future__ import print_function - import binascii import struct @@ -99,7 +96,7 @@ def _read_ssh_ed25519_pubkey(keydata): raise Exception('invalid SSH Ed25519 public key') algo, keydata, comment = parts - if algo != u'ssh-ed25519': + if algo != 'ssh-ed25519': raise Exception('not a Ed25519 SSH public key (but {})'.format(algo)) blob = binascii.a2b_base64(keydata) @@ -177,8 +174,8 @@ def _read_ssh_ed25519_privkey(keydata): # https://tools.ietf.org/html/draft-bjh21-ssh-ed25519-02 # http://blog.oddbit.com/2011/05/08/converting-openssh-public-keys/ - SSH_BEGIN = u'-----BEGIN OPENSSH PRIVATE KEY-----' - SSH_END = u'-----END OPENSSH PRIVATE KEY-----' + SSH_BEGIN = '-----BEGIN OPENSSH PRIVATE KEY-----' + SSH_END = '-----END OPENSSH PRIVATE KEY-----' OPENSSH_KEY_V1 = b'openssh-key-v1\0' if not (keydata.startswith(SSH_BEGIN) and keydata.endswith(SSH_END)): @@ -186,7 +183,7 @@ def _read_ssh_ed25519_privkey(keydata): ssh_end = keydata.find(SSH_END) keydata = keydata[len(SSH_BEGIN):ssh_end] - keydata = u''.join([x.strip() for x in keydata.split()]) + keydata = ''.join([x.strip() for x in keydata.split()]) blob = binascii.a2b_base64(keydata) blob = blob[len(OPENSSH_KEY_V1):] @@ -380,8 +377,8 @@ def __init__(self, key, comment=None): self._can_sign = isinstance(key, signing.SigningKey) def __str__(self): - comment = u'"{}"'.format(self.comment()) if self.comment() else None - return u'Key(can_sign={}, comment={}, public_key={})'.format(self.can_sign(), comment, self.public_key()) + comment = '"{}"'.format(self.comment()) if self.comment() else None + return 'Key(can_sign={}, comment={}, public_key={})'.format(self.can_sign(), comment, self.public_key()) @util.public def can_sign(self): @@ -462,19 +459,19 @@ def sign_challenge(self, session, challenge): :rtype: str """ if not isinstance(challenge, Challenge): - raise Exception(u"challenge must be instance of autobahn.wamp.types.Challenge, not {}".format(type(challenge))) + raise Exception("challenge must be instance of autobahn.wamp.types.Challenge, not {}".format(type(challenge))) - if u'challenge' not in challenge.extra: - raise Exception(u"missing challenge value in challenge.extra") + if 'challenge' not in challenge.extra: + raise Exception("missing challenge value in challenge.extra") # the challenge sent by the router (a 32 bytes random value) - challenge_hex = challenge.extra[u'challenge'] + challenge_hex = challenge.extra['challenge'] if type(challenge_hex) != str: - raise Exception(u"invalid type {} for challenge (expected a hex string)".format(type(challenge_hex))) + raise Exception("invalid type {} for challenge (expected a hex string)".format(type(challenge_hex))) if len(challenge_hex) != 64: - raise Exception(u"unexpected challenge (hex) length: was {}, but expected 64".format(len(challenge_hex))) + raise Exception("unexpected challenge (hex) length: was {}, but expected 64".format(len(challenge_hex))) # the challenge for WAMP-cryptosign is a 32 bytes random value in Hex encoding (that is, a unicode string) challenge_raw = binascii.a2b_hex(challenge_hex) @@ -573,7 +570,7 @@ def from_ssh_data(cls, keydata): key (from a SSH private key file) or a (public) verification key (from a SSH public key file). A private key file must be passphrase-less. """ - SSH_BEGIN = u'-----BEGIN OPENSSH PRIVATE KEY-----' + SSH_BEGIN = '-----BEGIN OPENSSH PRIVATE KEY-----' if keydata.startswith(SSH_BEGIN): # OpenSSH private key keydata, comment = _read_ssh_ed25519_privkey(keydata) diff --git a/autobahn/wamp/exception.py b/autobahn/wamp/exception.py index 6a14a8fe8..43f2fb448 100644 --- a/autobahn/wamp/exception.py +++ b/autobahn/wamp/exception.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.util import public from autobahn.wamp.uri import error @@ -96,57 +94,57 @@ class ApplicationError(Error): at the application level. """ - INVALID_URI = u"wamp.error.invalid_uri" + INVALID_URI = "wamp.error.invalid_uri" """ Peer provided an incorrect URI for a URI-based attribute of a WAMP message such as a realm, topic or procedure. """ - INVALID_PAYLOAD = u"wamp.error.invalid_payload" + INVALID_PAYLOAD = "wamp.error.invalid_payload" """ The application payload could not be serialized. """ - PAYLOAD_SIZE_EXCEEDED = u"wamp.error.payload_size_exceeded" + PAYLOAD_SIZE_EXCEEDED = "wamp.error.payload_size_exceeded" """ The application payload could not be transported becuase the serialized/framed payload exceeds the transport limits. """ - NO_SUCH_PROCEDURE = u"wamp.error.no_such_procedure" + NO_SUCH_PROCEDURE = "wamp.error.no_such_procedure" """ A Dealer could not perform a call, since not procedure is currently registered under the given URI. """ - PROCEDURE_ALREADY_EXISTS = u"wamp.error.procedure_already_exists" + PROCEDURE_ALREADY_EXISTS = "wamp.error.procedure_already_exists" """ A procedure could not be registered, since a procedure with the given URI is already registered. """ - PROCEDURE_EXISTS_INVOCATION_POLICY_CONFLICT = u"wamp.error.procedure_exists_with_different_invocation_policy" + PROCEDURE_EXISTS_INVOCATION_POLICY_CONFLICT = "wamp.error.procedure_exists_with_different_invocation_policy" """ A procedure could not be registered, since a procedure with the given URI is already registered, and the registration has a conflicting invocation policy. """ - NO_SUCH_REGISTRATION = u"wamp.error.no_such_registration" + NO_SUCH_REGISTRATION = "wamp.error.no_such_registration" """ A Dealer could not perform a unregister, since the given registration is not active. """ - NO_SUCH_SUBSCRIPTION = u"wamp.error.no_such_subscription" + NO_SUCH_SUBSCRIPTION = "wamp.error.no_such_subscription" """ A Broker could not perform a unsubscribe, since the given subscription is not active. """ - NO_SUCH_SESSION = u"wamp.error.no_such_session" + NO_SUCH_SESSION = "wamp.error.no_such_session" """ A router could not perform an operation, since a session ID specified was non-existant. """ - INVALID_ARGUMENT = u"wamp.error.invalid_argument" + INVALID_ARGUMENT = "wamp.error.invalid_argument" """ A call failed, since the given argument types or values are not acceptable to the called procedure - in which case the *Callee* may throw this error. Or a Router @@ -155,95 +153,95 @@ class ApplicationError(Error): """ # FIXME: this currently isn't used neither in Autobahn nor Crossbar. Check! - SYSTEM_SHUTDOWN = u"wamp.error.system_shutdown" + SYSTEM_SHUTDOWN = "wamp.error.system_shutdown" """ The *Peer* is shutting down completely - used as a ``GOODBYE`` (or ``ABORT``) reason. """ # FIXME: this currently isn't used neither in Autobahn nor Crossbar. Check! - CLOSE_REALM = u"wamp.error.close_realm" + CLOSE_REALM = "wamp.error.close_realm" """ The *Peer* want to leave the realm - used as a ``GOODBYE`` reason. """ # FIXME: this currently isn't used neither in Autobahn nor Crossbar. Check! - GOODBYE_AND_OUT = u"wamp.error.goodbye_and_out" + GOODBYE_AND_OUT = "wamp.error.goodbye_and_out" """ A *Peer* acknowledges ending of a session - used as a ``GOOBYE`` reply reason. """ - NOT_AUTHORIZED = u"wamp.error.not_authorized" + NOT_AUTHORIZED = "wamp.error.not_authorized" """ A call, register, publish or subscribe failed, since the session is not authorized to perform the operation. """ - AUTHORIZATION_FAILED = u"wamp.error.authorization_failed" + AUTHORIZATION_FAILED = "wamp.error.authorization_failed" """ A Dealer or Broker could not determine if the *Peer* is authorized to perform a join, call, register, publish or subscribe, since the authorization operation *itself* failed. E.g. a custom authorizer did run into an error. """ - AUTHENTICATION_FAILED = u"wamp.error.authentication_failed" + AUTHENTICATION_FAILED = "wamp.error.authentication_failed" """ Something failed with the authentication itself, that is, authentication could not run to end. """ - NO_AUTH_METHOD = u"wamp.error.no_auth_method" + NO_AUTH_METHOD = "wamp.error.no_auth_method" """ No authentication method the peer offered is available or active. """ - NO_SUCH_REALM = u"wamp.error.no_such_realm" + NO_SUCH_REALM = "wamp.error.no_such_realm" """ Peer wanted to join a non-existing realm (and the *Router* did not allow to auto-create the realm). """ - NO_SUCH_ROLE = u"wamp.error.no_such_role" + NO_SUCH_ROLE = "wamp.error.no_such_role" """ A *Peer* was to be authenticated under a Role that does not (or no longer) exists on the Router. For example, the *Peer* was successfully authenticated, but the Role configured does not exists - hence there is some misconfiguration in the Router. """ - NO_SUCH_PRINCIPAL = u"wamp.error.no_such_principal" + NO_SUCH_PRINCIPAL = "wamp.error.no_such_principal" """ A *Peer* was authenticated for an authid that does not or longer exists. """ - CANCELED = u"wamp.error.canceled" + CANCELED = "wamp.error.canceled" """ A Dealer or Callee canceled a call previously issued (WAMP AP). """ - TIMEOUT = u"wamp.error.timeout" + TIMEOUT = "wamp.error.timeout" """ A pending (in-flight) call was timed out. """ # FIXME: this currently isn't used neither in Autobahn nor Crossbar. Check! - NO_ELIGIBLE_CALLEE = u"wamp.error.no_eligible_callee" + NO_ELIGIBLE_CALLEE = "wamp.error.no_eligible_callee" """ A *Dealer* could not perform a call, since a procedure with the given URI is registered, but *Callee Black- and Whitelisting* and/or *Caller Exclusion* lead to the exclusion of (any) *Callee* providing the procedure (WAMP AP). """ - ENC_NO_PAYLOAD_CODEC = u"wamp.error.no_payload_codec" + ENC_NO_PAYLOAD_CODEC = "wamp.error.no_payload_codec" """ WAMP message in payload transparency mode received, but no codec set or codec did not decode the payload. """ - ENC_TRUSTED_URI_MISMATCH = u"wamp.error.encryption.trusted_uri_mismatch" + ENC_TRUSTED_URI_MISMATCH = "wamp.error.encryption.trusted_uri_mismatch" """ WAMP-cryptobox application payload end-to-end encryption error. """ - ENC_DECRYPT_ERROR = u"wamp.error.encryption.decrypt_error" + ENC_DECRYPT_ERROR = "wamp.error.encryption.decrypt_error" """ WAMP-cryptobox application payload end-to-end encryption error. """ @@ -271,18 +269,18 @@ def error_message(self): :returns: The error message. :rtype: str """ - return u'{0}: {1}'.format( + return '{0}: {1}'.format( self.error, - u' '.join([str(a) for a in self.args]), + ' '.join([str(a) for a in self.args]), ) def __unicode__(self): if self.kwargs and 'traceback' in self.kwargs: - tb = u':\n' + u'\n'.join(self.kwargs.pop('traceback')) + u'\n' - self.kwargs['traceback'] = u'...' + tb = ':\n' + '\n'.join(self.kwargs.pop('traceback')) + '\n' + self.kwargs['traceback'] = '...' else: - tb = u'' - return u"ApplicationError(error=<{0}>, args={1}, kwargs={2}, enc_algo={3}, callee={4}, callee_authid={5}, callee_authrole={6}, forward_for={7}){8}".format( + tb = '' + return "ApplicationError(error=<{0}>, args={1}, kwargs={2}, enc_algo={3}, callee={4}, callee_authid={5}, callee_authrole={6}, forward_for={7}){8}".format( self.error, list(self.args), self.kwargs, self.enc_algo, self.callee, self.callee_authid, self.callee_authrole, self.forward_for, tb) def __str__(self): diff --git a/autobahn/wamp/interfaces.py b/autobahn/wamp/interfaces.py index 66376f143..f9223c176 100644 --- a/autobahn/wamp/interfaces.py +++ b/autobahn/wamp/interfaces.py @@ -546,7 +546,7 @@ def call(self, procedure, *args, **kwargs): When the *Caller* and *Dealer* implementations support canceling of calls, the call may be canceled by canceling the returned Deferred/Future. - :param procedure: The URI of the remote procedure to be called, e.g. ``u"com.myapp.hello"``. + :param procedure: The URI of the remote procedure to be called, e.g. ``"com.myapp.hello"``. :type procedure: unicode :param args: Any positional arguments for the call. @@ -627,7 +627,7 @@ def publish(self, topic, *args, **kwargs): - If the publication fails the Deferred/Future will reject with an instance of :class:`autobahn.wamp.exception.ApplicationError`. - :param topic: The URI of the topic to publish to, e.g. ``u"com.myapp.mytopic1"``. + :param topic: The URI of the topic to publish to, e.g. ``"com.myapp.mytopic1"``. :type topic: unicode :param args: Arbitrary application payload for the event (positional arguments). diff --git a/autobahn/wamp/message.py b/autobahn/wamp/message.py index 78328dd63..fa74c71f9 100644 --- a/autobahn/wamp/message.py +++ b/autobahn/wamp/message.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import re import binascii @@ -101,19 +99,19 @@ # Value for algo attribute in end-to-end encrypted messages using cryptobox, which # is a scheme based on Curve25519, SHA512, Salsa20 and Poly1305. # See: http://cr.yp.to/highspeed/coolnacl-20120725.pdf -PAYLOAD_ENC_CRYPTO_BOX = u'cryptobox' +PAYLOAD_ENC_CRYPTO_BOX = 'cryptobox' # Payload transparency identifier for MQTT payloads (which are arbitrary binary). -PAYLOAD_ENC_MQTT = u'mqtt' +PAYLOAD_ENC_MQTT = 'mqtt' # Payload transparency identifier for XBR payloads -PAYLOAD_ENC_XBR = u'xbr' +PAYLOAD_ENC_XBR = 'xbr' # Payload transparency algorithm identifiers from the WAMP spec. PAYLOAD_ENC_STANDARD_IDENTIFIERS = [PAYLOAD_ENC_CRYPTO_BOX, PAYLOAD_ENC_MQTT, PAYLOAD_ENC_XBR] # Payload transparency serializer identifiers from the WAMP spec. -PAYLOAD_ENC_STANDARD_SERIALIZERS = [u'json', u'msgpack', u'cbor', u'ubjson', u'flatbuffers'] +PAYLOAD_ENC_STANDARD_SERIALIZERS = ['json', 'msgpack', 'cbor', 'ubjson', 'flatbuffers'] ENC_ALGO_NONE = 0 ENC_ALGO_CRYPTOBOX = 1 @@ -121,10 +119,10 @@ ENC_ALGO_XBR = 3 ENC_ALGOS = { - ENC_ALGO_NONE: u'null', - ENC_ALGO_CRYPTOBOX: u'cryptobox', - ENC_ALGO_MQTT: u'mqtt', - ENC_ALGO_XBR: u'xbr', + ENC_ALGO_NONE: 'null', + ENC_ALGO_CRYPTOBOX: 'cryptobox', + ENC_ALGO_MQTT: 'mqtt', + ENC_ALGO_XBR: 'xbr', } ENC_ALGOS_FROMSTR = {key: value for value, key in ENC_ALGOS.items()} @@ -138,13 +136,13 @@ ENC_SER_FLATBUFFERS = 6 ENC_SERS = { - ENC_SER_NONE: u'null', - ENC_SER_JSON: u'json', - ENC_SER_MSGPACK: u'msgpack', - ENC_SER_CBOR: u'cbor', - ENC_SER_UBJSON: u'ubjson', - ENC_SER_OPAQUE: u'opaque', - ENC_SER_FLATBUFFERS: u'flatbuffers', + ENC_SER_NONE: 'null', + ENC_SER_JSON: 'json', + ENC_SER_MSGPACK: 'msgpack', + ENC_SER_CBOR: 'cbor', + ENC_SER_UBJSON: 'ubjson', + ENC_SER_OPAQUE: 'opaque', + ENC_SER_FLATBUFFERS: 'flatbuffers', } ENC_SERS_FROMSTR = {key: value for value, key in ENC_SERS.items()} @@ -161,7 +159,7 @@ def is_valid_enc_algo(enc_algo): * ``"mqtt"`` * ``"xbr"`` - Users can select arbitrary identifiers too, but these MUST start with ``u"x_"``. + Users can select arbitrary identifiers too, but these MUST start with ``"x_"``. :param enc_algo: The payload transparency algorithm identifier to check. :type enc_algo: str @@ -186,7 +184,7 @@ def is_valid_enc_serializer(enc_serializer): * ``"ubjson"`` * ``"flatbuffers"`` - Users can select arbitrary identifiers too, but these MUST start with ``u"x_"``. + Users can select arbitrary identifiers too, but these MUST start with ``"x_"``. :param enc_serializer: The payload transparency serializer identifier to check. :type enc_serializer: str @@ -204,16 +202,16 @@ def b2a(data, max_len=40): elif type(data) == bytes: s = binascii.b2a_hex(data).decode('ascii') elif data is None: - s = u'-' + s = '-' else: - s = u'{}'.format(data) + s = '{}'.format(data) if len(s) > max_len: - return s[:max_len] + u'..' + return s[:max_len] + '..' else: return s -def check_or_raise_uri(value, message=u"WAMP message invalid", strict=False, allow_empty_components=False, allow_last_empty=False, allow_none=False): +def check_or_raise_uri(value, message="WAMP message invalid", strict=False, allow_empty_components=False, allow_last_empty=False, allow_none=False): """ Check a value for being a valid WAMP URI. @@ -245,11 +243,11 @@ def check_or_raise_uri(value, message=u"WAMP message invalid", strict=False, all if allow_none: return else: - raise InvalidUriError(u"{0}: URI cannot be null".format(message)) + raise InvalidUriError("{0}: URI cannot be null".format(message)) if type(value) != str: if not (value is None and allow_none): - raise InvalidUriError(u"{0}: invalid type {1} for URI".format(message, type(value))) + raise InvalidUriError("{0}: invalid type {1} for URI".format(message, type(value))) if strict: if allow_last_empty: @@ -267,12 +265,12 @@ def check_or_raise_uri(value, message=u"WAMP message invalid", strict=False, all pat = _URI_PAT_LOOSE_NON_EMPTY if not pat.match(value): - raise InvalidUriError(u'{0}: invalid value "{1}" for URI (did not match pattern "{2}" with options strict={3}, allow_empty_components={4}, allow_last_empty={5}, allow_none={6})'.format(message, value, pat.pattern, strict, allow_empty_components, allow_last_empty, allow_none)) + raise InvalidUriError('{0}: invalid value "{1}" for URI (did not match pattern "{2}" with options strict={3}, allow_empty_components={4}, allow_last_empty={5}, allow_none={6})'.format(message, value, pat.pattern, strict, allow_empty_components, allow_last_empty, allow_none)) else: return value -def check_or_raise_id(value, message=u"WAMP message invalid"): +def check_or_raise_id(value, message="WAMP message invalid"): """ Check a value for being a valid WAMP ID. @@ -291,15 +289,15 @@ def check_or_raise_id(value, message=u"WAMP message invalid"): :raises: instance of :class:`autobahn.wamp.exception.ProtocolError` """ if type(value) != int: - raise ProtocolError(u"{0}: invalid type {1} for ID".format(message, type(value))) + raise ProtocolError("{0}: invalid type {1} for ID".format(message, type(value))) # the value 0 for WAMP IDs is possible in certain WAMP messages, e.g. UNREGISTERED with # router revocation signaling! if value < 0 or value > 9007199254740992: # 2**53 - raise ProtocolError(u"{0}: invalid value {1} for ID".format(message, value)) + raise ProtocolError("{0}: invalid value {1} for ID".format(message, value)) return value -def check_or_raise_extra(value, message=u"WAMP message invalid"): +def check_or_raise_extra(value, message="WAMP message invalid"): """ Check a value for being a valid WAMP extra dictionary. @@ -318,14 +316,14 @@ def check_or_raise_extra(value, message=u"WAMP message invalid"): :raises: instance of :class:`autobahn.wamp.exception.ProtocolError` """ if type(value) != dict: - raise ProtocolError(u"{0}: invalid type {1} for WAMP extra".format(message, type(value))) + raise ProtocolError("{0}: invalid type {1} for WAMP extra".format(message, type(value))) for k in value.keys(): if not isinstance(k, str): - raise ProtocolError(u"{0}: invalid type {1} for key in WAMP extra ('{2}')".format(message, type(k), k)) + raise ProtocolError("{0}: invalid type {1} for key in WAMP extra ('{2}')".format(message, type(k), k)) return value -def _validate_kwargs(kwargs, message=u"WAMP message invalid"): +def _validate_kwargs(kwargs, message="WAMP message invalid"): """ Check a value for being a valid WAMP kwargs dictionary. @@ -354,10 +352,10 @@ def _validate_kwargs(kwargs, message=u"WAMP message invalid"): """ if kwargs is not None: if type(kwargs) != dict: - raise ProtocolError(u"{0}: invalid type {1} for WAMP kwargs".format(message, type(kwargs))) + raise ProtocolError("{0}: invalid type {1} for WAMP kwargs".format(message, type(kwargs))) for k in kwargs.keys(): if not isinstance(k, str): - raise ProtocolError(u"{0}: invalid type {1} for key in WAMP kwargs ('{2}')".format(message, type(k), k)) + raise ProtocolError("{0}: invalid type {1} for key in WAMP kwargs ('{2}')".format(message, type(k), k)) return kwargs @@ -508,7 +506,7 @@ def serialize(self, serializer): """ # only serialize if not cached .. if serializer not in self._serialized: - if serializer.NAME == u'flatbuffers': + if serializer.NAME == 'flatbuffers': # flatbuffers get special treatment .. builder = flatbuffers.Builder(1024) @@ -594,7 +592,7 @@ def __init__(self, assert(type(roles) == dict) assert(len(roles) > 0) for role in roles: - assert(role in [u'subscriber', u'publisher', u'caller', u'callee']) + assert(role in ['subscriber', 'publisher', 'caller', 'callee']) assert(isinstance(roles[role], autobahn.wamp.role.ROLE_NAME_TO_CLASS[role])) if authmethods: assert(type(authmethods) == list) @@ -634,31 +632,31 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for HELLO".format(len(wmsg))) - realm = check_or_raise_uri(wmsg[1], u"'realm' in HELLO", allow_none=True) - details = check_or_raise_extra(wmsg[2], u"'details' in HELLO") + realm = check_or_raise_uri(wmsg[1], "'realm' in HELLO", allow_none=True) + details = check_or_raise_extra(wmsg[2], "'details' in HELLO") roles = {} - if u'roles' not in details: - raise ProtocolError(u"missing mandatory roles attribute in options in HELLO") + if 'roles' not in details: + raise ProtocolError("missing mandatory roles attribute in options in HELLO") - details_roles = check_or_raise_extra(details[u'roles'], u"'roles' in 'details' in HELLO") + details_roles = check_or_raise_extra(details['roles'], "'roles' in 'details' in HELLO") if len(details_roles) == 0: - raise ProtocolError(u"empty 'roles' in 'details' in HELLO") + raise ProtocolError("empty 'roles' in 'details' in HELLO") for role in details_roles: - if role not in [u'subscriber', u'publisher', u'caller', u'callee']: + if role not in ['subscriber', 'publisher', 'caller', 'callee']: raise ProtocolError("invalid role '{0}' in 'roles' in 'details' in HELLO".format(role)) role_cls = ROLE_NAME_TO_CLASS[role] details_role = check_or_raise_extra(details_roles[role], "role '{0}' in 'roles' in 'details' in HELLO".format(role)) - if u'features' in details_role: - check_or_raise_extra(details_role[u'features'], "'features' in role '{0}' in 'roles' in 'details' in HELLO".format(role)) + if 'features' in details_role: + check_or_raise_extra(details_role['features'], "'features' in role '{0}' in 'roles' in 'details' in HELLO".format(role)) - role_features = role_cls(**details_role[u'features']) + role_features = role_cls(**details_role['features']) else: role_features = role_cls() @@ -666,8 +664,8 @@ def parse(wmsg): roles[role] = role_features authmethods = None - if u'authmethods' in details: - details_authmethods = details[u'authmethods'] + if 'authmethods' in details: + details_authmethods = details['authmethods'] if type(details_authmethods) != list: raise ProtocolError("invalid type {0} for 'authmethods' detail in HELLO".format(type(details_authmethods))) @@ -678,44 +676,44 @@ def parse(wmsg): authmethods = details_authmethods authid = None - if u'authid' in details: - details_authid = details[u'authid'] + if 'authid' in details: + details_authid = details['authid'] if type(details_authid) != str: raise ProtocolError("invalid type {0} for 'authid' detail in HELLO".format(type(details_authid))) authid = details_authid authrole = None - if u'authrole' in details: - details_authrole = details[u'authrole'] + if 'authrole' in details: + details_authrole = details['authrole'] if type(details_authrole) != str: raise ProtocolError("invalid type {0} for 'authrole' detail in HELLO".format(type(details_authrole))) authrole = details_authrole authextra = None - if u'authextra' in details: - details_authextra = details[u'authextra'] + if 'authextra' in details: + details_authextra = details['authextra'] if type(details_authextra) != dict: raise ProtocolError("invalid type {0} for 'authextra' detail in HELLO".format(type(details_authextra))) authextra = details_authextra resumable = None - if u'resumable' in details: - resumable = details[u'resumable'] + if 'resumable' in details: + resumable = details['resumable'] if type(resumable) != bool: raise ProtocolError("invalid type {0} for 'resumable' detail in HELLO".format(type(resumable))) resume_session = None - if u'resume-session' in details: - resume_session = details[u'resume-session'] + if 'resume-session' in details: + resume_session = details['resume-session'] if type(resume_session) != int: raise ProtocolError("invalid type {0} for 'resume-session' detail in HELLO".format(type(resume_session))) resume_token = None - if u'resume-token' in details: - resume_token = details[u'resume-token'] + if 'resume-token' in details: + resume_token = details['resume-token'] if type(resume_token) != str: raise ProtocolError("invalid type {0} for 'resume-token' detail in HELLO".format(type(resume_token))) else: @@ -733,35 +731,35 @@ def marshal(self): :returns: The serialized raw message. :rtype: list """ - details = {u'roles': {}} + details = {'roles': {}} for role in self.roles.values(): - details[u'roles'][role.ROLE] = {} + details['roles'][role.ROLE] = {} for feature in role.__dict__: if not feature.startswith('_') and feature != 'ROLE' and getattr(role, feature) is not None: - if u'features' not in details[u'roles'][role.ROLE]: - details[u'roles'][role.ROLE] = {u'features': {}} - details[u'roles'][role.ROLE][u'features'][feature] = getattr(role, feature) + if 'features' not in details['roles'][role.ROLE]: + details['roles'][role.ROLE] = {'features': {}} + details['roles'][role.ROLE]['features'][feature] = getattr(role, feature) if self.authmethods is not None: - details[u'authmethods'] = self.authmethods + details['authmethods'] = self.authmethods if self.authid is not None: - details[u'authid'] = self.authid + details['authid'] = self.authid if self.authrole is not None: - details[u'authrole'] = self.authrole + details['authrole'] = self.authrole if self.authextra is not None: - details[u'authextra'] = self.authextra + details['authextra'] = self.authextra if self.resumable is not None: - details[u'resumable'] = self.resumable + details['resumable'] = self.resumable if self.resume_session is not None: - details[u'resume-session'] = self.resume_session + details['resume-session'] = self.resume_session if self.resume_token is not None: - details[u'resume-token'] = self.resume_token + details['resume-token'] = self.resume_token return [Hello.MESSAGE_TYPE, self.realm, details] @@ -769,7 +767,7 @@ def __str__(self): """ Return a string representation of this message. """ - return u"Hello(realm={}, roles={}, authmethods={}, authid={}, authrole={}, authextra={}, resumable={}, resume_session={}, resume_token={})".format(self.realm, self.roles, self.authmethods, self.authid, self.authrole, self.authextra, self.resumable, self.resume_session, self.resume_token) + return "Hello(realm={}, roles={}, authmethods={}, authid={}, authrole={}, authextra={}, resumable={}, resume_session={}, resume_token={})".format(self.realm, self.roles, self.authmethods, self.authid, self.authrole, self.authextra, self.resumable, self.resume_session, self.resume_token) class Welcome(Message): @@ -854,7 +852,7 @@ def __init__(self, assert(type(roles) == dict) assert(len(roles) > 0) for role in roles: - assert(role in [u'broker', u'dealer']) + assert(role in ['broker', 'dealer']) assert(isinstance(roles[role], autobahn.wamp.role.ROLE_NAME_TO_CLASS[role])) assert(realm is None or type(realm) == str) assert(authid is None or type(authid) == str) @@ -900,32 +898,32 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for WELCOME".format(len(wmsg))) - session = check_or_raise_id(wmsg[1], u"'session' in WELCOME") - details = check_or_raise_extra(wmsg[2], u"'details' in WELCOME") + session = check_or_raise_id(wmsg[1], "'session' in WELCOME") + details = check_or_raise_extra(wmsg[2], "'details' in WELCOME") # FIXME: tigher value checking (types, URIs etc) - realm = details.get(u'realm', None) - authid = details.get(u'authid', None) - authrole = details.get(u'authrole', None) - authmethod = details.get(u'authmethod', None) - authprovider = details.get(u'authprovider', None) - authextra = details.get(u'authextra', None) + realm = details.get('realm', None) + authid = details.get('authid', None) + authrole = details.get('authrole', None) + authmethod = details.get('authmethod', None) + authprovider = details.get('authprovider', None) + authextra = details.get('authextra', None) resumed = None - if u'resumed' in details: - resumed = details[u'resumed'] + if 'resumed' in details: + resumed = details['resumed'] if not type(resumed) == bool: raise ProtocolError("invalid type {0} for 'resumed' detail in WELCOME".format(type(resumed))) resumable = None - if u'resumable' in details: - resumable = details[u'resumable'] + if 'resumable' in details: + resumable = details['resumable'] if not type(resumable) == bool: raise ProtocolError("invalid type {0} for 'resumable' detail in WELCOME".format(type(resumable))) resume_token = None - if u'resume_token' in details: - resume_token = details[u'resume_token'] + if 'resume_token' in details: + resume_token = details['resume_token'] if not type(resume_token) == str: raise ProtocolError("invalid type {0} for 'resume_token' detail in WELCOME".format(type(resume_token))) elif resumable: @@ -933,26 +931,26 @@ def parse(wmsg): roles = {} - if u'roles' not in details: - raise ProtocolError(u"missing mandatory roles attribute in options in WELCOME") + if 'roles' not in details: + raise ProtocolError("missing mandatory roles attribute in options in WELCOME") - details_roles = check_or_raise_extra(details['roles'], u"'roles' in 'details' in WELCOME") + details_roles = check_or_raise_extra(details['roles'], "'roles' in 'details' in WELCOME") if len(details_roles) == 0: - raise ProtocolError(u"empty 'roles' in 'details' in WELCOME") + raise ProtocolError("empty 'roles' in 'details' in WELCOME") for role in details_roles: - if role not in [u'broker', u'dealer']: + if role not in ['broker', 'dealer']: raise ProtocolError("invalid role '{0}' in 'roles' in 'details' in WELCOME".format(role)) role_cls = ROLE_NAME_TO_CLASS[role] details_role = check_or_raise_extra(details_roles[role], "role '{0}' in 'roles' in 'details' in WELCOME".format(role)) - if u'features' in details_role: - check_or_raise_extra(details_role[u'features'], "'features' in role '{0}' in 'roles' in 'details' in WELCOME".format(role)) + if 'features' in details_role: + check_or_raise_extra(details_role['features'], "'features' in role '{0}' in 'roles' in 'details' in WELCOME".format(role)) - role_features = role_cls(**details_roles[role][u'features']) + role_features = role_cls(**details_roles[role]['features']) else: role_features = role_cls() @@ -979,40 +977,40 @@ def marshal(self): details.update(self.custom) if self.realm: - details[u'realm'] = self.realm + details['realm'] = self.realm if self.authid: - details[u'authid'] = self.authid + details['authid'] = self.authid if self.authrole: - details[u'authrole'] = self.authrole + details['authrole'] = self.authrole if self.authrole: - details[u'authmethod'] = self.authmethod + details['authmethod'] = self.authmethod if self.authprovider: - details[u'authprovider'] = self.authprovider + details['authprovider'] = self.authprovider if self.authextra: - details[u'authextra'] = self.authextra + details['authextra'] = self.authextra if self.resumed: - details[u'resumed'] = self.resumed + details['resumed'] = self.resumed if self.resumable: - details[u'resumable'] = self.resumable + details['resumable'] = self.resumable if self.resume_token: - details[u'resume_token'] = self.resume_token + details['resume_token'] = self.resume_token - details[u'roles'] = {} + details['roles'] = {} for role in self.roles.values(): - details[u'roles'][role.ROLE] = {} + details['roles'][role.ROLE] = {} for feature in role.__dict__: if not feature.startswith('_') and feature != 'ROLE' and getattr(role, feature) is not None: - if u'features' not in details[u'roles'][role.ROLE]: - details[u'roles'][role.ROLE] = {u'features': {}} - details[u'roles'][role.ROLE][u'features'][feature] = getattr(role, feature) + if 'features' not in details['roles'][role.ROLE]: + details['roles'][role.ROLE] = {'features': {}} + details['roles'][role.ROLE]['features'][feature] = getattr(role, feature) return [Welcome.MESSAGE_TYPE, self.session, details] @@ -1020,7 +1018,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Welcome(session={}, roles={}, realm={}, authid={}, authrole={}, authmethod={}, authprovider={}, authextra={}, resumed={}, resumable={}, resume_token={})".format(self.session, self.roles, self.realm, self.authid, self.authrole, self.authmethod, self.authprovider, self.authextra, self.resumed, self.resumable, self.resume_token) + return "Welcome(session={}, roles={}, realm={}, authid={}, authrole={}, authmethod={}, authprovider={}, authextra={}, resumed={}, resumable={}, resume_token={})".format(self.session, self.roles, self.realm, self.authid, self.authrole, self.authmethod, self.authprovider, self.authextra, self.resumed, self.resumable, self.resume_token) class Abort(Message): @@ -1072,14 +1070,14 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for ABORT".format(len(wmsg))) - details = check_or_raise_extra(wmsg[1], u"'details' in ABORT") - reason = check_or_raise_uri(wmsg[2], u"'reason' in ABORT") + details = check_or_raise_extra(wmsg[1], "'details' in ABORT") + reason = check_or_raise_uri(wmsg[2], "'reason' in ABORT") message = None - if u'message' in details: + if 'message' in details: - details_message = details[u'message'] + details_message = details['message'] if type(details_message) != str: raise ProtocolError("invalid type {0} for 'message' detail in ABORT".format(type(details_message))) @@ -1098,7 +1096,7 @@ def marshal(self): """ details = {} if self.message: - details[u'message'] = self.message + details['message'] = self.message return [Abort.MESSAGE_TYPE, details, self.reason] @@ -1106,7 +1104,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Abort(message={0}, reason={1})".format(self.message, self.reason) + return "Abort(message={0}, reason={1})".format(self.message, self.reason) class Challenge(Message): @@ -1162,7 +1160,7 @@ def parse(wmsg): if type(method) != str: raise ProtocolError("invalid type {0} for 'method' in CHALLENGE".format(type(method))) - extra = check_or_raise_extra(wmsg[2], u"'extra' in CHALLENGE") + extra = check_or_raise_extra(wmsg[2], "'extra' in CHALLENGE") obj = Challenge(method, extra) @@ -1181,7 +1179,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Challenge(method={0}, extra={1})".format(self.method, self.extra) + return "Challenge(method={0}, extra={1})".format(self.method, self.extra) class Authenticate(Message): @@ -1237,7 +1235,7 @@ def parse(wmsg): if type(signature) != str: raise ProtocolError("invalid type {0} for 'signature' in AUTHENTICATE".format(type(signature))) - extra = check_or_raise_extra(wmsg[2], u"'extra' in AUTHENTICATE") + extra = check_or_raise_extra(wmsg[2], "'extra' in AUTHENTICATE") obj = Authenticate(signature, extra) @@ -1256,7 +1254,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Authenticate(signature={0}, extra={1})".format(self.signature, self.extra) + return "Authenticate(signature={0}, extra={1})".format(self.signature, self.extra) class Goodbye(Message): @@ -1271,7 +1269,7 @@ class Goodbye(Message): The WAMP message code for this type of message. """ - DEFAULT_REASON = u"wamp.close.normal" + DEFAULT_REASON = "wamp.close.normal" """ Default WAMP closing reason. """ @@ -1319,22 +1317,22 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for GOODBYE".format(len(wmsg))) - details = check_or_raise_extra(wmsg[1], u"'details' in GOODBYE") - reason = check_or_raise_uri(wmsg[2], u"'reason' in GOODBYE") + details = check_or_raise_extra(wmsg[1], "'details' in GOODBYE") + reason = check_or_raise_uri(wmsg[2], "'reason' in GOODBYE") message = None resumable = None - if u'message' in details: + if 'message' in details: - details_message = details[u'message'] + details_message = details['message'] if type(details_message) != str: raise ProtocolError("invalid type {0} for 'message' detail in GOODBYE".format(type(details_message))) message = details_message - if u'resumable' in details: - resumable = details[u'resumable'] + if 'resumable' in details: + resumable = details['resumable'] if type(resumable) != bool: raise ProtocolError("invalid type {0} for 'resumable' detail in GOODBYE".format(type(resumable))) @@ -1353,10 +1351,10 @@ def marshal(self): """ details = {} if self.message: - details[u'message'] = self.message + details['message'] = self.message if self.resumable: - details[u'resumable'] = self.resumable + details['resumable'] = self.resumable return [Goodbye.MESSAGE_TYPE, details, self.reason] @@ -1364,7 +1362,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Goodbye(message={}, reason={}, resumable={})".format(self.message, self.reason, self.resumable) + return "Goodbye(message={}, reason={}, resumable={})".format(self.message, self.reason, self.resumable) class Error(Message): @@ -1532,9 +1530,9 @@ def parse(wmsg): Invocation.MESSAGE_TYPE]: raise ProtocolError("invalid value {0} for 'request_type' in ERROR".format(request_type)) - request = check_or_raise_id(wmsg[2], u"'request' in ERROR") - details = check_or_raise_extra(wmsg[3], u"'details' in ERROR") - error = check_or_raise_uri(wmsg[4], u"'error' in ERROR") + request = check_or_raise_id(wmsg[2], "'request' in ERROR") + details = check_or_raise_extra(wmsg[3], "'details' in ERROR") + error = check_or_raise_uri(wmsg[4], "'error' in ERROR") args = None kwargs = None @@ -1551,15 +1549,15 @@ def parse(wmsg): payload = wmsg[5] - enc_algo = details.get(u'enc_algo', None) + enc_algo = details.get('enc_algo', None) if enc_algo and not is_valid_enc_algo(enc_algo): raise ProtocolError("invalid value {0} for 'enc_algo' detail in EVENT".format(enc_algo)) - enc_key = details.get(u'enc_key', None) + enc_key = details.get('enc_key', None) if enc_key and type(enc_key) != str: raise ProtocolError("invalid type {0} for 'enc_key' detail in EVENT".format(type(enc_key))) - enc_serializer = details.get(u'enc_serializer', None) + enc_serializer = details.get('enc_serializer', None) if enc_serializer and not is_valid_enc_serializer(enc_serializer): raise ProtocolError("invalid value {0} for 'enc_serializer' detail in EVENT".format(enc_serializer)) @@ -1574,32 +1572,32 @@ def parse(wmsg): if type(kwargs) != dict: raise ProtocolError("invalid type {0} for 'kwargs' in ERROR".format(type(kwargs))) - if u'callee' in details: + if 'callee' in details: - detail_callee = details[u'callee'] + detail_callee = details['callee'] if type(detail_callee) != int: raise ProtocolError("invalid type {0} for 'callee' detail in ERROR".format(type(detail_callee))) callee = detail_callee - if u'callee_authid' in details: + if 'callee_authid' in details: - detail_callee_authid = details[u'callee_authid'] + detail_callee_authid = details['callee_authid'] if type(detail_callee_authid) != str: raise ProtocolError("invalid type {0} for 'callee_authid' detail in ERROR".format(type(detail_callee_authid))) callee_authid = detail_callee_authid - if u'callee_authrole' in details: + if 'callee_authrole' in details: - detail_callee_authrole = details[u'callee_authrole'] + detail_callee_authrole = details['callee_authrole'] if type(detail_callee_authrole) != str: raise ProtocolError("invalid type {0} for 'callee_authrole' detail in ERROR".format(type(detail_callee_authrole))) callee_authrole = detail_callee_authrole - if u'forward_for' in details: - forward_for = details[u'forward_for'] + if 'forward_for' in details: + forward_for = details['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -1642,21 +1640,21 @@ def marshal(self): details = {} if self.callee is not None: - details[u'callee'] = self.callee + details['callee'] = self.callee if self.callee_authid is not None: - details[u'callee_authid'] = self.callee_authid + details['callee_authid'] = self.callee_authid if self.callee_authrole is not None: - details[u'callee_authrole'] = self.callee_authrole + details['callee_authrole'] = self.callee_authrole if self.forward_for is not None: - details[u'forward_for'] = self.forward_for + details['forward_for'] = self.forward_for if self.payload: if self.enc_algo is not None: - details[u'enc_algo'] = self.enc_algo + details['enc_algo'] = self.enc_algo if self.enc_key is not None: - details[u'enc_key'] = self.enc_key + details['enc_key'] = self.enc_key if self.enc_serializer is not None: - details[u'enc_serializer'] = self.enc_serializer + details['enc_serializer'] = self.enc_serializer return [self.MESSAGE_TYPE, self.request_type, self.request, details, self.error, self.payload] else: if self.kwargs: @@ -1670,7 +1668,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Error(request_type={0}, request={1}, error={2}, args={3}, kwargs={4}, enc_algo={5}, enc_key={6}, enc_serializer={7}, payload={8}, callee={9}, callee_authid={10}, callee_authrole={11}, forward_for={12})".format(self.request_type, self.request, self.error, self.args, self.kwargs, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.callee, self.callee_authid, self.callee_authrole, self.forward_for) + return "Error(request_type={0}, request={1}, error={2}, args={3}, kwargs={4}, enc_algo={5}, enc_key={6}, enc_serializer={7}, payload={8}, callee={9}, callee_authid={10}, callee_authrole={11}, forward_for={12})".format(self.request_type, self.request, self.error, self.args, self.kwargs, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.callee, self.callee_authid, self.callee_authrole, self.forward_for) class Publish(Message): @@ -2368,9 +2366,9 @@ def parse(wmsg): if len(wmsg) not in (4, 5, 6): raise ProtocolError("invalid message length {0} for PUBLISH".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in PUBLISH") - options = check_or_raise_extra(wmsg[2], u"'options' in PUBLISH") - topic = check_or_raise_uri(wmsg[3], u"'topic' in PUBLISH") + request = check_or_raise_id(wmsg[1], "'request' in PUBLISH") + options = check_or_raise_extra(wmsg[2], "'options' in PUBLISH") + topic = check_or_raise_uri(wmsg[3], "'topic' in PUBLISH") args = None kwargs = None @@ -2380,15 +2378,15 @@ def parse(wmsg): payload = wmsg[4] - enc_algo = options.get(u'enc_algo', None) + enc_algo = options.get('enc_algo', None) if enc_algo and not is_valid_enc_algo(enc_algo): raise ProtocolError("invalid value {0} for 'enc_algo' option in PUBLISH".format(enc_algo)) - enc_key = options.get(u'enc_key', None) + enc_key = options.get('enc_key', None) if enc_key and type(enc_key) != str: raise ProtocolError("invalid type {0} for 'enc_key' option in PUBLISH".format(type(enc_key))) - enc_serializer = options.get(u'enc_serializer', None) + enc_serializer = options.get('enc_serializer', None) if enc_serializer and not is_valid_enc_serializer(enc_serializer): raise ProtocolError("invalid value {0} for 'enc_serializer' option in PUBLISH".format(enc_serializer)) @@ -2418,25 +2416,25 @@ def parse(wmsg): retain = None forward_for = None - if u'acknowledge' in options: + if 'acknowledge' in options: - option_acknowledge = options[u'acknowledge'] + option_acknowledge = options['acknowledge'] if type(option_acknowledge) != bool: raise ProtocolError("invalid type {0} for 'acknowledge' option in PUBLISH".format(type(option_acknowledge))) acknowledge = option_acknowledge - if u'exclude_me' in options: + if 'exclude_me' in options: - option_exclude_me = options[u'exclude_me'] + option_exclude_me = options['exclude_me'] if type(option_exclude_me) != bool: raise ProtocolError("invalid type {0} for 'exclude_me' option in PUBLISH".format(type(option_exclude_me))) exclude_me = option_exclude_me - if u'exclude' in options: + if 'exclude' in options: - option_exclude = options[u'exclude'] + option_exclude = options['exclude'] if type(option_exclude) != list: raise ProtocolError("invalid type {0} for 'exclude' option in PUBLISH".format(type(option_exclude))) @@ -2446,9 +2444,9 @@ def parse(wmsg): exclude = option_exclude - if u'exclude_authid' in options: + if 'exclude_authid' in options: - option_exclude_authid = options[u'exclude_authid'] + option_exclude_authid = options['exclude_authid'] if type(option_exclude_authid) != list: raise ProtocolError("invalid type {0} for 'exclude_authid' option in PUBLISH".format(type(option_exclude_authid))) @@ -2458,9 +2456,9 @@ def parse(wmsg): exclude_authid = option_exclude_authid - if u'exclude_authrole' in options: + if 'exclude_authrole' in options: - option_exclude_authrole = options[u'exclude_authrole'] + option_exclude_authrole = options['exclude_authrole'] if type(option_exclude_authrole) != list: raise ProtocolError("invalid type {0} for 'exclude_authrole' option in PUBLISH".format(type(option_exclude_authrole))) @@ -2470,9 +2468,9 @@ def parse(wmsg): exclude_authrole = option_exclude_authrole - if u'eligible' in options: + if 'eligible' in options: - option_eligible = options[u'eligible'] + option_eligible = options['eligible'] if type(option_eligible) != list: raise ProtocolError("invalid type {0} for 'eligible' option in PUBLISH".format(type(option_eligible))) @@ -2482,9 +2480,9 @@ def parse(wmsg): eligible = option_eligible - if u'eligible_authid' in options: + if 'eligible_authid' in options: - option_eligible_authid = options[u'eligible_authid'] + option_eligible_authid = options['eligible_authid'] if type(option_eligible_authid) != list: raise ProtocolError("invalid type {0} for 'eligible_authid' option in PUBLISH".format(type(option_eligible_authid))) @@ -2494,9 +2492,9 @@ def parse(wmsg): eligible_authid = option_eligible_authid - if u'eligible_authrole' in options: + if 'eligible_authrole' in options: - option_eligible_authrole = options[u'eligible_authrole'] + option_eligible_authrole = options['eligible_authrole'] if type(option_eligible_authrole) != list: raise ProtocolError("invalid type {0} for 'eligible_authrole' option in PUBLISH".format(type(option_eligible_authrole))) @@ -2506,13 +2504,13 @@ def parse(wmsg): eligible_authrole = option_eligible_authrole - if u'retain' in options: - retain = options[u'retain'] + if 'retain' in options: + retain = options['retain'] if type(retain) != bool: raise ProtocolError("invalid type {0} for 'retain' option in PUBLISH".format(type(retain))) - if u'forward_for' in options: - forward_for = options[u'forward_for'] + if 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -2554,35 +2552,35 @@ def marshal_options(self): options = {} if self.acknowledge is not None: - options[u'acknowledge'] = self.acknowledge + options['acknowledge'] = self.acknowledge if self.exclude_me is not None: - options[u'exclude_me'] = self.exclude_me + options['exclude_me'] = self.exclude_me if self.exclude is not None: - options[u'exclude'] = self.exclude + options['exclude'] = self.exclude if self.exclude_authid is not None: - options[u'exclude_authid'] = self.exclude_authid + options['exclude_authid'] = self.exclude_authid if self.exclude_authrole is not None: - options[u'exclude_authrole'] = self.exclude_authrole + options['exclude_authrole'] = self.exclude_authrole if self.eligible is not None: - options[u'eligible'] = self.eligible + options['eligible'] = self.eligible if self.eligible_authid is not None: - options[u'eligible_authid'] = self.eligible_authid + options['eligible_authid'] = self.eligible_authid if self.eligible_authrole is not None: - options[u'eligible_authrole'] = self.eligible_authrole + options['eligible_authrole'] = self.eligible_authrole if self.retain is not None: - options[u'retain'] = self.retain + options['retain'] = self.retain if self.payload: if self.enc_algo is not None: - options[u'enc_algo'] = self.enc_algo + options['enc_algo'] = self.enc_algo if self.enc_key is not None: - options[u'enc_key'] = self.enc_key + options['enc_key'] = self.enc_key if self.enc_serializer is not None: - options[u'enc_serializer'] = self.enc_serializer + options['enc_serializer'] = self.enc_serializer if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return options @@ -2609,7 +2607,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Publish(request={}, topic={}, args={}, kwargs={}, acknowledge={}, exclude_me={}, exclude={}, exclude_authid={}, exclude_authrole={}, eligible={}, eligible_authid={}, eligible_authrole={}, retain={}, enc_algo={}, enc_key={}, enc_serializer={}, payload={}, forward_for={})".format(self.request, self.topic, self.args, self.kwargs, self.acknowledge, self.exclude_me, self.exclude, self.exclude_authid, self.exclude_authrole, self.eligible, self.eligible_authid, self.eligible_authrole, self.retain, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.forward_for) + return "Publish(request={}, topic={}, args={}, kwargs={}, acknowledge={}, exclude_me={}, exclude={}, exclude_authid={}, exclude_authrole={}, eligible={}, eligible_authid={}, eligible_authrole={}, retain={}, enc_algo={}, enc_key={}, enc_serializer={}, payload={}, forward_for={})".format(self.request, self.topic, self.args, self.kwargs, self.acknowledge, self.exclude_me, self.exclude, self.exclude_authid, self.exclude_authrole, self.eligible, self.eligible_authid, self.eligible_authrole, self.retain, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.forward_for) class Published(Message): @@ -2661,8 +2659,8 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for PUBLISHED".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in PUBLISHED") - publication = check_or_raise_id(wmsg[2], u"'publication' in PUBLISHED") + request = check_or_raise_id(wmsg[1], "'request' in PUBLISHED") + publication = check_or_raise_id(wmsg[2], "'publication' in PUBLISHED") obj = Published(request, publication) @@ -2681,7 +2679,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Published(request={0}, publication={1})".format(self.request, self.publication) + return "Published(request={0}, publication={1})".format(self.request, self.publication) class Subscribe(Message): @@ -2696,9 +2694,9 @@ class Subscribe(Message): The WAMP message code for this type of message. """ - MATCH_EXACT = u'exact' - MATCH_PREFIX = u'prefix' - MATCH_WILDCARD = u'wildcard' + MATCH_EXACT = 'exact' + MATCH_PREFIX = 'prefix' + MATCH_WILDCARD = 'wildcard' __slots__ = ( 'request', @@ -2768,17 +2766,17 @@ def parse(wmsg): if len(wmsg) != 4: raise ProtocolError("invalid message length {0} for SUBSCRIBE".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in SUBSCRIBE") - options = check_or_raise_extra(wmsg[2], u"'options' in SUBSCRIBE") - topic = check_or_raise_uri(wmsg[3], u"'topic' in SUBSCRIBE", allow_empty_components=True) + request = check_or_raise_id(wmsg[1], "'request' in SUBSCRIBE") + options = check_or_raise_extra(wmsg[2], "'options' in SUBSCRIBE") + topic = check_or_raise_uri(wmsg[3], "'topic' in SUBSCRIBE", allow_empty_components=True) match = Subscribe.MATCH_EXACT get_retained = None forward_for = None - if u'match' in options: + if 'match' in options: - option_match = options[u'match'] + option_match = options['match'] if type(option_match) != str: raise ProtocolError("invalid type {0} for 'match' option in SUBSCRIBE".format(type(option_match))) @@ -2787,14 +2785,14 @@ def parse(wmsg): match = option_match - if u'get_retained' in options: - get_retained = options[u'get_retained'] + if 'get_retained' in options: + get_retained = options['get_retained'] if type(get_retained) != bool: raise ProtocolError("invalid type {0} for 'get_retained' option in SUBSCRIBE".format(type(get_retained))) - if u'forward_for' in options: - forward_for = options[u'forward_for'] + if 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -2819,13 +2817,13 @@ def marshal_options(self): options = {} if self.match and self.match != Subscribe.MATCH_EXACT: - options[u'match'] = self.match + options['match'] = self.match if self.get_retained is not None: - options[u'get_retained'] = self.get_retained + options['get_retained'] = self.get_retained if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return options @@ -2842,7 +2840,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Subscribe(request={0}, topic={1}, match={2}, get_retained={3}, forward_for={4})".format(self.request, self.topic, self.match, self.get_retained, self.forward_for) + return "Subscribe(request={0}, topic={1}, match={2}, get_retained={3}, forward_for={4})".format(self.request, self.topic, self.match, self.get_retained, self.forward_for) class Subscribed(Message): @@ -2894,8 +2892,8 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for SUBSCRIBED".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in SUBSCRIBED") - subscription = check_or_raise_id(wmsg[2], u"'subscription' in SUBSCRIBED") + request = check_or_raise_id(wmsg[1], "'request' in SUBSCRIBED") + subscription = check_or_raise_id(wmsg[2], "'subscription' in SUBSCRIBED") obj = Subscribed(request, subscription) @@ -2914,7 +2912,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Subscribed(request={0}, subscription={1})".format(self.request, self.subscription) + return "Subscribed(request={0}, subscription={1})".format(self.request, self.subscription) class Unsubscribe(Message): @@ -2981,16 +2979,16 @@ def parse(wmsg): if len(wmsg) not in [3, 4]: raise ProtocolError("invalid message length {0} for WAMP UNSUBSCRIBE".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in UNSUBSCRIBE") - subscription = check_or_raise_id(wmsg[2], u"'subscription' in UNSUBSCRIBE") + request = check_or_raise_id(wmsg[1], "'request' in UNSUBSCRIBE") + subscription = check_or_raise_id(wmsg[2], "'subscription' in UNSUBSCRIBE") options = None if len(wmsg) > 3: - options = check_or_raise_extra(wmsg[3], u"'options' in UNSUBSCRIBE") + options = check_or_raise_extra(wmsg[3], "'options' in UNSUBSCRIBE") forward_for = None - if options and u'forward_for' in options: - forward_for = options[u'forward_for'] + if options and 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -3020,7 +3018,7 @@ def marshal(self): """ if self.forward_for: options = { - u'forward_for': self.forward_for, + 'forward_for': self.forward_for, } return [Unsubscribe.MESSAGE_TYPE, self.request, self.subscription, options] else: @@ -3030,7 +3028,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Unsubscribe(request={0}, subscription={1}, forward_for={2})".format(self.request, self.subscription, self.forward_for) + return "Unsubscribe(request={0}, subscription={1}, forward_for={2})".format(self.request, self.subscription, self.forward_for) class Unsubscribed(Message): @@ -3094,23 +3092,23 @@ def parse(wmsg): if len(wmsg) not in [2, 3]: raise ProtocolError("invalid message length {0} for UNSUBSCRIBED".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in UNSUBSCRIBED") + request = check_or_raise_id(wmsg[1], "'request' in UNSUBSCRIBED") subscription = None reason = None if len(wmsg) > 2: - details = check_or_raise_extra(wmsg[2], u"'details' in UNSUBSCRIBED") + details = check_or_raise_extra(wmsg[2], "'details' in UNSUBSCRIBED") - if u"subscription" in details: - details_subscription = details[u"subscription"] + if "subscription" in details: + details_subscription = details["subscription"] if type(details_subscription) != int: raise ProtocolError("invalid type {0} for 'subscription' detail in UNSUBSCRIBED".format(type(details_subscription))) subscription = details_subscription - if u"reason" in details: - reason = check_or_raise_uri(details[u"reason"], u"'reason' in UNSUBSCRIBED") + if "reason" in details: + reason = check_or_raise_uri(details["reason"], "'reason' in UNSUBSCRIBED") obj = Unsubscribed(request, subscription, reason) @@ -3126,9 +3124,9 @@ def marshal(self): if self.reason is not None or self.subscription is not None: details = {} if self.reason is not None: - details[u"reason"] = self.reason + details["reason"] = self.reason if self.subscription is not None: - details[u"subscription"] = self.subscription + details["subscription"] = self.subscription return [Unsubscribed.MESSAGE_TYPE, self.request, details] else: return [Unsubscribed.MESSAGE_TYPE, self.request] @@ -3137,7 +3135,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Unsubscribed(request={0}, reason={1}, subscription={2})".format(self.request, self.reason, self.subscription) + return "Unsubscribed(request={0}, reason={1}, subscription={2})".format(self.request, self.reason, self.subscription) class Event(Message): @@ -3618,9 +3616,9 @@ def parse(wmsg): if len(wmsg) not in (4, 5, 6): raise ProtocolError("invalid message length {0} for EVENT".format(len(wmsg))) - subscription = check_or_raise_id(wmsg[1], u"'subscription' in EVENT") - publication = check_or_raise_id(wmsg[2], u"'publication' in EVENT") - details = check_or_raise_extra(wmsg[3], u"'details' in EVENT") + subscription = check_or_raise_id(wmsg[1], "'subscription' in EVENT") + publication = check_or_raise_id(wmsg[2], "'publication' in EVENT") + details = check_or_raise_extra(wmsg[3], "'details' in EVENT") args = None kwargs = None @@ -3633,15 +3631,15 @@ def parse(wmsg): payload = wmsg[4] - enc_algo = details.get(u'enc_algo', None) + enc_algo = details.get('enc_algo', None) if enc_algo and not is_valid_enc_algo(enc_algo): raise ProtocolError("invalid value {0} for 'enc_algo' detail in EVENT".format(enc_algo)) - enc_key = details.get(u'enc_key', None) + enc_key = details.get('enc_key', None) if enc_key and type(enc_key) != str: raise ProtocolError("invalid type {0} for 'enc_key' detail in EVENT".format(type(enc_key))) - enc_serializer = details.get(u'enc_serializer', None) + enc_serializer = details.get('enc_serializer', None) if enc_serializer and not is_valid_enc_serializer(enc_serializer): raise ProtocolError("invalid value {0} for 'enc_serializer' detail in EVENT".format(enc_serializer)) @@ -3663,50 +3661,50 @@ def parse(wmsg): forward_for = None x_acknowledged_delivery = None - if u'publisher' in details: + if 'publisher' in details: - detail_publisher = details[u'publisher'] + detail_publisher = details['publisher'] if type(detail_publisher) != int: raise ProtocolError("invalid type {0} for 'publisher' detail in EVENT".format(type(detail_publisher))) publisher = detail_publisher - if u'publisher_authid' in details: + if 'publisher_authid' in details: - detail_publisher_authid = details[u'publisher_authid'] + detail_publisher_authid = details['publisher_authid'] if type(detail_publisher_authid) != str: raise ProtocolError("invalid type {0} for 'publisher_authid' detail in EVENT".format(type(detail_publisher_authid))) publisher_authid = detail_publisher_authid - if u'publisher_authrole' in details: + if 'publisher_authrole' in details: - detail_publisher_authrole = details[u'publisher_authrole'] + detail_publisher_authrole = details['publisher_authrole'] if type(detail_publisher_authrole) != str: raise ProtocolError("invalid type {0} for 'publisher_authrole' detail in EVENT".format(type(detail_publisher_authrole))) publisher_authrole = detail_publisher_authrole - if u'topic' in details: + if 'topic' in details: - detail_topic = details[u'topic'] + detail_topic = details['topic'] if type(detail_topic) != str: raise ProtocolError("invalid type {0} for 'topic' detail in EVENT".format(type(detail_topic))) topic = detail_topic - if u'retained' in details: - retained = details[u'retained'] + if 'retained' in details: + retained = details['retained'] if type(retained) != bool: raise ProtocolError("invalid type {0} for 'retained' detail in EVENT".format(type(retained))) - if u'x_acknowledged_delivery' in details: - x_acknowledged_delivery = details[u'x_acknowledged_delivery'] + if 'x_acknowledged_delivery' in details: + x_acknowledged_delivery = details['x_acknowledged_delivery'] if type(x_acknowledged_delivery) != bool: raise ProtocolError("invalid type {0} for 'x_acknowledged_delivery' detail in EVENT".format(type(x_acknowledged_delivery))) - if u'forward_for' in details: - forward_for = details[u'forward_for'] + if 'forward_for' in details: + forward_for = details['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -3751,33 +3749,33 @@ def marshal(self): details = {} if self.publisher is not None: - details[u'publisher'] = self.publisher + details['publisher'] = self.publisher if self.publisher_authid is not None: - details[u'publisher_authid'] = self.publisher_authid + details['publisher_authid'] = self.publisher_authid if self.publisher_authrole is not None: - details[u'publisher_authrole'] = self.publisher_authrole + details['publisher_authrole'] = self.publisher_authrole if self.topic is not None: - details[u'topic'] = self.topic + details['topic'] = self.topic if self.retained is not None: - details[u'retained'] = self.retained + details['retained'] = self.retained if self.x_acknowledged_delivery is not None: - details[u'x_acknowledged_delivery'] = self.x_acknowledged_delivery + details['x_acknowledged_delivery'] = self.x_acknowledged_delivery if self.forward_for is not None: - details[u'forward_for'] = self.forward_for + details['forward_for'] = self.forward_for if self.payload: if self.enc_algo is not None: - details[u'enc_algo'] = self.enc_algo + details['enc_algo'] = self.enc_algo if self.enc_key is not None: - details[u'enc_key'] = self.enc_key + details['enc_key'] = self.enc_key if self.enc_serializer is not None: - details[u'enc_serializer'] = self.enc_serializer + details['enc_serializer'] = self.enc_serializer return [Event.MESSAGE_TYPE, self.subscription, self.publication, details, self.payload] else: if self.kwargs: @@ -3791,7 +3789,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Event(subscription={}, publication={}, args={}, kwargs={}, publisher={}, publisher_authid={}, publisher_authrole={}, topic={}, retained={}, enc_algo={}, enc_key={}, enc_serializer={}, payload={}, forward_for={})".format(self.subscription, self.publication, self.args, self.kwargs, self.publisher, self.publisher_authid, self.publisher_authrole, self.topic, self.retained, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.forward_for) + return "Event(subscription={}, publication={}, args={}, kwargs={}, publisher={}, publisher_authid={}, publisher_authrole={}, topic={}, retained={}, enc_algo={}, enc_key={}, enc_serializer={}, payload={}, forward_for={})".format(self.subscription, self.publication, self.args, self.kwargs, self.publisher, self.publisher_authid, self.publisher_authrole, self.topic, self.retained, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.forward_for) class EventReceived(Message): @@ -3838,7 +3836,7 @@ def parse(wmsg): if len(wmsg) != 2: raise ProtocolError("invalid message length {0} for EVENT_RECEIVED".format(len(wmsg))) - publication = check_or_raise_id(wmsg[1], u"'publication' in EVENT_RECEIVED") + publication = check_or_raise_id(wmsg[1], "'publication' in EVENT_RECEIVED") obj = EventReceived(publication) @@ -3857,7 +3855,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"EventReceived(publication={})".format(self.publication) + return "EventReceived(publication={})".format(self.publication) class Call(Message): @@ -4020,9 +4018,9 @@ def parse(wmsg): if len(wmsg) not in (4, 5, 6): raise ProtocolError("invalid message length {0} for CALL".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in CALL") - options = check_or_raise_extra(wmsg[2], u"'options' in CALL") - procedure = check_or_raise_uri(wmsg[3], u"'procedure' in CALL") + request = check_or_raise_id(wmsg[1], "'request' in CALL") + options = check_or_raise_extra(wmsg[2], "'options' in CALL") + procedure = check_or_raise_uri(wmsg[3], "'procedure' in CALL") args = None kwargs = None @@ -4035,15 +4033,15 @@ def parse(wmsg): payload = wmsg[4] - enc_algo = options.get(u'enc_algo', None) + enc_algo = options.get('enc_algo', None) if enc_algo and not is_valid_enc_algo(enc_algo): raise ProtocolError("invalid value {0} for 'enc_algo' detail in CALL".format(enc_algo)) - enc_key = options.get(u'enc_key', None) + enc_key = options.get('enc_key', None) if enc_key and type(enc_key) != str: raise ProtocolError("invalid type {0} for 'enc_key' detail in CALL".format(type(enc_key))) - enc_serializer = options.get(u'enc_serializer', None) + enc_serializer = options.get('enc_serializer', None) if enc_serializer and not is_valid_enc_serializer(enc_serializer): raise ProtocolError("invalid value {0} for 'enc_serializer' detail in CALL".format(enc_serializer)) @@ -4065,9 +4063,9 @@ def parse(wmsg): caller_authrole = None forward_for = None - if u'timeout' in options: + if 'timeout' in options: - option_timeout = options[u'timeout'] + option_timeout = options['timeout'] if type(option_timeout) != int: raise ProtocolError("invalid type {0} for 'timeout' option in CALL".format(type(option_timeout))) @@ -4076,40 +4074,40 @@ def parse(wmsg): timeout = option_timeout - if u'receive_progress' in options: + if 'receive_progress' in options: - option_receive_progress = options[u'receive_progress'] + option_receive_progress = options['receive_progress'] if type(option_receive_progress) != bool: raise ProtocolError("invalid type {0} for 'receive_progress' option in CALL".format(type(option_receive_progress))) receive_progress = option_receive_progress - if u'caller' in options: + if 'caller' in options: - option_caller = options[u'caller'] + option_caller = options['caller'] if type(option_caller) != int: raise ProtocolError("invalid type {0} for 'caller' detail in CALL".format(type(option_caller))) caller = option_caller - if u'caller_authid' in options: + if 'caller_authid' in options: - option_caller_authid = options[u'caller_authid'] + option_caller_authid = options['caller_authid'] if type(option_caller_authid) != str: raise ProtocolError("invalid type {0} for 'caller_authid' detail in CALL".format(type(option_caller_authid))) caller_authid = option_caller_authid - if u'caller_authrole' in options: + if 'caller_authrole' in options: - option_caller_authrole = options[u'caller_authrole'] + option_caller_authrole = options['caller_authrole'] if type(option_caller_authrole) != str: raise ProtocolError("invalid type {0} for 'caller_authrole' detail in CALL".format(type(option_caller_authrole))) caller_authrole = option_caller_authrole - if u'forward_for' in options: - forward_for = options[u'forward_for'] + if 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -4147,28 +4145,28 @@ def marshal_options(self): options = {} if self.timeout is not None: - options[u'timeout'] = self.timeout + options['timeout'] = self.timeout if self.receive_progress is not None: - options[u'receive_progress'] = self.receive_progress + options['receive_progress'] = self.receive_progress if self.payload: if self.enc_algo is not None: - options[u'enc_algo'] = self.enc_algo + options['enc_algo'] = self.enc_algo if self.enc_key is not None: - options[u'enc_key'] = self.enc_key + options['enc_key'] = self.enc_key if self.enc_serializer is not None: - options[u'enc_serializer'] = self.enc_serializer + options['enc_serializer'] = self.enc_serializer if self.caller is not None: - options[u'caller'] = self.caller + options['caller'] = self.caller if self.caller_authid is not None: - options[u'caller_authid'] = self.caller_authid + options['caller_authid'] = self.caller_authid if self.caller_authrole is not None: - options[u'caller_authrole'] = self.caller_authrole + options['caller_authrole'] = self.caller_authrole if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return options @@ -4195,7 +4193,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Call(request={}, procedure={}, args={}, kwargs={}, timeout={}, receive_progress={}, enc_algo={}, enc_key={}, enc_serializer={}, payload={}, caller={}, caller_authid={}, caller_authrole={}, forward_for={})".format(self.request, self.procedure, self.args, self.kwargs, self.timeout, self.receive_progress, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.caller, self.caller_authid, self.caller_authrole, self.forward_for) + return "Call(request={}, procedure={}, args={}, kwargs={}, timeout={}, receive_progress={}, enc_algo={}, enc_key={}, enc_serializer={}, payload={}, caller={}, caller_authid={}, caller_authrole={}, forward_for={})".format(self.request, self.procedure, self.args, self.kwargs, self.timeout, self.receive_progress, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.caller, self.caller_authid, self.caller_authrole, self.forward_for) class Cancel(Message): @@ -4212,9 +4210,9 @@ class Cancel(Message): The WAMP message code for this type of message. """ - SKIP = u'skip' - KILL = u'kill' - KILLNOWAIT = u'killnowait' + SKIP = 'skip' + KILL = 'kill' + KILLNOWAIT = 'killnowait' __slots__ = ( 'request', @@ -4269,17 +4267,17 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for CANCEL".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in CANCEL") - options = check_or_raise_extra(wmsg[2], u"'options' in CANCEL") + request = check_or_raise_id(wmsg[1], "'request' in CANCEL") + options = check_or_raise_extra(wmsg[2], "'options' in CANCEL") # options # mode = None forward_for = None - if u'mode' in options: + if 'mode' in options: - option_mode = options[u'mode'] + option_mode = options['mode'] if type(option_mode) != str: raise ProtocolError("invalid type {0} for 'mode' option in CANCEL".format(type(option_mode))) @@ -4288,8 +4286,8 @@ def parse(wmsg): mode = option_mode - if u'forward_for' in options: - forward_for = options[u'forward_for'] + if 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -4320,9 +4318,9 @@ def marshal(self): options = {} if self.mode is not None: - options[u'mode'] = self.mode + options['mode'] = self.mode if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return [Cancel.MESSAGE_TYPE, self.request, options] @@ -4330,7 +4328,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Cancel(request={0}, mode={1})".format(self.request, self.mode) + return "Cancel(request={0}, mode={1})".format(self.request, self.mode) class Result(Message): @@ -4479,8 +4477,8 @@ def parse(wmsg): if len(wmsg) not in (3, 4, 5): raise ProtocolError("invalid message length {0} for RESULT".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in RESULT") - details = check_or_raise_extra(wmsg[2], u"'details' in RESULT") + request = check_or_raise_id(wmsg[1], "'request' in RESULT") + details = check_or_raise_extra(wmsg[2], "'details' in RESULT") args = None kwargs = None @@ -4498,15 +4496,15 @@ def parse(wmsg): payload = wmsg[3] - enc_algo = details.get(u'enc_algo', None) + enc_algo = details.get('enc_algo', None) if enc_algo and not is_valid_enc_algo(enc_algo): raise ProtocolError("invalid value {0} for 'enc_algo' detail in RESULT".format(enc_algo)) - enc_key = details.get(u'enc_key', None) + enc_key = details.get('enc_key', None) if enc_key and type(enc_key) != str: raise ProtocolError("invalid type {0} for 'enc_key' detail in RESULT".format(type(enc_key))) - enc_serializer = details.get(u'enc_serializer', None) + enc_serializer = details.get('enc_serializer', None) if enc_serializer and not is_valid_enc_serializer(enc_serializer): raise ProtocolError("invalid value {0} for 'enc_serializer' detail in RESULT".format(enc_serializer)) @@ -4521,40 +4519,40 @@ def parse(wmsg): if type(kwargs) != dict: raise ProtocolError("invalid type {0} for 'kwargs' in RESULT".format(type(kwargs))) - if u'progress' in details: + if 'progress' in details: - detail_progress = details[u'progress'] + detail_progress = details['progress'] if type(detail_progress) != bool: raise ProtocolError("invalid type {0} for 'progress' option in RESULT".format(type(detail_progress))) progress = detail_progress - if u'callee' in details: + if 'callee' in details: - detail_callee = details[u'callee'] + detail_callee = details['callee'] if type(detail_callee) != int: raise ProtocolError("invalid type {0} for 'callee' detail in RESULT".format(type(detail_callee))) callee = detail_callee - if u'callee_authid' in details: + if 'callee_authid' in details: - detail_callee_authid = details[u'callee_authid'] + detail_callee_authid = details['callee_authid'] if type(detail_callee_authid) != str: raise ProtocolError("invalid type {0} for 'callee_authid' detail in RESULT".format(type(detail_callee_authid))) callee_authid = detail_callee_authid - if u'callee_authrole' in details: + if 'callee_authrole' in details: - detail_callee_authrole = details[u'callee_authrole'] + detail_callee_authrole = details['callee_authrole'] if type(detail_callee_authrole) != str: raise ProtocolError("invalid type {0} for 'callee_authrole' detail in RESULT".format(type(detail_callee_authrole))) callee_authrole = detail_callee_authrole - if u'forward_for' in details: - forward_for = details[u'forward_for'] + if 'forward_for' in details: + forward_for = details['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -4596,24 +4594,24 @@ def marshal(self): details = {} if self.progress is not None: - details[u'progress'] = self.progress + details['progress'] = self.progress if self.callee is not None: - details[u'callee'] = self.callee + details['callee'] = self.callee if self.callee_authid is not None: - details[u'callee_authid'] = self.callee_authid + details['callee_authid'] = self.callee_authid if self.callee_authrole is not None: - details[u'callee_authrole'] = self.callee_authrole + details['callee_authrole'] = self.callee_authrole if self.forward_for is not None: - details[u'forward_for'] = self.forward_for + details['forward_for'] = self.forward_for if self.payload: if self.enc_algo is not None: - details[u'enc_algo'] = self.enc_algo + details['enc_algo'] = self.enc_algo if self.enc_key is not None: - details[u'enc_key'] = self.enc_key + details['enc_key'] = self.enc_key if self.enc_serializer is not None: - details[u'enc_serializer'] = self.enc_serializer + details['enc_serializer'] = self.enc_serializer return [Result.MESSAGE_TYPE, self.request, details, self.payload] else: if self.kwargs: @@ -4627,7 +4625,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Result(request={0}, args={1}, kwargs={2}, progress={3}, enc_algo={4}, enc_key={5}, enc_serializer={6}, payload={7}, callee={8}, callee_authid={9}, callee_authrole={10}, forward_for={11})".format(self.request, self.args, self.kwargs, self.progress, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.callee, self.callee_authid, self.callee_authrole, self.forward_for) + return "Result(request={0}, args={1}, kwargs={2}, progress={3}, enc_algo={4}, enc_key={5}, enc_serializer={6}, payload={7}, callee={8}, callee_authid={9}, callee_authrole={10}, forward_for={11})".format(self.request, self.args, self.kwargs, self.progress, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.callee, self.callee_authid, self.callee_authrole, self.forward_for) class Register(Message): @@ -4642,16 +4640,16 @@ class Register(Message): The WAMP message code for this type of message. """ - MATCH_EXACT = u'exact' - MATCH_PREFIX = u'prefix' - MATCH_WILDCARD = u'wildcard' + MATCH_EXACT = 'exact' + MATCH_PREFIX = 'prefix' + MATCH_WILDCARD = 'wildcard' - INVOKE_SINGLE = u'single' - INVOKE_FIRST = u'first' - INVOKE_LAST = u'last' - INVOKE_ROUNDROBIN = u'roundrobin' - INVOKE_RANDOM = u'random' - INVOKE_ALL = u'all' + INVOKE_SINGLE = 'single' + INVOKE_FIRST = 'first' + INVOKE_LAST = 'last' + INVOKE_ROUNDROBIN = 'roundrobin' + INVOKE_RANDOM = 'random' + INVOKE_ALL = 'all' __slots__ = ( 'request', @@ -4733,8 +4731,8 @@ def parse(wmsg): if len(wmsg) != 4: raise ProtocolError("invalid message length {0} for REGISTER".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in REGISTER") - options = check_or_raise_extra(wmsg[2], u"'options' in REGISTER") + request = check_or_raise_id(wmsg[1], "'request' in REGISTER") + options = check_or_raise_extra(wmsg[2], "'options' in REGISTER") match = Register.MATCH_EXACT invoke = Register.INVOKE_SINGLE @@ -4742,9 +4740,9 @@ def parse(wmsg): force_reregister = None forward_for = None - if u'match' in options: + if 'match' in options: - option_match = options[u'match'] + option_match = options['match'] if type(option_match) != str: raise ProtocolError("invalid type {0} for 'match' option in REGISTER".format(type(option_match))) @@ -4768,11 +4766,11 @@ def parse(wmsg): else: raise Exception("logic error") - procedure = check_or_raise_uri(wmsg[3], u"'procedure' in REGISTER", allow_empty_components=allow_empty_components, allow_last_empty=allow_last_empty) + procedure = check_or_raise_uri(wmsg[3], "'procedure' in REGISTER", allow_empty_components=allow_empty_components, allow_last_empty=allow_last_empty) - if u'invoke' in options: + if 'invoke' in options: - option_invoke = options[u'invoke'] + option_invoke = options['invoke'] if type(option_invoke) != str: raise ProtocolError("invalid type {0} for 'invoke' option in REGISTER".format(type(option_invoke))) @@ -4781,9 +4779,9 @@ def parse(wmsg): invoke = option_invoke - if u'concurrency' in options: + if 'concurrency' in options: - options_concurrency = options[u'concurrency'] + options_concurrency = options['concurrency'] if type(options_concurrency) != int: raise ProtocolError("invalid type {0} for 'concurrency' option in REGISTER".format(type(options_concurrency))) @@ -4792,7 +4790,7 @@ def parse(wmsg): concurrency = options_concurrency - options_reregister = options.get(u'force_reregister', None) + options_reregister = options.get('force_reregister', None) if options_reregister not in [True, False, None]: raise ProtocolError( "invalid type {0} for 'force_reregister option in REGISTER".format( @@ -4802,8 +4800,8 @@ def parse(wmsg): if options_reregister is not None: force_reregister = options_reregister - if u'forward_for' in options: - forward_for = options[u'forward_for'] + if 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -4829,19 +4827,19 @@ def marshal_options(self): options = {} if self.match and self.match != Register.MATCH_EXACT: - options[u'match'] = self.match + options['match'] = self.match if self.invoke and self.invoke != Register.INVOKE_SINGLE: - options[u'invoke'] = self.invoke + options['invoke'] = self.invoke if self.concurrency: - options[u'concurrency'] = self.concurrency + options['concurrency'] = self.concurrency if self.force_reregister is not None: - options[u'force_reregister'] = self.force_reregister + options['force_reregister'] = self.force_reregister if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return options @@ -4858,7 +4856,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Register(request={0}, procedure={1}, match={2}, invoke={3}, concurrency={4}, force_reregister={5}, forward_for={6})".format(self.request, self.procedure, self.match, self.invoke, self.concurrency, self.force_reregister, self.forward_for) + return "Register(request={0}, procedure={1}, match={2}, invoke={3}, concurrency={4}, force_reregister={5}, forward_for={6})".format(self.request, self.procedure, self.match, self.invoke, self.concurrency, self.force_reregister, self.forward_for) class Registered(Message): @@ -4910,8 +4908,8 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for REGISTERED".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in REGISTERED") - registration = check_or_raise_id(wmsg[2], u"'registration' in REGISTERED") + request = check_or_raise_id(wmsg[1], "'request' in REGISTERED") + registration = check_or_raise_id(wmsg[2], "'registration' in REGISTERED") obj = Registered(request, registration) @@ -4930,7 +4928,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Registered(request={0}, registration={1})".format(self.request, self.registration) + return "Registered(request={0}, registration={1})".format(self.request, self.registration) class Unregister(Message): @@ -4991,16 +4989,16 @@ def parse(wmsg): if len(wmsg) not in [3, 4]: raise ProtocolError("invalid message length {0} for WAMP UNREGISTER".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in UNREGISTER") - registration = check_or_raise_id(wmsg[2], u"'registration' in UNREGISTER") + request = check_or_raise_id(wmsg[1], "'request' in UNREGISTER") + registration = check_or_raise_id(wmsg[2], "'registration' in UNREGISTER") options = None if len(wmsg) > 3: - options = check_or_raise_extra(wmsg[3], u"'options' in UNREGISTER") + options = check_or_raise_extra(wmsg[3], "'options' in UNREGISTER") forward_for = None - if options and u'forward_for' in options: - forward_for = options[u'forward_for'] + if options and 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -5030,7 +5028,7 @@ def marshal(self): """ if self.forward_for: options = { - u'forward_for': self.forward_for, + 'forward_for': self.forward_for, } return [Unregister.MESSAGE_TYPE, self.request, self.registration, options] else: @@ -5040,7 +5038,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Unregister(request={0}, registration={1})".format(self.request, self.registration) + return "Unregister(request={0}, registration={1})".format(self.request, self.registration) class Unregistered(Message): @@ -5103,23 +5101,23 @@ def parse(wmsg): if len(wmsg) not in [2, 3]: raise ProtocolError("invalid message length {0} for UNREGISTERED".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in UNREGISTERED") + request = check_or_raise_id(wmsg[1], "'request' in UNREGISTERED") registration = None reason = None if len(wmsg) > 2: - details = check_or_raise_extra(wmsg[2], u"'details' in UNREGISTERED") + details = check_or_raise_extra(wmsg[2], "'details' in UNREGISTERED") - if u"registration" in details: - details_registration = details[u"registration"] + if "registration" in details: + details_registration = details["registration"] if type(details_registration) != int: raise ProtocolError("invalid type {0} for 'registration' detail in UNREGISTERED".format(type(details_registration))) registration = details_registration - if u"reason" in details: - reason = check_or_raise_uri(details[u"reason"], u"'reason' in UNREGISTERED") + if "reason" in details: + reason = check_or_raise_uri(details["reason"], "'reason' in UNREGISTERED") obj = Unregistered(request, registration, reason) @@ -5135,9 +5133,9 @@ def marshal(self): if self.reason is not None or self.registration is not None: details = {} if self.reason is not None: - details[u"reason"] = self.reason + details["reason"] = self.reason if self.registration is not None: - details[u"registration"] = self.registration + details["registration"] = self.registration return [Unregistered.MESSAGE_TYPE, self.request, details] else: return [Unregistered.MESSAGE_TYPE, self.request] @@ -5146,7 +5144,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Unregistered(request={0}, reason={1}, registration={2})".format(self.request, self.reason, self.registration) + return "Unregistered(request={0}, reason={1}, registration={2})".format(self.request, self.reason, self.registration) class Invocation(Message): @@ -5310,9 +5308,9 @@ def parse(wmsg): if len(wmsg) not in (4, 5, 6): raise ProtocolError("invalid message length {0} for INVOCATION".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in INVOCATION") - registration = check_or_raise_id(wmsg[2], u"'registration' in INVOCATION") - details = check_or_raise_extra(wmsg[3], u"'details' in INVOCATION") + request = check_or_raise_id(wmsg[1], "'request' in INVOCATION") + registration = check_or_raise_id(wmsg[2], "'registration' in INVOCATION") + details = check_or_raise_extra(wmsg[3], "'details' in INVOCATION") args = None kwargs = None @@ -5325,15 +5323,15 @@ def parse(wmsg): payload = wmsg[4] - enc_algo = details.get(u'enc_algo', None) + enc_algo = details.get('enc_algo', None) if enc_algo and not is_valid_enc_algo(enc_algo): raise ProtocolError("invalid value {0} for 'enc_algo' detail in INVOCATION".format(enc_algo)) - enc_key = details.get(u'enc_key', None) + enc_key = details.get('enc_key', None) if enc_key and type(enc_key) != str: raise ProtocolError("invalid type {0} for 'enc_key' detail in INVOCATION".format(type(enc_key))) - enc_serializer = details.get(u'enc_serializer', None) + enc_serializer = details.get('enc_serializer', None) if enc_serializer and not is_valid_enc_serializer(enc_serializer): raise ProtocolError("invalid value {0} for 'enc_serializer' detail in INVOCATION".format(enc_serializer)) @@ -5356,9 +5354,9 @@ def parse(wmsg): procedure = None forward_for = None - if u'timeout' in details: + if 'timeout' in details: - detail_timeout = details[u'timeout'] + detail_timeout = details['timeout'] if type(detail_timeout) != int: raise ProtocolError("invalid type {0} for 'timeout' detail in INVOCATION".format(type(detail_timeout))) @@ -5367,48 +5365,48 @@ def parse(wmsg): timeout = detail_timeout - if u'receive_progress' in details: + if 'receive_progress' in details: - detail_receive_progress = details[u'receive_progress'] + detail_receive_progress = details['receive_progress'] if type(detail_receive_progress) != bool: raise ProtocolError("invalid type {0} for 'receive_progress' detail in INVOCATION".format(type(detail_receive_progress))) receive_progress = detail_receive_progress - if u'caller' in details: + if 'caller' in details: - detail_caller = details[u'caller'] + detail_caller = details['caller'] if type(detail_caller) != int: raise ProtocolError("invalid type {0} for 'caller' detail in INVOCATION".format(type(detail_caller))) caller = detail_caller - if u'caller_authid' in details: + if 'caller_authid' in details: - detail_caller_authid = details[u'caller_authid'] + detail_caller_authid = details['caller_authid'] if type(detail_caller_authid) != str: raise ProtocolError("invalid type {0} for 'caller_authid' detail in INVOCATION".format(type(detail_caller_authid))) caller_authid = detail_caller_authid - if u'caller_authrole' in details: + if 'caller_authrole' in details: - detail_caller_authrole = details[u'caller_authrole'] + detail_caller_authrole = details['caller_authrole'] if type(detail_caller_authrole) != str: raise ProtocolError("invalid type {0} for 'caller_authrole' detail in INVOCATION".format(type(detail_caller_authrole))) caller_authrole = detail_caller_authrole - if u'procedure' in details: + if 'procedure' in details: - detail_procedure = details[u'procedure'] + detail_procedure = details['procedure'] if type(detail_procedure) != str: raise ProtocolError("invalid type {0} for 'procedure' detail in INVOCATION".format(type(detail_procedure))) procedure = detail_procedure - if u'forward_for' in details: - forward_for = details[u'forward_for'] + if 'forward_for' in details: + forward_for = details['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -5453,33 +5451,33 @@ def marshal(self): options = {} if self.timeout is not None: - options[u'timeout'] = self.timeout + options['timeout'] = self.timeout if self.receive_progress is not None: - options[u'receive_progress'] = self.receive_progress + options['receive_progress'] = self.receive_progress if self.caller is not None: - options[u'caller'] = self.caller + options['caller'] = self.caller if self.caller_authid is not None: - options[u'caller_authid'] = self.caller_authid + options['caller_authid'] = self.caller_authid if self.caller_authrole is not None: - options[u'caller_authrole'] = self.caller_authrole + options['caller_authrole'] = self.caller_authrole if self.procedure is not None: - options[u'procedure'] = self.procedure + options['procedure'] = self.procedure if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for if self.payload: if self.enc_algo is not None: - options[u'enc_algo'] = self.enc_algo + options['enc_algo'] = self.enc_algo if self.enc_key is not None: - options[u'enc_key'] = self.enc_key + options['enc_key'] = self.enc_key if self.enc_serializer is not None: - options[u'enc_serializer'] = self.enc_serializer + options['enc_serializer'] = self.enc_serializer return [Invocation.MESSAGE_TYPE, self.request, self.registration, options, self.payload] else: if self.kwargs: @@ -5493,7 +5491,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Invocation(request={0}, registration={1}, args={2}, kwargs={3}, timeout={4}, receive_progress={5}, caller={6}, caller_authid={7}, caller_authrole={8}, procedure={9}, enc_algo={10}, enc_key={11}, enc_serializer={12}, payload={13})".format(self.request, self.registration, self.args, self.kwargs, self.timeout, self.receive_progress, self.caller, self.caller_authid, self.caller_authrole, self.procedure, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload)) + return "Invocation(request={0}, registration={1}, args={2}, kwargs={3}, timeout={4}, receive_progress={5}, caller={6}, caller_authid={7}, caller_authrole={8}, procedure={9}, enc_algo={10}, enc_key={11}, enc_serializer={12}, payload={13})".format(self.request, self.registration, self.args, self.kwargs, self.timeout, self.receive_progress, self.caller, self.caller_authid, self.caller_authrole, self.procedure, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload)) class Interrupt(Message): @@ -5510,8 +5508,8 @@ class Interrupt(Message): The WAMP message code for this type of message. """ - KILL = u'kill' - KILLNOWAIT = u'killnowait' + KILL = 'kill' + KILLNOWAIT = 'killnowait' __slots__ = ( 'request', @@ -5579,8 +5577,8 @@ def parse(wmsg): if len(wmsg) != 3: raise ProtocolError("invalid message length {0} for INTERRUPT".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in INTERRUPT") - options = check_or_raise_extra(wmsg[2], u"'options' in INTERRUPT") + request = check_or_raise_id(wmsg[1], "'request' in INTERRUPT") + options = check_or_raise_extra(wmsg[2], "'options' in INTERRUPT") # options # @@ -5588,9 +5586,9 @@ def parse(wmsg): reason = None forward_for = None - if u'mode' in options: + if 'mode' in options: - option_mode = options[u'mode'] + option_mode = options['mode'] if type(option_mode) != str: raise ProtocolError("invalid type {0} for 'mode' option in INTERRUPT".format(type(option_mode))) @@ -5599,11 +5597,11 @@ def parse(wmsg): mode = option_mode - if u'reason' in options: - reason = check_or_raise_uri(options[u'reason'], u'"reason" in INTERRUPT') + if 'reason' in options: + reason = check_or_raise_uri(options['reason'], '"reason" in INTERRUPT') - if u'forward_for' in options: - forward_for = options[u'forward_for'] + if 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -5634,13 +5632,13 @@ def marshal(self): options = {} if self.mode is not None: - options[u'mode'] = self.mode + options['mode'] = self.mode if self.reason is not None: - options[u'reason'] = self.reason + options['reason'] = self.reason if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return [Interrupt.MESSAGE_TYPE, self.request, options] @@ -5648,7 +5646,7 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Interrupt(request={0}, mode={1}, reason={2})".format(self.request, self.mode, self.reason) + return "Interrupt(request={0}, mode={1}, reason={2})".format(self.request, self.mode, self.reason) class Yield(Message): @@ -5794,8 +5792,8 @@ def parse(wmsg): if len(wmsg) not in (3, 4, 5): raise ProtocolError("invalid message length {0} for YIELD".format(len(wmsg))) - request = check_or_raise_id(wmsg[1], u"'request' in YIELD") - options = check_or_raise_extra(wmsg[2], u"'options' in YIELD") + request = check_or_raise_id(wmsg[1], "'request' in YIELD") + options = check_or_raise_extra(wmsg[2], "'options' in YIELD") args = None kwargs = None @@ -5808,15 +5806,15 @@ def parse(wmsg): payload = wmsg[3] - enc_algo = options.get(u'enc_algo', None) + enc_algo = options.get('enc_algo', None) if enc_algo and not is_valid_enc_algo(enc_algo): raise ProtocolError("invalid value {0} for 'enc_algo' detail in YIELD".format(enc_algo)) - enc_key = options.get(u'enc_key', None) + enc_key = options.get('enc_key', None) if enc_key and type(enc_key) != str: raise ProtocolError("invalid type {0} for 'enc_key' detail in YIELD".format(type(enc_key))) - enc_serializer = options.get(u'enc_serializer', None) + enc_serializer = options.get('enc_serializer', None) if enc_serializer and not is_valid_enc_serializer(enc_serializer): raise ProtocolError("invalid value {0} for 'enc_serializer' detail in YIELD".format(enc_serializer)) @@ -5837,40 +5835,40 @@ def parse(wmsg): callee_authrole = None forward_for = None - if u'progress' in options: + if 'progress' in options: - option_progress = options[u'progress'] + option_progress = options['progress'] if type(option_progress) != bool: raise ProtocolError("invalid type {0} for 'progress' option in YIELD".format(type(option_progress))) progress = option_progress - if u'callee' in options: + if 'callee' in options: - option_callee = options[u'callee'] + option_callee = options['callee'] if type(option_callee) != int: raise ProtocolError("invalid type {0} for 'callee' detail in YIELD".format(type(option_callee))) callee = option_callee - if u'callee_authid' in options: + if 'callee_authid' in options: - option_callee_authid = options[u'callee_authid'] + option_callee_authid = options['callee_authid'] if type(option_callee_authid) != str: raise ProtocolError("invalid type {0} for 'callee_authid' detail in YIELD".format(type(option_callee_authid))) callee_authid = option_callee_authid - if u'callee_authrole' in options: + if 'callee_authrole' in options: - option_callee_authrole = options[u'callee_authrole'] + option_callee_authrole = options['callee_authrole'] if type(option_callee_authrole) != str: raise ProtocolError("invalid type {0} for 'callee_authrole' detail in YIELD".format(type(option_callee_authrole))) callee_authrole = option_callee_authrole - if u'forward_for' in options: - forward_for = options[u'forward_for'] + if 'forward_for' in options: + forward_for = options['forward_for'] valid = False if type(forward_for) == list: for ff in forward_for: @@ -5912,24 +5910,24 @@ def marshal(self): options = {} if self.progress is not None: - options[u'progress'] = self.progress + options['progress'] = self.progress if self.callee is not None: - options[u'callee'] = self.callee + options['callee'] = self.callee if self.callee_authid is not None: - options[u'callee_authid'] = self.callee_authid + options['callee_authid'] = self.callee_authid if self.callee_authrole is not None: - options[u'callee_authrole'] = self.callee_authrole + options['callee_authrole'] = self.callee_authrole if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for if self.payload: if self.enc_algo is not None: - options[u'enc_algo'] = self.enc_algo + options['enc_algo'] = self.enc_algo if self.enc_key is not None: - options[u'enc_key'] = self.enc_key + options['enc_key'] = self.enc_key if self.enc_serializer is not None: - options[u'enc_serializer'] = self.enc_serializer + options['enc_serializer'] = self.enc_serializer return [Yield.MESSAGE_TYPE, self.request, options, self.payload] else: if self.kwargs: @@ -5943,4 +5941,4 @@ def __str__(self): """ Returns string representation of this message. """ - return u"Yield(request={0}, args={1}, kwargs={2}, progress={3}, enc_algo={4}, enc_key={5}, enc_serializer={6}, payload={7}, callee={8}, callee_authid={9}, callee_authrole={10}, forward_for={11})".format(self.request, self.args, self.kwargs, self.progress, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.callee, self.callee_authid, self.callee_authrole, self.forward_for) + return "Yield(request={0}, args={1}, kwargs={2}, progress={3}, enc_algo={4}, enc_key={5}, enc_serializer={6}, payload={7}, callee={8}, callee_authid={9}, callee_authrole={10}, forward_for={11})".format(self.request, self.args, self.kwargs, self.progress, self.enc_algo, self.enc_key, self.enc_serializer, b2a(self.payload), self.callee, self.callee_authid, self.callee_authrole, self.forward_for) diff --git a/autobahn/wamp/message_fbs.py b/autobahn/wamp/message_fbs.py index 849623fdf..677060103 100644 --- a/autobahn/wamp/message_fbs.py +++ b/autobahn/wamp/message_fbs.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import flatbuffers from autobahn.wamp.gen.wamp.proto import Event as EventGen from autobahn.wamp.gen.wamp.proto import Publish as PublishGen diff --git a/autobahn/wamp/protocol.py b/autobahn/wamp/protocol.py index eec247c11..f14bae202 100644 --- a/autobahn/wamp/protocol.py +++ b/autobahn/wamp/protocol.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import txaio import inspect from functools import reduce @@ -175,9 +173,9 @@ def _message_from_exception(self, request_type, request, exc, tb=None, enc_algo= if tb: if kwargs: - kwargs[u'traceback'] = tb + kwargs['traceback'] = tb else: - kwargs = {u'traceback': tb} + kwargs = {'traceback': tb} if isinstance(exc, exception.ApplicationError): error = exc.error if type(exc.error) == str else exc.error @@ -185,7 +183,7 @@ def _message_from_exception(self, request_type, request, exc, tb=None, enc_algo= if exc.__class__ in self._ecls_to_uri_pat: error = self._ecls_to_uri_pat[exc.__class__][0]._uri else: - error = u"wamp.error.runtime_error" + error = "wamp.error.runtime_error" encoded_payload = None if self._payload_codec: @@ -226,7 +224,7 @@ def _exception_from_message(self, msg): if msg.enc_algo: if not self._payload_codec: - log_msg = u"received encoded payload, but no payload codec active" + log_msg = "received encoded payload, but no payload codec active" self.log.warn(log_msg) enc_err = ApplicationError(ApplicationError.ENC_NO_PAYLOAD_CODEC, log_msg, enc_algo=msg.enc_algo) else: @@ -237,19 +235,19 @@ def _exception_from_message(self, msg): self.log.warn("failed to decrypt application payload 1: {err}", err=e) enc_err = ApplicationError( ApplicationError.ENC_DECRYPT_ERROR, - u"failed to decrypt application payload 1: {}".format(e), + "failed to decrypt application payload 1: {}".format(e), enc_algo=msg.enc_algo, ) else: if msg.error != decrypted_error: self.log.warn( - u"URI within encrypted payload ('{decrypted_error}') does not match the envelope ('{error}')", + "URI within encrypted payload ('{decrypted_error}') does not match the envelope ('{error}')", decrypted_error=decrypted_error, error=msg.error, ) enc_err = ApplicationError( ApplicationError.ENC_TRUSTED_URI_MISMATCH, - u"URI within encrypted payload ('{}') does not match the envelope ('{}')".format(decrypted_error, msg.error), + "URI within encrypted payload ('{}') does not match the envelope ('{}')".format(decrypted_error, msg.error), enc_algo=msg.enc_algo, ) @@ -320,7 +318,7 @@ def __init__(self, config=None): Implements :func:`autobahn.wamp.interfaces.ISession` """ BaseSession.__init__(self) - self.config = config or types.ComponentConfig(realm=u"realm1") + self.config = config or types.ComponentConfig(realm="realm1") # set client role features supported and announced self._session_roles = role.DEFAULT_CLIENT_ROLES @@ -514,7 +512,7 @@ def success(res): if res is not None: self.log.info("Session denied by onWelcome") reply = message.Abort( - u"wamp.error.cannot_authenticate", u"{0}".format(res) + "wamp.error.cannot_authenticate", "{0}".format(res) ) self._transport.send(reply) return @@ -578,7 +576,7 @@ def success(res): def error(e): reply = message.Abort( - u"wamp.error.cannot_authenticate", u"Error calling onWelcome handler" + "wamp.error.cannot_authenticate", "Error calling onWelcome handler" ) self._transport.send(reply) return self._swallow_error(e, "While firing onWelcome") @@ -622,7 +620,7 @@ def success(signature): def error(err): self.onUserError(err, "Authentication failed") - reply = message.Abort(u"wamp.error.cannot_authenticate", u"{0}".format(err.value)) + reply = message.Abort("wamp.error.cannot_authenticate", "{0}".format(err.value)) self._transport.send(reply) # fire callback and close the transport details = types.CloseDetails(reply.reason, reply.message) @@ -791,7 +789,7 @@ def _error(e): if msg.enc_algo: if not self._payload_codec: - log_msg = u"received encoded payload, but no payload codec active" + log_msg = "received encoded payload, but no payload codec active" self.log.warn(log_msg) enc_err = ApplicationError(ApplicationError.ENC_NO_PAYLOAD_CODEC, log_msg) else: @@ -805,7 +803,7 @@ def _error(e): ) enc_err = ApplicationError( ApplicationError.ENC_DECRYPT_ERROR, - u"failed to decrypt application payload 1: {}".format(e), + "failed to decrypt application payload 1: {}".format(e), ) else: if proc != decrypted_proc: @@ -816,7 +814,7 @@ def _error(e): ) enc_err = ApplicationError( ApplicationError.ENC_TRUSTED_URI_MISMATCH, - u"URI within encrypted payload ('{}') does not match the envelope ('{}')".format(decrypted_proc, proc), + "URI within encrypted payload ('{}') does not match the envelope ('{}')".format(decrypted_proc, proc), ) if msg.progress: @@ -908,7 +906,7 @@ def _error(fail): if msg.enc_algo: if not self._payload_codec: - log_msg = u"received encrypted INVOCATION payload, but no keyring active" + log_msg = "received encrypted INVOCATION payload, but no keyring active" self.log.warn(log_msg) enc_err = ApplicationError(ApplicationError.ENC_NO_PAYLOAD_CODEC, log_msg) else: @@ -934,7 +932,7 @@ def _error(fail): ) enc_err = ApplicationError( ApplicationError.ENC_TRUSTED_URI_MISMATCH, - u"URI within encrypted INVOCATION payload ('{}') does not match the envelope ('{}')".format(decrypted_proc, proc), + "URI within encrypted INVOCATION payload ('{}') does not match the envelope ('{}')".format(decrypted_proc, proc), ) if enc_err: @@ -966,7 +964,7 @@ def progress(*args, **kwargs): encoded_payload = None if msg.enc_algo: if not self._payload_codec: - raise Exception(u"trying to send encrypted payload, but no keyring active") + raise Exception("trying to send encrypted payload, but no keyring active") encoded_payload = self._payload_codec.encode(False, proc, args, kwargs) if encoded_payload: @@ -1002,7 +1000,7 @@ def success(res): encoded_payload = None if msg.enc_algo: if not self._payload_codec: - log_msg = u"trying to send encrypted payload, but no keyring active" + log_msg = "trying to send encrypted payload, but no keyring active" self.log.warn(log_msg) else: try: @@ -1055,13 +1053,13 @@ def success(res): except SerializationError as e: # the application-level payload returned from the invoked procedure can't be serialized reply = message.Error(message.Invocation.MESSAGE_TYPE, msg.request, ApplicationError.INVALID_PAYLOAD, - args=[u'success return value from invoked procedure "{0}" could not be serialized: {1}'.format(registration.procedure, e)]) + args=['success return value from invoked procedure "{0}" could not be serialized: {1}'.format(registration.procedure, e)]) self._transport.send(reply) except PayloadExceededError as e: # the application-level payload returned from the invoked procedure, when serialized and framed # for the transport, exceeds the transport message/frame size limit reply = message.Error(message.Invocation.MESSAGE_TYPE, msg.request, ApplicationError.PAYLOAD_SIZE_EXCEEDED, - args=[u'success return value from invoked procedure "{0}" exceeds transport size limit: {1}'.format(registration.procedure, e)]) + args=['success return value from invoked procedure "{0}" exceeds transport size limit: {1}'.format(registration.procedure, e)]) self._transport.send(reply) def error(err): @@ -1091,13 +1089,13 @@ def error(err): except SerializationError as e: # the application-level payload returned from the invoked procedure can't be serialized reply = message.Error(message.Invocation.MESSAGE_TYPE, msg.request, ApplicationError.INVALID_PAYLOAD, - args=[u'error return value from invoked procedure "{0}" could not be serialized: {1}'.format(registration.procedure, e)]) + args=['error return value from invoked procedure "{0}" could not be serialized: {1}'.format(registration.procedure, e)]) self._transport.send(reply) except PayloadExceededError as e: # the application-level payload returned from the invoked procedure, when serialized and framed # for the transport, exceeds the transport message/frame size limit reply = message.Error(message.Invocation.MESSAGE_TYPE, msg.request, ApplicationError.PAYLOAD_SIZE_EXCEEDED, - args=[u'success return value from invoked procedure "{0}" exceeds transport size limit: {1}'.format(registration.procedure, e)]) + args=['success return value from invoked procedure "{0}" exceeds transport size limit: {1}'.format(registration.procedure, e)]) self._transport.send(reply) # we have handled the error, so we eat it @@ -1151,7 +1149,7 @@ def error(err): " ID {0}".format(msg.registration) ) self.log.info( - u"Router unregistered procedure '{proc}' with ID {id}", + "Router unregistered procedure '{proc}' with ID {id}", proc=reg.procedure, id=msg.registration, ) @@ -1220,7 +1218,7 @@ def onClose(self, wasClean): # fire callback and close the transport details = types.CloseDetails( reason=types.CloseDetails.REASON_TRANSPORT_LOST, - message=u'WAMP transport was lost without closing the session {} before'.format(self._session_id), + message='WAMP transport was lost without closing the session {} before'.format(self._session_id), ) d = txaio.as_future(self.onLeave, details) @@ -1326,11 +1324,11 @@ def leave(self, reason=None, message=None): Implements :func:`autobahn.wamp.interfaces.ISession.leave` """ if not self._session_id: - raise SessionNotReady(u"session hasn't joined a realm") + raise SessionNotReady("session hasn't joined a realm") if not self._goodbye_sent: if not reason: - reason = u"wamp.close.normal" + reason = "wamp.close.normal" msg = wamp.message.Goodbye(reason=reason, message=message) self._transport.send(msg) self._goodbye_sent = True @@ -1502,9 +1500,9 @@ def _subscribe(obj, fn, topic, options): subopts = pat.options or options if subopts is None: if pat.uri_type == uri.Pattern.URI_TYPE_WILDCARD: - subopts = types.SubscribeOptions(match=u"wildcard") + subopts = types.SubscribeOptions(match="wildcard") else: - subopts = types.SubscribeOptions(match=u"exact") + subopts = types.SubscribeOptions(match="exact") on_replies.append(_subscribe(handler, proc, _uri, subopts)) # XXX needs coverage @@ -1666,7 +1664,7 @@ def _register(obj, fn, procedure, options): on_reply = txaio.create_future() endpoint_obj = Endpoint(fn, obj, options.details_arg if options else None) if prefix is not None: - procedure = u"{}{}".format(prefix, procedure) + procedure = "{}{}".format(prefix, procedure) self._register_reqs[request_id] = RegisterRequest(request_id, on_reply, procedure, endpoint_obj) if options: @@ -1739,7 +1737,7 @@ class _SessionShim(ApplicationSession): **NOTE:** this is not public or intended for use; you should import either :class:`autobahn.asyncio.wamp.Session` or :class:`autobahn.twisted.wamp.Session` depending on which async - framework you're using. + framework yo're using. """ #: name -> IAuthenticator @@ -1762,8 +1760,8 @@ def onConnect(self): self.join( self.config.realm, authmethods=list(self._authenticators.keys()), - authid=authid or u'public', - authrole=authrole or u'default', + authid=authid or 'public', + authrole=authrole or 'default', authextra=authextra, ) else: @@ -1920,7 +1918,7 @@ def __init__(self, config=None): :param config: The default component configuration. :type config: instance of :class:`autobahn.wamp.types.ComponentConfig` """ - self.config = config or types.ComponentConfig(realm=u"realm1") + self.config = config or types.ComponentConfig(realm="realm1") def __call__(self): """ diff --git a/autobahn/wamp/request.py b/autobahn/wamp/request.py index 9fe90a6ac..c4ccd9eaf 100644 --- a/autobahn/wamp/request.py +++ b/autobahn/wamp/request.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import - __all__ = ( 'Publication', 'Subscription', diff --git a/autobahn/wamp/role.py b/autobahn/wamp/role.py index ff98a14d5..485967e9e 100644 --- a/autobahn/wamp/role.py +++ b/autobahn/wamp/role.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import json from autobahn import util @@ -77,7 +75,7 @@ class RoleBrokerFeatures(RoleFeatures): WAMP broker role features. """ - ROLE = u'broker' + ROLE = 'broker' def __init__(self, publisher_identification=None, @@ -116,7 +114,7 @@ class RoleSubscriberFeatures(RoleFeatures): WAMP subscriber role features. """ - ROLE = u'subscriber' + ROLE = 'subscriber' def __init__(self, publisher_identification=None, @@ -143,7 +141,7 @@ class RolePublisherFeatures(RoleFeatures): WAMP publisher role features. """ - ROLE = u'publisher' + ROLE = 'publisher' def __init__(self, publisher_identification=None, @@ -168,7 +166,7 @@ class RoleDealerFeatures(RoleFeatures): WAMP dealer role features. """ - ROLE = u'dealer' + ROLE = 'dealer' def __init__(self, caller_identification=None, @@ -207,7 +205,7 @@ class RoleCallerFeatures(RoleFeatures): WAMP caller role features. """ - ROLE = u'caller' + ROLE = 'caller' def __init__(self, caller_identification=None, @@ -232,7 +230,7 @@ class RoleCalleeFeatures(RoleFeatures): WAMP callee role features. """ - ROLE = u'callee' + ROLE = 'callee' def __init__(self, caller_identification=None, @@ -261,25 +259,25 @@ def __init__(self, # map of role names to role class ROLE_NAME_TO_CLASS = { - u'broker': RoleBrokerFeatures, - u'subscriber': RoleSubscriberFeatures, - u'publisher': RolePublisherFeatures, - u'dealer': RoleDealerFeatures, - u'caller': RoleCallerFeatures, - u'callee': RoleCalleeFeatures, + 'broker': RoleBrokerFeatures, + 'subscriber': RoleSubscriberFeatures, + 'publisher': RolePublisherFeatures, + 'dealer': RoleDealerFeatures, + 'caller': RoleCallerFeatures, + 'callee': RoleCalleeFeatures, } # default role features for client roles supported DEFAULT_CLIENT_ROLES = { - u'subscriber': RoleSubscriberFeatures( + 'subscriber': RoleSubscriberFeatures( publisher_identification=True, pattern_based_subscription=True, subscription_revocation=True, payload_transparency=True, payload_encryption_cryptobox=True, ), - u'publisher': RolePublisherFeatures( + 'publisher': RolePublisherFeatures( publisher_identification=True, subscriber_blackwhite_listing=True, publisher_exclusion=True, @@ -287,14 +285,14 @@ def __init__(self, x_acknowledged_event_delivery=True, payload_encryption_cryptobox=True, ), - u'caller': RoleCallerFeatures( + 'caller': RoleCallerFeatures( caller_identification=True, progressive_call_results=True, payload_transparency=True, payload_encryption_cryptobox=True, call_canceling=True, ), - u'callee': RoleCalleeFeatures( + 'callee': RoleCalleeFeatures( caller_identification=True, pattern_based_registration=True, shared_registration=True, diff --git a/autobahn/wamp/serializer.py b/autobahn/wamp/serializer.py index b3d10c130..c2640c4ec 100644 --- a/autobahn/wamp/serializer.py +++ b/autobahn/wamp/serializer.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os import struct import platform @@ -278,7 +276,7 @@ def unserialize(self, payload, isBinary=None): except Exception as e: raise ProtocolError("invalid serialization of WAMP message: {0} {1}".format(type(e).__name__, e)) - if self._serializer.NAME == u'flatbuffers': + if self._serializer.NAME == 'flatbuffers': msgs = raw_msgs else: msgs = [] @@ -288,7 +286,7 @@ def unserialize(self, payload, isBinary=None): raise ProtocolError("invalid type {0} for WAMP message".format(type(raw_msg))) if len(raw_msg) == 0: - raise ProtocolError(u"missing message type in WAMP message") + raise ProtocolError("missing message type in WAMP message") message_type = raw_msg[0] @@ -347,7 +345,7 @@ class _WAMPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytes): - return u'\x00' + base64.b64encode(obj).decode('ascii') + return '\x00' + base64.b64encode(obj).decode('ascii') else: return json.JSONEncoder.default(self, obj) @@ -360,7 +358,7 @@ def default(self, obj): def _parse_string(*args, **kwargs): s, idx = scanstring(*args, **kwargs) - if s and s[0] == u'\x00': + if s and s[0] == '\x00': s = base64.b64decode(s[1:]) return s, idx @@ -397,7 +395,7 @@ class JsonObjectSerializer(object): The JSON module used (now only stdlib). """ - NAME = u'json' + NAME = 'json' BINARY = False @@ -441,7 +439,7 @@ def unserialize(self, payload): class JsonSerializer(Serializer): - SERIALIZER_ID = u"json" + SERIALIZER_ID = "json" """ ID used as part of the WebSocket subprotocol name to identify the serializer with WAMP-over-WebSocket. @@ -453,7 +451,7 @@ class JsonSerializer(Serializer): handshake identify the serializer with WAMP-over-RawSocket. """ - MIME_TYPE = u"application/json" + MIME_TYPE = "application/json" """ MIME type announced in HTTP request/response headers when running WAMP-over-Longpoll HTTP fallback. @@ -468,7 +466,7 @@ def __init__(self, batched=False): """ Serializer.__init__(self, JsonObjectSerializer(batched=batched)) if batched: - self.SERIALIZER_ID = u"json.batched" + self.SERIALIZER_ID = "json.batched" ISerializer.register(JsonSerializer) @@ -476,7 +474,7 @@ def __init__(self, batched=False): _HAS_MSGPACK = False -_USE_UMSGPACK = platform.python_implementation() == u'PyPy' or 'AUTOBAHN_USE_UMSGPACK' in os.environ +_USE_UMSGPACK = platform.python_implementation() == 'PyPy' or 'AUTOBAHN_USE_UMSGPACK' in os.environ if not _USE_UMSGPACK: try: @@ -512,7 +510,7 @@ def __init__(self, batched=False): class MsgPackObjectSerializer(object): - NAME = u'msgpack' + NAME = 'msgpack' MSGPACK_MODULE = _msgpack @@ -580,7 +578,7 @@ def unserialize(self, payload): class MsgPackSerializer(Serializer): - SERIALIZER_ID = u"msgpack" + SERIALIZER_ID = "msgpack" """ ID used as part of the WebSocket subprotocol name to identify the serializer with WAMP-over-WebSocket. @@ -592,7 +590,7 @@ class MsgPackSerializer(Serializer): handshake identify the serializer with WAMP-over-RawSocket. """ - MIME_TYPE = u"application/x-msgpack" + MIME_TYPE = "application/x-msgpack" """ MIME type announced in HTTP request/response headers when running WAMP-over-Longpoll HTTP fallback. @@ -607,7 +605,7 @@ def __init__(self, batched=False): """ Serializer.__init__(self, MsgPackObjectSerializer(batched=batched)) if batched: - self.SERIALIZER_ID = u"msgpack.batched" + self.SERIALIZER_ID = "msgpack.batched" ISerializer.register(MsgPackSerializer) SERID_TO_SER[MsgPackSerializer.SERIALIZER_ID] = MsgPackSerializer @@ -648,7 +646,7 @@ def __init__(self, batched=False): class CBORObjectSerializer(object): - NAME = u'cbor' + NAME = 'cbor' CBOR_MODULE = _cbor @@ -717,7 +715,7 @@ def unserialize(self, payload): class CBORSerializer(Serializer): - SERIALIZER_ID = u"cbor" + SERIALIZER_ID = "cbor" """ ID used as part of the WebSocket subprotocol name to identify the serializer with WAMP-over-WebSocket. @@ -729,7 +727,7 @@ class CBORSerializer(Serializer): handshake identify the serializer with WAMP-over-RawSocket. """ - MIME_TYPE = u"application/cbor" + MIME_TYPE = "application/cbor" """ MIME type announced in HTTP request/response headers when running WAMP-over-Longpoll HTTP fallback. @@ -744,7 +742,7 @@ def __init__(self, batched=False): """ Serializer.__init__(self, CBORObjectSerializer(batched=batched)) if batched: - self.SERIALIZER_ID = u"cbor.batched" + self.SERIALIZER_ID = "cbor.batched" ISerializer.register(CBORSerializer) SERID_TO_SER[CBORSerializer.SERIALIZER_ID] = CBORSerializer @@ -764,7 +762,7 @@ def __init__(self, batched=False): class UBJSONObjectSerializer(object): - NAME = u'ubjson' + NAME = 'ubjson' UBJSON_MODULE = ubjson @@ -832,7 +830,7 @@ def unserialize(self, payload): class UBJSONSerializer(Serializer): - SERIALIZER_ID = u"ubjson" + SERIALIZER_ID = "ubjson" """ ID used as part of the WebSocket subprotocol name to identify the serializer with WAMP-over-WebSocket. @@ -844,7 +842,7 @@ class UBJSONSerializer(Serializer): handshake identify the serializer with WAMP-over-RawSocket. """ - MIME_TYPE = u"application/ubjson" + MIME_TYPE = "application/ubjson" """ MIME type announced in HTTP request/response headers when running WAMP-over-Longpoll HTTP fallback. @@ -859,7 +857,7 @@ def __init__(self, batched=False): """ Serializer.__init__(self, UBJSONObjectSerializer(batched=batched)) if batched: - self.SERIALIZER_ID = u"ubjson.batched" + self.SERIALIZER_ID = "ubjson.batched" ISerializer.register(UBJSONSerializer) SERID_TO_SER[UBJSONSerializer.SERIALIZER_ID] = UBJSONSerializer @@ -881,7 +879,7 @@ def __init__(self, batched=False): class FlatBuffersObjectSerializer(object): - NAME = u'flatbuffers' + NAME = 'flatbuffers' FLATBUFFERS_MODULE = flatbuffers @@ -934,7 +932,7 @@ def unserialize(self, payload): class FlatBuffersSerializer(Serializer): - SERIALIZER_ID = u"flatbuffers" + SERIALIZER_ID = "flatbuffers" """ ID used as part of the WebSocket subprotocol name to identify the serializer with WAMP-over-WebSocket. @@ -946,7 +944,7 @@ class FlatBuffersSerializer(Serializer): handshake identify the serializer with WAMP-over-RawSocket. """ - MIME_TYPE = u"application/x-flatbuffers" + MIME_TYPE = "application/x-flatbuffers" """ MIME type announced in HTTP request/response headers when running WAMP-over-Longpoll HTTP fallback. @@ -960,7 +958,7 @@ def __init__(self, batched=False): """ Serializer.__init__(self, FlatBuffersObjectSerializer(batched=batched)) if batched: - self.SERIALIZER_ID = u"flatbuffers.batched" + self.SERIALIZER_ID = "flatbuffers.batched" ISerializer.register(FlatBuffersSerializer) SERID_TO_SER[FlatBuffersSerializer.SERIALIZER_ID] = FlatBuffersSerializer diff --git a/autobahn/wamp/test/test_auth.py b/autobahn/wamp/test/test_auth.py index c94a3d307..af7dd9b3a 100644 --- a/autobahn/wamp/test/test_auth.py +++ b/autobahn/wamp/test/test_auth.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import unittest import platform @@ -41,17 +39,17 @@ # these test vectors are all for HMAC-SHA1 PBKDF2_TEST_VECTORS = [ # From RFC 6070 - (b'password', b'salt', 1, 20, u'0c60c80f961f0e71f3a9b524af6012062fe037a6'), - (b'password', b'salt', 2, 20, u'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), + (b'password', b'salt', 1, 20, '0c60c80f961f0e71f3a9b524af6012062fe037a6'), + (b'password', b'salt', 2, 20, 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'), # From Crypt-PBKDF2 - (b'password', b'ATHENA.MIT.EDUraeburn', 1, 16, u'cdedb5281bb2f801565a1122b2563515'), - (b'password', b'ATHENA.MIT.EDUraeburn', 1, 32, u'cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837'), - (b'password', b'ATHENA.MIT.EDUraeburn', 2, 16, u'01dbee7f4a9e243e988b62c73cda935d'), - (b'password', b'ATHENA.MIT.EDUraeburn', 2, 32, u'01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86'), - (b'password', b'ATHENA.MIT.EDUraeburn', 1200, 32, u'5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13'), - (b'X' * 64, b'pass phrase equals block size', 1200, 32, u'139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1'), - (b'X' * 65, b'pass phrase exceeds block size', 1200, 32, u'9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a'), + (b'password', b'ATHENA.MIT.EDUraeburn', 1, 16, 'cdedb5281bb2f801565a1122b2563515'), + (b'password', b'ATHENA.MIT.EDUraeburn', 1, 32, 'cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837'), + (b'password', b'ATHENA.MIT.EDUraeburn', 2, 16, '01dbee7f4a9e243e988b62c73cda935d'), + (b'password', b'ATHENA.MIT.EDUraeburn', 2, 32, '01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86'), + (b'password', b'ATHENA.MIT.EDUraeburn', 1200, 32, '5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13'), + (b'X' * 64, b'pass phrase equals block size', 1200, 32, '139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1'), + (b'X' * 65, b'pass phrase exceeds block size', 1200, 32, '9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a'), ] if platform.python_implementation() != 'PyPy': @@ -60,12 +58,12 @@ PBKDF2_TEST_VECTORS.extend( [ # From RFC 6070 - (b'password', b'salt', 4096, 20, u'4b007901b765489abead49d926f721d065a429c1'), - (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25, u'3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038'), - (b'pass\x00word', b'sa\x00lt', 4096, 16, u'56fa6aa75548099dcc37d7f03425e0c3'), + (b'password', b'salt', 4096, 20, '4b007901b765489abead49d926f721d065a429c1'), + (b'passwordPASSWORDpassword', b'saltSALTsaltSALTsaltSALTsaltSALTsalt', 4096, 25, '3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038'), + (b'pass\x00word', b'sa\x00lt', 4096, 16, '56fa6aa75548099dcc37d7f03425e0c3'), # This one is from the RFC but it just takes for ages - # (b'password', b'salt', 16777216, 20, u'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), + # (b'password', b'salt', 16777216, 20, 'eefe3d61cd4da4e4e9945b3d6ba2158c2634e984'), ] ) @@ -91,22 +89,22 @@ def test_generate_totp_secret_length(self): def test_compute_totp(self): pat = re.compile(r"\d\d\d\d\d\d") - secret = u"MFRGGZDFMZTWQ2LK" + secret = "MFRGGZDFMZTWQ2LK" signature = auth.compute_totp(secret) self.assertEqual(type(signature), str) self.assertTrue(pat.match(signature) is not None) def test_compute_totp_offset(self): pat = re.compile(r"\d\d\d\d\d\d") - secret = u"MFRGGZDFMZTWQ2LK" + secret = "MFRGGZDFMZTWQ2LK" for offset in range(-10, 10): signature = auth.compute_totp(secret, offset) self.assertEqual(type(signature), str) self.assertTrue(pat.match(signature) is not None) def test_derive_key(self): - secret = u'L3L1YUE8Txlw' - salt = u'salt123' + secret = 'L3L1YUE8Txlw' + salt = 'salt123' key = auth.derive_key(secret.encode('utf8'), salt.encode('utf8')) self.assertEqual(type(key), bytes) self.assertEqual(key, b"qzcdsr9uu/L5hnss3kjNTRe490ETgA70ZBaB5rvnJ5Y=") @@ -123,7 +121,7 @@ def test_generate_wcs_length(self): self.assertEqual(len(secret), length) def test_compute_wcs(self): - secret = u'L3L1YUE8Txlw' + secret = 'L3L1YUE8Txlw' challenge = json.dumps([1, 2, 3], ensure_ascii=False).encode('utf8') signature = auth.compute_wcs(secret.encode('utf8'), challenge) self.assertEqual(type(signature), bytes) @@ -154,26 +152,26 @@ def test_pbkdf2_static(self): def test_basic(self): scram = auth.AuthScram( - nonce=u'1234567890abcdef', - kdf=u'argon2id13', + nonce='1234567890abcdef', + kdf='argon2id13', salt=binascii.b2a_hex(b'1234567890abcdef').decode('ascii'), iterations=32, # far too few; use 4096 or more for production memory=512, - password=u'p4ssw0rd', - authid=u'username', + password='p4ssw0rd', + authid='username', ) # thought: if we could import crossbar code here, we could # test the "other side" of this with fewer mocks # (i.e. hard-coding the client nonce) scram._client_nonce = binascii.b2a_hex(b'1234567890abcdef').decode('ascii') self.assertEqual( - {'nonce': u'31323334353637383930616263646566'}, + {'nonce': '31323334353637383930616263646566'}, scram.authextra, ) - challenge = types.Challenge(u'scram', { - 'nonce': u'1234567890abcdeffedcba0987654321', - 'kdf': u'argon2id-13', + challenge = types.Challenge('scram', { + 'nonce': '1234567890abcdeffedcba0987654321', + 'kdf': 'argon2id-13', 'salt': binascii.b2a_hex(b'1234567890abcdef').decode('ascii'), 'iterations': 32, 'memory': 512, @@ -191,20 +189,20 @@ def test_basic(self): def test_no_memory_arg(self): scram = auth.AuthScram( - nonce=u'1234567890abcdef', - kdf=u'argon2id13', + nonce='1234567890abcdef', + kdf='argon2id13', salt=binascii.b2a_hex(b'1234567890abcdef').decode('ascii'), iterations=4096, memory=512, - password=u'p4ssw0rd', - authid=u'username', + password='p4ssw0rd', + authid='username', ) scram.authextra with self.assertRaises(ValueError) as ctx: - challenge = types.Challenge(u'scram', { - 'nonce': u'1234567890abcdeffedcba0987654321', - 'kdf': u'argon2id-13', + challenge = types.Challenge('scram', { + 'nonce': '1234567890abcdeffedcba0987654321', + 'kdf': 'argon2id-13', 'salt': binascii.b2a_hex(b'1234567890abcdef'), 'iterations': 4096, # no 'memory' key @@ -222,15 +220,15 @@ def test_unknown_arg(self): salt=binascii.b2a_hex(b'1234567890abcdef'), iterations=4096, memory=512, - password=u'p4ssw0rd', - authid=u'username', + password='p4ssw0rd', + authid='username', ) scram.authextra with self.assertRaises(RuntimeError) as ctx: - challenge = types.Challenge(u'scram', { - 'nonce': u'1234567890abcdeffedcba0987654321', - 'kdf': u'argon2id-13', + challenge = types.Challenge('scram', { + 'nonce': '1234567890abcdeffedcba0987654321', + 'kdf': 'argon2id-13', 'salt': binascii.b2a_hex(b'1234567890abcdef'), 'iterations': 4096, 'memory': 512, diff --git a/autobahn/wamp/test/test_component.py b/autobahn/wamp/test/test_component.py index 6e3616be7..a82eb3dd9 100644 --- a/autobahn/wamp/test/test_component.py +++ b/autobahn/wamp/test/test_component.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os if os.environ.get('USE_TWISTED', False): @@ -58,7 +56,7 @@ def log(self, *args): else: sargs = "-" - msg = u'= : {0:>3} : {1:<20} : {2}'.format(self._logline, self.__class__.__name__, sargs) + msg = '= : {0:>3} : {1:<20} : {2}'.format(self._logline, self.__class__.__name__, sargs) self._logline += 1 print(msg) @@ -118,21 +116,21 @@ def add2(a, b): def stars(nick="somebody", stars=0): self.log("stars() is invoked", nick, stars) - return u"{0} starred {1}x".format(nick, stars) + return "{0} starred {1}x".format(nick, stars) def orders(product, limit=5): self.log("orders() is invoked", product, limit) - return [u"Product {0}".format(i) for i in range(50)][:limit] + return ["Product {0}".format(i) for i in range(50)][:limit] def arglen(*args, **kwargs): self.log("arglen() is invoked", args, kwargs) return [len(args), len(kwargs)] - yield self.register(ping, u'com.arguments.ping') - yield self.register(add2, u'com.arguments.add2') - yield self.register(stars, u'com.arguments.stars') - yield self.register(orders, u'com.arguments.orders') - yield self.register(arglen, u'com.arguments.arglen') + yield self.register(ping, 'com.arguments.ping') + yield self.register(add2, 'com.arguments.add2') + yield self.register(stars, 'com.arguments.stars') + yield self.register(orders, 'com.arguments.orders') + yield self.register(arglen, 'com.arguments.arglen') self.log("procedures registered") @@ -145,40 +143,40 @@ def onJoin(self, details): yield sleep(1) - yield self.call(u'com.arguments.ping') + yield self.call('com.arguments.ping') self.log("Pinged!") - res = yield self.call(u'com.arguments.add2', 2, 3) + res = yield self.call('com.arguments.add2', 2, 3) self.log("Add2: {0}".format(res)) - starred = yield self.call(u'com.arguments.stars') + starred = yield self.call('com.arguments.stars') self.log("Starred 1: {0}".format(starred)) - starred = yield self.call(u'com.arguments.stars', nick=u'Homer') + starred = yield self.call('com.arguments.stars', nick='Homer') self.log("Starred 2: {0}".format(starred)) - starred = yield self.call(u'com.arguments.stars', stars=5) + starred = yield self.call('com.arguments.stars', stars=5) self.log("Starred 3: {0}".format(starred)) - starred = yield self.call(u'com.arguments.stars', nick=u'Homer', stars=5) + starred = yield self.call('com.arguments.stars', nick='Homer', stars=5) self.log("Starred 4: {0}".format(starred)) - orders = yield self.call(u'com.arguments.orders', u'coffee') + orders = yield self.call('com.arguments.orders', 'coffee') self.log("Orders 1: {0}".format(orders)) - orders = yield self.call(u'com.arguments.orders', u'coffee', limit=10) + orders = yield self.call('com.arguments.orders', 'coffee', limit=10) self.log("Orders 2: {0}".format(orders)) - arglengths = yield self.call(u'com.arguments.arglen') + arglengths = yield self.call('com.arguments.arglen') self.log("Arglen 1: {0}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3) + arglengths = yield self.call('com.arguments.arglen', 1, 2, 3) self.log("Arglen 1: {0}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', a=1, b=2, c=3) + arglengths = yield self.call('com.arguments.arglen', a=1, b=2, c=3) self.log("Arglen 2: {0}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3, a=1, b=2, c=3) + arglengths = yield self.call('com.arguments.arglen', 1, 2, 3, a=1, b=2, c=3) self.log("Arglen 3: {0}".format(arglengths)) self.log("finishing") @@ -193,7 +191,7 @@ class TestRpc(unittest.TestCase): def setUp(self): self.url = os.environ.get("WAMP_ROUTER_URL") - self.realm = u"realm1" + self.realm = "realm1" @defer.inlineCallbacks def runOneTest(self, components): diff --git a/autobahn/wamp/test/test_component_aio.py b/autobahn/wamp/test/test_component_aio.py index a0c3e5f37..e67922022 100644 --- a/autobahn/wamp/test/test_component_aio.py +++ b/autobahn/wamp/test/test_component_aio.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os import sys import mock @@ -44,9 +42,9 @@ def test_asyncio_component(event_loop): comp = Component( transports=[ { - u"url": u"ws://localhost:12/bogus", - u"max_retries": 1, - u"max_retry_delay": 0.1, + "url": "ws://localhost:12/bogus", + "max_retries": 1, + "max_retry_delay": 0.1, } ] ) @@ -112,9 +110,9 @@ def create_connection(protocol_factory=None, server_hostname=None, host=None, po comp = Component( transports=[ { - u"url": u"ws://localhost:12/bogus", - u"max_retries": 1, - u"max_retry_delay": 0.1, + "url": "ws://localhost:12/bogus", + "max_retries": 1, + "max_retry_delay": 0.1, } ] ) diff --git a/autobahn/wamp/test/test_cryptobox.py b/autobahn/wamp/test/test_cryptobox.py index 74e785b08..31ca4b948 100644 --- a/autobahn/wamp/test/test_cryptobox.py +++ b/autobahn/wamp/test/test_cryptobox.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.wamp import cryptobox import unittest diff --git a/autobahn/wamp/test/test_cryptosign.py b/autobahn/wamp/test/test_cryptosign.py index ebf376842..e2b551533 100644 --- a/autobahn/wamp/test/test_cryptosign.py +++ b/autobahn/wamp/test/test_cryptosign.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import hashlib import os @@ -77,26 +75,26 @@ def setUp(self): def test_valid(self): session = Mock() session._transport.get_channel_id = Mock(return_value=self.channel_id) - challenge = types.Challenge(u"ticket", dict(challenge="ff" * 32)) + challenge = types.Challenge("ticket", dict(challenge="ff" * 32)) signed = yield self.key.sign_challenge(session, challenge) self.assertEqual( - u'9b6f41540c9b95b4b7b281c3042fa9c54cef43c842d62ea3fd6030fcb66e70b3e80d49d44c29d1635da9348d02ec93f3ed1ef227dfb59a07b580095c2b82f80f9d16ca518aa0c2b707f2b2a609edeca73bca8dd59817a633f35574ac6fd80d00', + '9b6f41540c9b95b4b7b281c3042fa9c54cef43c842d62ea3fd6030fcb66e70b3e80d49d44c29d1635da9348d02ec93f3ed1ef227dfb59a07b580095c2b82f80f9d16ca518aa0c2b707f2b2a609edeca73bca8dd59817a633f35574ac6fd80d00', signed.result, ) def test_authenticator(self): authenticator = create_authenticator( - u"cryptosign", + "cryptosign", authid="someone", privkey=self.privkey_hex, ) session = Mock() session._transport.get_channel_id = Mock(return_value=self.channel_id) - challenge = types.Challenge(u"cryptosign", dict(challenge="ff" * 32)) + challenge = types.Challenge("cryptosign", dict(challenge="ff" * 32)) reply = yield authenticator.on_challenge(session, challenge) self.assertEqual( reply.result, - u'9b6f41540c9b95b4b7b281c3042fa9c54cef43c842d62ea3fd6030fcb66e70b3e80d49d44c29d1635da9348d02ec93f3ed1ef227dfb59a07b580095c2b82f80f9d16ca518aa0c2b707f2b2a609edeca73bca8dd59817a633f35574ac6fd80d00', + '9b6f41540c9b95b4b7b281c3042fa9c54cef43c842d62ea3fd6030fcb66e70b3e80d49d44c29d1635da9348d02ec93f3ed1ef227dfb59a07b580095c2b82f80f9d16ca518aa0c2b707f2b2a609edeca73bca8dd59817a633f35574ac6fd80d00', ) diff --git a/autobahn/wamp/test/test_exception.py b/autobahn/wamp/test/test_exception.py index d9490560b..add2a3014 100644 --- a/autobahn/wamp/test/test_exception.py +++ b/autobahn/wamp/test/test_exception.py @@ -36,15 +36,15 @@ def test_unicode_str(self): Unicode arguments in ApplicationError will not raise an exception when str()'d. """ - error = ApplicationError(u"some.url", u"\u2603") - self.assertIn(u"\u2603", str(error)) + error = ApplicationError("some.url", "\u2603") + self.assertIn("\u2603", str(error)) def test_unicode_errormessage(self): """ Unicode arguments in ApplicationError will not raise an exception when the error_message method is called. """ - error = ApplicationError(u"some.url", u"\u2603") - # on py27-tw189: exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\u2603' in position 10: ordinal not in + error = ApplicationError("some.url", "\u2603") + # on py27-tw189: exceptions.UnicodeEncodeError: 'ascii' codec can't encode character '\u2603' in position 10: ordinal not in print(error.error_message()) - self.assertIn(u"\u2603", error.error_message()) + self.assertIn("\u2603", error.error_message()) diff --git a/autobahn/wamp/test/test_message.py b/autobahn/wamp/test/test_message.py index 2ccd6dffc..c7d39a08f 100644 --- a/autobahn/wamp/test/test_message.py +++ b/autobahn/wamp/test/test_message.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.wamp import role from autobahn.wamp import message from autobahn.wamp.exception import ProtocolError, InvalidUriError @@ -44,22 +42,22 @@ def test_valid_ids(self): self.assertEqual(val, message.check_or_raise_id(val)) def test_invalid_ids(self): - for val in [-1, -9007199254740992, None, b"", b"abc", u"", u"abc", 0.9, Foo(), False, True, [], {}]: + for val in [-1, -9007199254740992, None, b"", b"abc", "", "abc", 0.9, Foo(), False, True, [], {}]: self.assertRaises(ProtocolError, message.check_or_raise_id, val) class TestUris(unittest.TestCase): def test_valid_uris_loose_nonempty(self): - for u in [u"com.myapp.topic1", - u"com.myapp.product.123", - u"com.myapp.product.1.delete", - u"Com-star.MyApp.**+$for", - u"\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5", - u"hello\x24world", - u"hello\xC2\xA2world", - u"hello\xE2\x82\xACworld", - u"hello\xF0\xA4\xAD\xA2world", + for u in ["com.myapp.topic1", + "com.myapp.product.123", + "com.myapp.product.1.delete", + "Com-star.MyApp.**+$for", + "\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5", + "hello\x24world", + "hello\xC2\xA2world", + "hello\xE2\x82\xACworld", + "hello\xF0\xA4\xAD\xA2world", ]: self.assertEqual(u, message.check_or_raise_uri(u)) @@ -71,31 +69,31 @@ def test_invalid_uris_loose_nonempty(self): 0.8, b"abc", Foo(), - u"", - u".", - u"com.", - u"com..product", - u"com.my app.product", - u"com.my\tapp.product", - u"com.my\napp.product", - u"com.myapp.product#", - u"com.#.product", + "", + ".", + "com.", + "com..product", + "com.my app.product", + "com.my\tapp.product", + "com.my\napp.product", + "com.myapp.product#", + "com.#.product", ]: self.assertRaises(InvalidUriError, message.check_or_raise_uri, u) def test_valid_uris_loose_empty(self): - for u in [u"com.myapp.topic1", - u"com.myapp..123", - u"com.myapp.product.1.", - u"com.", - u".", - u"", - u"Com-star.MyApp.**+$for..foo", - u"\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5..foo", - u"hello\x24world..foo", - u"hello\xC2\xA2world..foo", - u"hello\xE2\x82\xACworld..foo", - u"hello\xF0\xA4\xAD\xA2world..foo", + for u in ["com.myapp.topic1", + "com.myapp..123", + "com.myapp.product.1.", + "com.", + ".", + "", + "Com-star.MyApp.**+$for..foo", + "\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5..foo", + "hello\x24world..foo", + "hello\xC2\xA2world..foo", + "hello\xE2\x82\xACworld..foo", + "hello\xF0\xA4\xAD\xA2world..foo", ]: self.assertEqual(u, message.check_or_raise_uri(u, allow_empty_components=True)) @@ -107,18 +105,18 @@ def test_invalid_uris_loose_empty(self): 0.8, b"abc", Foo(), - u"com.my app.product", - u"com.my\tapp.product", - u"com.my\napp.product", - u"com.myapp.product#", - u"com.#.product", + "com.my app.product", + "com.my\tapp.product", + "com.my\napp.product", + "com.myapp.product#", + "com.#.product", ]: self.assertRaises(InvalidUriError, message.check_or_raise_uri, u, allow_empty_components=True) def test_valid_uris_strict_nonempty(self): - for u in [u"com.myapp.topic1", - u"com.myapp.product.123", - u"com.myapp.product.1.delete", + for u in ["com.myapp.topic1", + "com.myapp.product.123", + "com.myapp.product.1.delete", ]: self.assertEqual(u, message.check_or_raise_uri(u, strict=True)) @@ -130,31 +128,31 @@ def test_invalid_uris_strict_nonempty(self): 0.8, b"abc", Foo(), - u"", - u".", - u"com.", - u"com..product", - u"com.my app.product", - u"com.my\tapp.product", - u"com.my\napp.product", - u"com.myapp.product#", - u"com.#.product", - u"Com-star.MyApp.**+$for", - u"\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5", - u"hello\x24world", - u"hello\xC2\xA2world", - u"hello\xE2\x82\xACworld", - u"hello\xF0\xA4\xAD\xA2world", + "", + ".", + "com.", + "com..product", + "com.my app.product", + "com.my\tapp.product", + "com.my\napp.product", + "com.myapp.product#", + "com.#.product", + "Com-star.MyApp.**+$for", + "\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5", + "hello\x24world", + "hello\xC2\xA2world", + "hello\xE2\x82\xACworld", + "hello\xF0\xA4\xAD\xA2world", ]: self.assertRaises(InvalidUriError, message.check_or_raise_uri, u, strict=True) def test_valid_uris_strict_empty(self): - for u in [u"com.myapp.topic1", - u"com.myapp..123", - u"com.myapp.product.1.", - u"com.", - u".", - u"", + for u in ["com.myapp.topic1", + "com.myapp..123", + "com.myapp.product.1.", + "com.", + ".", + "", ]: self.assertEqual(u, message.check_or_raise_uri(u, strict=True, allow_empty_components=True)) @@ -166,17 +164,17 @@ def test_invalid_uris_strict_empty(self): 0.8, b"abc", Foo(), - u"com.my app.product", - u"com.my\tapp.product", - u"com.my\napp.product", - u"com.myapp.product#", - u"com.#.product", - u"Com-star.MyApp.**+$for..foo", - u"\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5..foo", - u"hello\x24world..foo", - u"hello\xC2\xA2world..foo", - u"hello\xE2\x82\xACworld..foo", - u"hello\xF0\xA4\xAD\xA2world..foo", + "com.my app.product", + "com.my\tapp.product", + "com.my\napp.product", + "com.myapp.product#", + "com.#.product", + "Com-star.MyApp.**+$for..foo", + "\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5..foo", + "hello\x24world..foo", + "hello\xC2\xA2world..foo", + "hello\xE2\x82\xACworld..foo", + "hello\xF0\xA4\xAD\xA2world..foo", ]: self.assertRaises(InvalidUriError, message.check_or_raise_uri, u, strict=True, allow_empty_components=True) @@ -184,112 +182,112 @@ def test_invalid_uris_strict_empty(self): class TestErrorMessage(unittest.TestCase): def test_ctor(self): - e = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1') + e = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error1') msg = e.marshal() self.assertEqual(len(msg), 5) self.assertEqual(msg[0], message.Error.MESSAGE_TYPE) self.assertEqual(msg[1], message.Call.MESSAGE_TYPE) self.assertEqual(msg[2], 123456) self.assertEqual(msg[3], {}) - self.assertEqual(msg[4], u'com.myapp.error1') + self.assertEqual(msg[4], 'com.myapp.error1') - e = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}) + e = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error1', args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}) msg = e.marshal() self.assertEqual(len(msg), 7) self.assertEqual(msg[0], message.Error.MESSAGE_TYPE) self.assertEqual(msg[1], message.Call.MESSAGE_TYPE) self.assertEqual(msg[2], 123456) self.assertEqual(msg[3], {}) - self.assertEqual(msg[4], u'com.myapp.error1') + self.assertEqual(msg[4], 'com.myapp.error1') self.assertEqual(msg[5], [1, 2, 3]) - self.assertEqual(msg[6], {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg[6], {'foo': 23, 'bar': 'hello'}) def test_parse_and_marshal(self): - wmsg = [message.Error.MESSAGE_TYPE, message.Call.MESSAGE_TYPE, 123456, {}, u'com.myapp.error1'] + wmsg = [message.Error.MESSAGE_TYPE, message.Call.MESSAGE_TYPE, 123456, {}, 'com.myapp.error1'] msg = message.Error.parse(wmsg) self.assertIsInstance(msg, message.Error) self.assertEqual(msg.request_type, message.Call.MESSAGE_TYPE) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.error, u'com.myapp.error1') + self.assertEqual(msg.error, 'com.myapp.error1') self.assertEqual(msg.args, None) self.assertEqual(msg.kwargs, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Error.MESSAGE_TYPE, message.Call.MESSAGE_TYPE, 123456, {}, u'com.myapp.error1', [1, 2, 3], {u'foo': 23, u'bar': u'hello'}] + wmsg = [message.Error.MESSAGE_TYPE, message.Call.MESSAGE_TYPE, 123456, {}, 'com.myapp.error1', [1, 2, 3], {'foo': 23, 'bar': 'hello'}] msg = message.Error.parse(wmsg) self.assertIsInstance(msg, message.Error) self.assertEqual(msg.request_type, message.Call.MESSAGE_TYPE) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.error, u'com.myapp.error1') + self.assertEqual(msg.error, 'com.myapp.error1') self.assertEqual(msg.args, [1, 2, 3]) - self.assertEqual(msg.kwargs, {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'}) self.assertEqual(msg.marshal(), wmsg) class TestSubscribeMessage(unittest.TestCase): def test_ctor(self): - e = message.Subscribe(123456, u'com.myapp.topic1') + e = message.Subscribe(123456, 'com.myapp.topic1') msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Subscribe.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) - self.assertEqual(msg[3], u'com.myapp.topic1') + self.assertEqual(msg[3], 'com.myapp.topic1') - e = message.Subscribe(123456, u'com.myapp.topic1', match=message.Subscribe.MATCH_PREFIX) + e = message.Subscribe(123456, 'com.myapp.topic1', match=message.Subscribe.MATCH_PREFIX) msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Subscribe.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'match': u'prefix'}) - self.assertEqual(msg[3], u'com.myapp.topic1') + self.assertEqual(msg[2], {'match': 'prefix'}) + self.assertEqual(msg[3], 'com.myapp.topic1') def test_parse_and_marshal(self): - wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {}, u'com.myapp.topic1'] + wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {}, 'com.myapp.topic1'] msg = message.Subscribe.parse(wmsg) self.assertIsInstance(msg, message.Subscribe) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.topic, u'com.myapp.topic1') + self.assertEqual(msg.topic, 'com.myapp.topic1') self.assertEqual(msg.match, message.Subscribe.MATCH_EXACT) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {u'match': u'prefix'}, u'com.myapp.topic1'] + wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {'match': 'prefix'}, 'com.myapp.topic1'] msg = message.Subscribe.parse(wmsg) self.assertIsInstance(msg, message.Subscribe) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.topic, u'com.myapp.topic1') + self.assertEqual(msg.topic, 'com.myapp.topic1') self.assertEqual(msg.match, message.Subscribe.MATCH_PREFIX) self.assertEqual(msg.marshal(), wmsg) def test_get_retained_default_false(self): - wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {u'match': u'prefix'}, u'com.myapp.topic1'] + wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {'match': 'prefix'}, 'com.myapp.topic1'] msg = message.Subscribe.parse(wmsg) self.assertIsInstance(msg, message.Subscribe) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.topic, u'com.myapp.topic1') + self.assertEqual(msg.topic, 'com.myapp.topic1') self.assertEqual(msg.get_retained, None) self.assertNotEqual(msg.get_retained, True) self.assertEqual(msg.match, message.Subscribe.MATCH_PREFIX) self.assertEqual(msg.marshal(), wmsg) def test_get_retained_explicit_false(self): - wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {u'match': u'prefix', u'get_retained': False}, u'com.myapp.topic1'] + wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {'match': 'prefix', 'get_retained': False}, 'com.myapp.topic1'] msg = message.Subscribe.parse(wmsg) self.assertIsInstance(msg, message.Subscribe) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.topic, u'com.myapp.topic1') + self.assertEqual(msg.topic, 'com.myapp.topic1') self.assertEqual(msg.get_retained, False) self.assertNotEqual(msg.get_retained, True) self.assertEqual(msg.match, message.Subscribe.MATCH_PREFIX) self.assertEqual(msg.marshal(), wmsg) def test_get_retained_explicit_true(self): - wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {u'match': u'prefix', u'get_retained': True}, u'com.myapp.topic1'] + wmsg = [message.Subscribe.MESSAGE_TYPE, 123456, {'match': 'prefix', 'get_retained': True}, 'com.myapp.topic1'] msg = message.Subscribe.parse(wmsg) self.assertIsInstance(msg, message.Subscribe) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.topic, u'com.myapp.topic1') + self.assertEqual(msg.topic, 'com.myapp.topic1') self.assertEqual(msg.get_retained, True) self.assertEqual(msg.match, message.Subscribe.MATCH_PREFIX) self.assertEqual(msg.marshal(), wmsg) @@ -347,14 +345,14 @@ def test_ctor(self): self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Unsubscribed.MESSAGE_TYPE) self.assertEqual(msg[1], 0) - self.assertEqual(msg[2], {u'subscription': 123456}) + self.assertEqual(msg[2], {'subscription': 123456}) - e = message.Unsubscribed(0, subscription=123456, reason=u"wamp.subscription.revoked") + e = message.Unsubscribed(0, subscription=123456, reason="wamp.subscription.revoked") msg = e.marshal() self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Unsubscribed.MESSAGE_TYPE) self.assertEqual(msg[1], 0) - self.assertEqual(msg[2], {u'subscription': 123456, u'reason': u"wamp.subscription.revoked"}) + self.assertEqual(msg[2], {'subscription': 123456, 'reason': "wamp.subscription.revoked"}) def test_parse_and_marshal(self): wmsg = [message.Unsubscribed.MESSAGE_TYPE, 123456] @@ -365,7 +363,7 @@ def test_parse_and_marshal(self): self.assertEqual(msg.reason, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Unsubscribed.MESSAGE_TYPE, 0, {u'subscription': 123456}] + wmsg = [message.Unsubscribed.MESSAGE_TYPE, 0, {'subscription': 123456}] msg = message.Unsubscribed.parse(wmsg) self.assertIsInstance(msg, message.Unsubscribed) self.assertEqual(msg.request, 0) @@ -373,50 +371,50 @@ def test_parse_and_marshal(self): self.assertEqual(msg.reason, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Unsubscribed.MESSAGE_TYPE, 0, {u'subscription': 123456, u'reason': u"wamp.subscription.revoked"}] + wmsg = [message.Unsubscribed.MESSAGE_TYPE, 0, {'subscription': 123456, 'reason': "wamp.subscription.revoked"}] msg = message.Unsubscribed.parse(wmsg) self.assertIsInstance(msg, message.Unsubscribed) self.assertEqual(msg.request, 0) self.assertEqual(msg.subscription, 123456) - self.assertEqual(msg.reason, u"wamp.subscription.revoked") + self.assertEqual(msg.reason, "wamp.subscription.revoked") self.assertEqual(msg.marshal(), wmsg) class TestPublishMessage(unittest.TestCase): def test_ctor(self): - e = message.Publish(123456, u'com.myapp.topic1') + e = message.Publish(123456, 'com.myapp.topic1') msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Publish.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) - self.assertEqual(msg[3], u'com.myapp.topic1') + self.assertEqual(msg[3], 'com.myapp.topic1') - e = message.Publish(123456, u'com.myapp.topic1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}) + e = message.Publish(123456, 'com.myapp.topic1', args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}) msg = e.marshal() self.assertEqual(len(msg), 6) self.assertEqual(msg[0], message.Publish.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) - self.assertEqual(msg[3], u'com.myapp.topic1') + self.assertEqual(msg[3], 'com.myapp.topic1') self.assertEqual(msg[4], [1, 2, 3]) - self.assertEqual(msg[5], {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg[5], {'foo': 23, 'bar': 'hello'}) - e = message.Publish(123456, u'com.myapp.topic1', exclude_me=False, exclude=[300], eligible=[100, 200, 300]) + e = message.Publish(123456, 'com.myapp.topic1', exclude_me=False, exclude=[300], eligible=[100, 200, 300]) msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Publish.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'exclude_me': False, u'exclude': [300], u'eligible': [100, 200, 300]}) - self.assertEqual(msg[3], u'com.myapp.topic1') + self.assertEqual(msg[2], {'exclude_me': False, 'exclude': [300], 'eligible': [100, 200, 300]}) + self.assertEqual(msg[3], 'com.myapp.topic1') def test_parse_and_marshal(self): - wmsg = [message.Publish.MESSAGE_TYPE, 123456, {}, u'com.myapp.topic1'] + wmsg = [message.Publish.MESSAGE_TYPE, 123456, {}, 'com.myapp.topic1'] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.topic, u'com.myapp.topic1') + self.assertEqual(msg.topic, 'com.myapp.topic1') self.assertEqual(msg.args, None) self.assertEqual(msg.kwargs, None) self.assertEqual(msg.exclude_me, None) @@ -424,23 +422,23 @@ def test_parse_and_marshal(self): self.assertEqual(msg.eligible, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Publish.MESSAGE_TYPE, 123456, {}, u'com.myapp.topic1', [1, 2, 3], {u'foo': 23, u'bar': u'hello'}] + wmsg = [message.Publish.MESSAGE_TYPE, 123456, {}, 'com.myapp.topic1', [1, 2, 3], {'foo': 23, 'bar': 'hello'}] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.topic, u'com.myapp.topic1') + self.assertEqual(msg.topic, 'com.myapp.topic1') self.assertEqual(msg.args, [1, 2, 3]) - self.assertEqual(msg.kwargs, {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'}) self.assertEqual(msg.exclude_me, None) self.assertEqual(msg.exclude, None) self.assertEqual(msg.eligible, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1'] + wmsg = [message.Publish.MESSAGE_TYPE, 123456, {'exclude_me': False, 'exclude': [300], 'eligible': [100, 200, 300]}, 'com.myapp.topic1'] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.topic, u'com.myapp.topic1') + self.assertEqual(msg.topic, 'com.myapp.topic1') self.assertEqual(msg.args, None) self.assertEqual(msg.kwargs, None) self.assertEqual(msg.exclude_me, False) @@ -452,7 +450,7 @@ def test_retain_default_false(self): """ Retain, when not specified, is False-y by default. """ - wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1'] + wmsg = [message.Publish.MESSAGE_TYPE, 123456, {'exclude_me': False, 'exclude': [300], 'eligible': [100, 200, 300]}, 'com.myapp.topic1'] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.retain, None) @@ -463,7 +461,7 @@ def test_retain_explicit_false(self): """ Retain, when specified as False, shows up in the message. """ - wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'retain': False, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1'] + wmsg = [message.Publish.MESSAGE_TYPE, 123456, {'exclude_me': False, 'retain': False, 'exclude': [300], 'eligible': [100, 200, 300]}, 'com.myapp.topic1'] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.retain, False) @@ -474,7 +472,7 @@ def test_retain_explicit_true(self): """ Retain, when specified as True, shows up in the message. """ - wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'retain': True, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1'] + wmsg = [message.Publish.MESSAGE_TYPE, 123456, {'exclude_me': False, 'retain': True, 'exclude': [300], 'eligible': [100, 200, 300]}, 'com.myapp.topic1'] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.retain, True) @@ -512,7 +510,7 @@ def test_ctor(self): self.assertEqual(msg[2], 789123) self.assertEqual(msg[3], {}) - e = message.Event(123456, 789123, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}) + e = message.Event(123456, 789123, args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}) msg = e.marshal() self.assertEqual(len(msg), 6) self.assertEqual(msg[0], message.Event.MESSAGE_TYPE) @@ -520,7 +518,7 @@ def test_ctor(self): self.assertEqual(msg[2], 789123) self.assertEqual(msg[3], {}) self.assertEqual(msg[4], [1, 2, 3]) - self.assertEqual(msg[5], {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg[5], {'foo': 23, 'bar': 'hello'}) e = message.Event(123456, 789123, publisher=300) msg = e.marshal() @@ -528,7 +526,7 @@ def test_ctor(self): self.assertEqual(msg[0], message.Event.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], 789123) - self.assertEqual(msg[3], {u'publisher': 300}) + self.assertEqual(msg[3], {'publisher': 300}) def test_parse_and_marshal(self): wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {}] @@ -541,17 +539,17 @@ def test_parse_and_marshal(self): self.assertEqual(msg.publisher, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {}, [1, 2, 3], {u'foo': 23, u'bar': u'hello'}] + wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {}, [1, 2, 3], {'foo': 23, 'bar': 'hello'}] msg = message.Event.parse(wmsg) self.assertIsInstance(msg, message.Event) self.assertEqual(msg.subscription, 123456) self.assertEqual(msg.publication, 789123) self.assertEqual(msg.args, [1, 2, 3]) - self.assertEqual(msg.kwargs, {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'}) self.assertEqual(msg.publisher, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {u'publisher': 300}] + wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {'publisher': 300}] msg = message.Event.parse(wmsg) self.assertIsInstance(msg, message.Event) self.assertEqual(msg.subscription, 123456) @@ -570,7 +568,7 @@ def test_retained_default_false(self): self.assertEqual(msg.marshal(), wmsg) def test_retained_explicit_false(self): - wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {u'retained': False}] + wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {'retained': False}] msg = message.Event.parse(wmsg) self.assertIsInstance(msg, message.Event) self.assertEqual(msg.retained, False) @@ -578,7 +576,7 @@ def test_retained_explicit_false(self): self.assertEqual(msg.marshal(), wmsg) def test_retained_explicit_true(self): - wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {u'retained': True}] + wmsg = [message.Event.MESSAGE_TYPE, 123456, 789123, {'retained': True}] msg = message.Event.parse(wmsg) self.assertIsInstance(msg, message.Event) self.assertEqual(msg.retained, True) @@ -588,30 +586,30 @@ def test_retained_explicit_true(self): class TestRegisterMessage(unittest.TestCase): def test_ctor(self): - e = message.Register(123456, u'com.myapp.procedure1') + e = message.Register(123456, 'com.myapp.procedure1') msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Register.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) - self.assertEqual(msg[3], u'com.myapp.procedure1') + self.assertEqual(msg[3], 'com.myapp.procedure1') - e = message.Register(123456, u'com.myapp.procedure1', match=u'wildcard') + e = message.Register(123456, 'com.myapp.procedure1', match='wildcard') msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Register.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'match': u'wildcard'}) - self.assertEqual(msg[3], u'com.myapp.procedure1') + self.assertEqual(msg[2], {'match': 'wildcard'}) + self.assertEqual(msg[3], 'com.myapp.procedure1') def test_ctor_reregister(self): - e = message.Register(123456, u'com.myapp.procedure1', force_reregister=True) + e = message.Register(123456, 'com.myapp.procedure1', force_reregister=True) msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Register.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'force_reregister': True}) - self.assertEqual(msg[3], u'com.myapp.procedure1') + self.assertEqual(msg[2], {'force_reregister': True}) + self.assertEqual(msg[3], 'com.myapp.procedure1') e2 = message.Register.parse(msg) str(e2) @@ -620,8 +618,8 @@ def test_parse_reregister_illegal_force(self): msg = [ message.Register.MESSAGE_TYPE, 123456, - {u'force_reregister': 'truthy'}, - u'com.myapp.procedure1', + {'force_reregister': 'truthy'}, + 'com.myapp.procedure1', ] with self.assertRaises(ProtocolError) as ctx: @@ -629,20 +627,20 @@ def test_parse_reregister_illegal_force(self): self.assertIn("invalid type", str(ctx.exception)) def test_parse_and_marshal(self): - wmsg = [message.Register.MESSAGE_TYPE, 123456, {}, u'com.myapp.procedure1'] + wmsg = [message.Register.MESSAGE_TYPE, 123456, {}, 'com.myapp.procedure1'] msg = message.Register.parse(wmsg) self.assertIsInstance(msg, message.Register) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.procedure, u'com.myapp.procedure1') - self.assertEqual(msg.match, u'exact') + self.assertEqual(msg.procedure, 'com.myapp.procedure1') + self.assertEqual(msg.match, 'exact') self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Register.MESSAGE_TYPE, 123456, {u'match': u'wildcard'}, u'com.myapp.procedure1'] + wmsg = [message.Register.MESSAGE_TYPE, 123456, {'match': 'wildcard'}, 'com.myapp.procedure1'] msg = message.Register.parse(wmsg) self.assertIsInstance(msg, message.Register) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.procedure, u'com.myapp.procedure1') - self.assertEqual(msg.match, u'wildcard') + self.assertEqual(msg.procedure, 'com.myapp.procedure1') + self.assertEqual(msg.match, 'wildcard') self.assertEqual(msg.marshal(), wmsg) @@ -698,14 +696,14 @@ def test_ctor(self): self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Unregistered.MESSAGE_TYPE) self.assertEqual(msg[1], 0) - self.assertEqual(msg[2], {u'registration': 123456}) + self.assertEqual(msg[2], {'registration': 123456}) - e = message.Unregistered(0, registration=123456, reason=u"wamp.registration.revoked") + e = message.Unregistered(0, registration=123456, reason="wamp.registration.revoked") msg = e.marshal() self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Unregistered.MESSAGE_TYPE) self.assertEqual(msg[1], 0) - self.assertEqual(msg[2], {u'registration': 123456, u'reason': u"wamp.registration.revoked"}) + self.assertEqual(msg[2], {'registration': 123456, 'reason': "wamp.registration.revoked"}) def test_parse_and_marshal(self): wmsg = [message.Unregistered.MESSAGE_TYPE, 123456] @@ -716,7 +714,7 @@ def test_parse_and_marshal(self): self.assertEqual(msg.reason, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Unregistered.MESSAGE_TYPE, 0, {u'registration': 123456}] + wmsg = [message.Unregistered.MESSAGE_TYPE, 0, {'registration': 123456}] msg = message.Unregistered.parse(wmsg) self.assertIsInstance(msg, message.Unregistered) self.assertEqual(msg.request, 0) @@ -724,70 +722,70 @@ def test_parse_and_marshal(self): self.assertEqual(msg.reason, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Unregistered.MESSAGE_TYPE, 0, {u'registration': 123456, u'reason': u"wamp.registration.revoked"}] + wmsg = [message.Unregistered.MESSAGE_TYPE, 0, {'registration': 123456, 'reason': "wamp.registration.revoked"}] msg = message.Unregistered.parse(wmsg) self.assertIsInstance(msg, message.Unregistered) self.assertEqual(msg.request, 0) self.assertEqual(msg.registration, 123456) - self.assertEqual(msg.reason, u"wamp.registration.revoked") + self.assertEqual(msg.reason, "wamp.registration.revoked") self.assertEqual(msg.marshal(), wmsg) class TestCallMessage(unittest.TestCase): def test_ctor(self): - e = message.Call(123456, u'com.myapp.procedure1') + e = message.Call(123456, 'com.myapp.procedure1') msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Call.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) - self.assertEqual(msg[3], u'com.myapp.procedure1') + self.assertEqual(msg[3], 'com.myapp.procedure1') - e = message.Call(123456, u'com.myapp.procedure1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}) + e = message.Call(123456, 'com.myapp.procedure1', args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}) msg = e.marshal() self.assertEqual(len(msg), 6) self.assertEqual(msg[0], message.Call.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) - self.assertEqual(msg[3], u'com.myapp.procedure1') + self.assertEqual(msg[3], 'com.myapp.procedure1') self.assertEqual(msg[4], [1, 2, 3]) - self.assertEqual(msg[5], {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg[5], {'foo': 23, 'bar': 'hello'}) - e = message.Call(123456, u'com.myapp.procedure1', timeout=10000) + e = message.Call(123456, 'com.myapp.procedure1', timeout=10000) msg = e.marshal() self.assertEqual(len(msg), 4) self.assertEqual(msg[0], message.Call.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'timeout': 10000}) - self.assertEqual(msg[3], u'com.myapp.procedure1') + self.assertEqual(msg[2], {'timeout': 10000}) + self.assertEqual(msg[3], 'com.myapp.procedure1') def test_parse_and_marshal(self): - wmsg = [message.Call.MESSAGE_TYPE, 123456, {}, u'com.myapp.procedure1'] + wmsg = [message.Call.MESSAGE_TYPE, 123456, {}, 'com.myapp.procedure1'] msg = message.Call.parse(wmsg) self.assertIsInstance(msg, message.Call) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.procedure, u'com.myapp.procedure1') + self.assertEqual(msg.procedure, 'com.myapp.procedure1') self.assertEqual(msg.args, None) self.assertEqual(msg.kwargs, None) self.assertEqual(msg.timeout, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Call.MESSAGE_TYPE, 123456, {}, u'com.myapp.procedure1', [1, 2, 3], {u'foo': 23, u'bar': u'hello'}] + wmsg = [message.Call.MESSAGE_TYPE, 123456, {}, 'com.myapp.procedure1', [1, 2, 3], {'foo': 23, 'bar': 'hello'}] msg = message.Call.parse(wmsg) self.assertIsInstance(msg, message.Call) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.procedure, u'com.myapp.procedure1') + self.assertEqual(msg.procedure, 'com.myapp.procedure1') self.assertEqual(msg.args, [1, 2, 3]) - self.assertEqual(msg.kwargs, {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'}) self.assertEqual(msg.timeout, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Call.MESSAGE_TYPE, 123456, {u'timeout': 10000}, u'com.myapp.procedure1'] + wmsg = [message.Call.MESSAGE_TYPE, 123456, {'timeout': 10000}, 'com.myapp.procedure1'] msg = message.Call.parse(wmsg) self.assertIsInstance(msg, message.Call) self.assertEqual(msg.request, 123456) - self.assertEqual(msg.procedure, u'com.myapp.procedure1') + self.assertEqual(msg.procedure, 'com.myapp.procedure1') self.assertEqual(msg.args, None) self.assertEqual(msg.kwargs, None) self.assertEqual(msg.timeout, 10000) @@ -809,7 +807,7 @@ def test_ctor(self): self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Cancel.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'mode': message.Cancel.KILL}) + self.assertEqual(msg[2], {'mode': message.Cancel.KILL}) def test_parse_and_marshal(self): wmsg = [message.Cancel.MESSAGE_TYPE, 123456, {}] @@ -819,7 +817,7 @@ def test_parse_and_marshal(self): self.assertEqual(msg.mode, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Cancel.MESSAGE_TYPE, 123456, {u'mode': message.Cancel.KILL}] + wmsg = [message.Cancel.MESSAGE_TYPE, 123456, {'mode': message.Cancel.KILL}] msg = message.Cancel.parse(wmsg) self.assertIsInstance(msg, message.Cancel) self.assertEqual(msg.request, 123456) @@ -837,21 +835,21 @@ def test_ctor(self): self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) - e = message.Result(123456, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}) + e = message.Result(123456, args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}) msg = e.marshal() self.assertEqual(len(msg), 5) self.assertEqual(msg[0], message.Result.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) self.assertEqual(msg[3], [1, 2, 3]) - self.assertEqual(msg[4], {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg[4], {'foo': 23, 'bar': 'hello'}) e = message.Result(123456, progress=True) msg = e.marshal() self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Result.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'progress': True}) + self.assertEqual(msg[2], {'progress': True}) def test_parse_and_marshal(self): wmsg = [message.Result.MESSAGE_TYPE, 123456, {}] @@ -863,16 +861,16 @@ def test_parse_and_marshal(self): self.assertEqual(msg.progress, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Result.MESSAGE_TYPE, 123456, {}, [1, 2, 3], {u'foo': 23, u'bar': u'hello'}] + wmsg = [message.Result.MESSAGE_TYPE, 123456, {}, [1, 2, 3], {'foo': 23, 'bar': 'hello'}] msg = message.Result.parse(wmsg) self.assertIsInstance(msg, message.Result) self.assertEqual(msg.request, 123456) self.assertEqual(msg.args, [1, 2, 3]) - self.assertEqual(msg.kwargs, {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'}) self.assertEqual(msg.progress, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Result.MESSAGE_TYPE, 123456, {u'progress': True}] + wmsg = [message.Result.MESSAGE_TYPE, 123456, {'progress': True}] msg = message.Result.parse(wmsg) self.assertIsInstance(msg, message.Result) self.assertEqual(msg.request, 123456) @@ -893,7 +891,7 @@ def test_ctor(self): self.assertEqual(msg[2], 789123) self.assertEqual(msg[3], {}) - e = message.Invocation(123456, 789123, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}) + e = message.Invocation(123456, 789123, args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}) msg = e.marshal() self.assertEqual(len(msg), 6) self.assertEqual(msg[0], message.Invocation.MESSAGE_TYPE) @@ -901,7 +899,7 @@ def test_ctor(self): self.assertEqual(msg[2], 789123) self.assertEqual(msg[3], {}) self.assertEqual(msg[4], [1, 2, 3]) - self.assertEqual(msg[5], {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg[5], {'foo': 23, 'bar': 'hello'}) e = message.Invocation(123456, 789123, timeout=10000) msg = e.marshal() @@ -909,7 +907,7 @@ def test_ctor(self): self.assertEqual(msg[0], message.Invocation.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], 789123) - self.assertEqual(msg[3], {u'timeout': 10000}) + self.assertEqual(msg[3], {'timeout': 10000}) def test_parse_and_marshal(self): wmsg = [message.Invocation.MESSAGE_TYPE, 123456, 789123, {}] @@ -922,17 +920,17 @@ def test_parse_and_marshal(self): self.assertEqual(msg.timeout, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Invocation.MESSAGE_TYPE, 123456, 789123, {}, [1, 2, 3], {u'foo': 23, u'bar': u'hello'}] + wmsg = [message.Invocation.MESSAGE_TYPE, 123456, 789123, {}, [1, 2, 3], {'foo': 23, 'bar': 'hello'}] msg = message.Invocation.parse(wmsg) self.assertIsInstance(msg, message.Invocation) self.assertEqual(msg.request, 123456) self.assertEqual(msg.registration, 789123) self.assertEqual(msg.args, [1, 2, 3]) - self.assertEqual(msg.kwargs, {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'}) self.assertEqual(msg.timeout, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Invocation.MESSAGE_TYPE, 123456, 789123, {u'timeout': 10000}] + wmsg = [message.Invocation.MESSAGE_TYPE, 123456, 789123, {'timeout': 10000}] msg = message.Invocation.parse(wmsg) self.assertIsInstance(msg, message.Invocation) self.assertEqual(msg.request, 123456) @@ -958,7 +956,7 @@ def test_ctor(self): self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Interrupt.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'mode': message.Interrupt.KILL}) + self.assertEqual(msg[2], {'mode': message.Interrupt.KILL}) def test_parse_and_marshal(self): wmsg = [message.Interrupt.MESSAGE_TYPE, 123456, {}] @@ -968,7 +966,7 @@ def test_parse_and_marshal(self): self.assertEqual(msg.mode, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Interrupt.MESSAGE_TYPE, 123456, {u'mode': message.Interrupt.KILL}] + wmsg = [message.Interrupt.MESSAGE_TYPE, 123456, {'mode': message.Interrupt.KILL}] msg = message.Interrupt.parse(wmsg) self.assertIsInstance(msg, message.Interrupt) self.assertEqual(msg.request, 123456) @@ -986,21 +984,21 @@ def test_ctor(self): self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) - e = message.Yield(123456, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}) + e = message.Yield(123456, args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}) msg = e.marshal() self.assertEqual(len(msg), 5) self.assertEqual(msg[0], message.Yield.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) self.assertEqual(msg[2], {}) self.assertEqual(msg[3], [1, 2, 3]) - self.assertEqual(msg[4], {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg[4], {'foo': 23, 'bar': 'hello'}) e = message.Yield(123456, progress=True) msg = e.marshal() self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Yield.MESSAGE_TYPE) self.assertEqual(msg[1], 123456) - self.assertEqual(msg[2], {u'progress': True}) + self.assertEqual(msg[2], {'progress': True}) def test_parse_and_marshal(self): wmsg = [message.Yield.MESSAGE_TYPE, 123456, {}] @@ -1012,16 +1010,16 @@ def test_parse_and_marshal(self): self.assertEqual(msg.progress, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Yield.MESSAGE_TYPE, 123456, {}, [1, 2, 3], {u'foo': 23, u'bar': u'hello'}] + wmsg = [message.Yield.MESSAGE_TYPE, 123456, {}, [1, 2, 3], {'foo': 23, 'bar': 'hello'}] msg = message.Yield.parse(wmsg) self.assertIsInstance(msg, message.Yield) self.assertEqual(msg.request, 123456) self.assertEqual(msg.args, [1, 2, 3]) - self.assertEqual(msg.kwargs, {u'foo': 23, u'bar': u'hello'}) + self.assertEqual(msg.kwargs, {'foo': 23, 'bar': 'hello'}) self.assertEqual(msg.progress, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Yield.MESSAGE_TYPE, 123456, {u'progress': True}] + wmsg = [message.Yield.MESSAGE_TYPE, 123456, {'progress': True}] msg = message.Yield.parse(wmsg) self.assertIsInstance(msg, message.Yield) self.assertEqual(msg.request, 123456) @@ -1034,71 +1032,71 @@ def test_parse_and_marshal(self): class TestHelloMessage(unittest.TestCase): def test_ctor(self): - e = message.Hello(u"realm1", {u'publisher': role.RolePublisherFeatures()}) + e = message.Hello("realm1", {'publisher': role.RolePublisherFeatures()}) msg = e.marshal() self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Hello.MESSAGE_TYPE) - self.assertEqual(msg[1], u"realm1") - self.assertEqual(msg[2], {u'roles': {u'publisher': {}}}) + self.assertEqual(msg[1], "realm1") + self.assertEqual(msg[2], {'roles': {'publisher': {}}}) - e = message.Hello(u"realm1", {u'publisher': role.RolePublisherFeatures(subscriber_blackwhite_listing=True)}) + e = message.Hello("realm1", {'publisher': role.RolePublisherFeatures(subscriber_blackwhite_listing=True)}) msg = e.marshal() self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Hello.MESSAGE_TYPE) - self.assertEqual(msg[1], u"realm1") - self.assertEqual(msg[2], {u'roles': {u'publisher': {u'features': {u'subscriber_blackwhite_listing': True}}}}) + self.assertEqual(msg[1], "realm1") + self.assertEqual(msg[2], {'roles': {'publisher': {'features': {'subscriber_blackwhite_listing': True}}}}) - e = message.Hello(u"realm1", {u'publisher': role.RolePublisherFeatures(subscriber_blackwhite_listing=True)}, resumable=True) + e = message.Hello("realm1", {'publisher': role.RolePublisherFeatures(subscriber_blackwhite_listing=True)}, resumable=True) msg = e.marshal() self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Hello.MESSAGE_TYPE) - self.assertEqual(msg[1], u"realm1") - self.assertEqual(msg[2], {u'roles': {u'publisher': {u'features': {u'subscriber_blackwhite_listing': True}}}, u'resumable': True}) + self.assertEqual(msg[1], "realm1") + self.assertEqual(msg[2], {'roles': {'publisher': {'features': {'subscriber_blackwhite_listing': True}}}, 'resumable': True}) def test_parse_and_marshal(self): - wmsg = [message.Hello.MESSAGE_TYPE, u"realm1", {u'roles': {u'publisher': {}}}] + wmsg = [message.Hello.MESSAGE_TYPE, "realm1", {'roles': {'publisher': {}}}] msg = message.Hello.parse(wmsg) self.assertIsInstance(msg, message.Hello) - self.assertEqual(msg.realm, u"realm1") - self.assertEqual(msg.roles, {u'publisher': role.RolePublisherFeatures()}) + self.assertEqual(msg.realm, "realm1") + self.assertEqual(msg.roles, {'publisher': role.RolePublisherFeatures()}) self.assertEqual(msg.resumable, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Hello.MESSAGE_TYPE, u"realm1", {u'roles': {u'publisher': {u'features': {u'subscriber_blackwhite_listing': True}}}}] + wmsg = [message.Hello.MESSAGE_TYPE, "realm1", {'roles': {'publisher': {'features': {'subscriber_blackwhite_listing': True}}}}] msg = message.Hello.parse(wmsg) self.assertIsInstance(msg, message.Hello) - self.assertEqual(msg.realm, u"realm1") - self.assertEqual(msg.roles, {u'publisher': role.RolePublisherFeatures(subscriber_blackwhite_listing=True)}) + self.assertEqual(msg.realm, "realm1") + self.assertEqual(msg.roles, {'publisher': role.RolePublisherFeatures(subscriber_blackwhite_listing=True)}) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Hello.MESSAGE_TYPE, u"realm1", {u'roles': {u'publisher': {}}, u'resumable': False}] + wmsg = [message.Hello.MESSAGE_TYPE, "realm1", {'roles': {'publisher': {}}, 'resumable': False}] msg = message.Hello.parse(wmsg) self.assertIsInstance(msg, message.Hello) - self.assertEqual(msg.realm, u"realm1") - self.assertEqual(msg.roles, {u'publisher': role.RolePublisherFeatures()}) + self.assertEqual(msg.realm, "realm1") + self.assertEqual(msg.roles, {'publisher': role.RolePublisherFeatures()}) self.assertEqual(msg.resumable, False) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Hello.MESSAGE_TYPE, u"realm1", {u'roles': {u'publisher': {}}, u'resumable': True, u'resume-session': 1234, u'resume-token': u"dsjgsg"}] + wmsg = [message.Hello.MESSAGE_TYPE, "realm1", {'roles': {'publisher': {}}, 'resumable': True, 'resume-session': 1234, 'resume-token': "dsjgsg"}] msg = message.Hello.parse(wmsg) self.assertIsInstance(msg, message.Hello) - self.assertEqual(msg.realm, u"realm1") - self.assertEqual(msg.roles, {u'publisher': role.RolePublisherFeatures()}) + self.assertEqual(msg.realm, "realm1") + self.assertEqual(msg.roles, {'publisher': role.RolePublisherFeatures()}) self.assertEqual(msg.resumable, True) self.assertEqual(msg.resume_session, 1234) - self.assertEqual(msg.resume_token, u"dsjgsg") + self.assertEqual(msg.resume_token, "dsjgsg") self.assertEqual(msg.marshal(), wmsg) def test_str(self): - e = message.Hello(u"realm1", {u'publisher': role.RolePublisherFeatures()}) + e = message.Hello("realm1", {'publisher': role.RolePublisherFeatures()}) self.assertIsInstance(str(e), str) class TestGoodbyeMessage(unittest.TestCase): def test_ctor(self): - reason = u'wamp.error.system_shutdown' - reason_msg = u'The host is shutting down now.' + reason = 'wamp.error.system_shutdown' + reason_msg = 'The host is shutting down now.' e = message.Goodbye() msg = e.marshal() @@ -1118,12 +1116,12 @@ def test_ctor(self): msg = e.marshal() self.assertEqual(len(msg), 3) self.assertEqual(msg[0], message.Goodbye.MESSAGE_TYPE) - self.assertEqual(msg[1], {u'message': reason_msg}) + self.assertEqual(msg[1], {'message': reason_msg}) self.assertEqual(msg[2], reason) def test_parse_and_marshal(self): - reason = u'wamp.error.system_shutdown' - reason_msg = u'The host is shutting down now.' + reason = 'wamp.error.system_shutdown' + reason_msg = 'The host is shutting down now.' wmsg = [message.Goodbye.MESSAGE_TYPE] self.assertRaises(ProtocolError, message.Goodbye.parse, wmsg) @@ -1131,7 +1129,7 @@ def test_parse_and_marshal(self): wmsg = [message.Goodbye.MESSAGE_TYPE, reason] self.assertRaises(ProtocolError, message.Goodbye.parse, wmsg) - wmsg = [message.Goodbye.MESSAGE_TYPE, {u'message': 100}, reason] + wmsg = [message.Goodbye.MESSAGE_TYPE, {'message': 100}, reason] self.assertRaises(ProtocolError, message.Goodbye.parse, wmsg) wmsg = [message.Goodbye.MESSAGE_TYPE, {}, reason] @@ -1141,7 +1139,7 @@ def test_parse_and_marshal(self): self.assertEqual(msg.message, None) self.assertEqual(msg.marshal(), wmsg) - wmsg = [message.Goodbye.MESSAGE_TYPE, {u'message': reason_msg}, reason] + wmsg = [message.Goodbye.MESSAGE_TYPE, {'message': reason_msg}, reason] msg = message.Goodbye.parse(wmsg) self.assertIsInstance(msg, message.Goodbye) self.assertEqual(msg.reason, reason) @@ -1149,5 +1147,5 @@ def test_parse_and_marshal(self): self.assertEqual(msg.marshal(), wmsg) def test_str(self): - e = message.Goodbye(reason=u'wamp.error.system_shutdown', message=u'The host is shutting down now.') + e = message.Goodbye(reason='wamp.error.system_shutdown', message='The host is shutting down now.') self.assertIsInstance(str(e), str) diff --git a/autobahn/wamp/test/test_protocol.py b/autobahn/wamp/test/test_protocol.py index d3e254404..b244909cb 100644 --- a/autobahn/wamp/test/test_protocol.py +++ b/autobahn/wamp/test/test_protocol.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os import mock @@ -61,7 +59,7 @@ def __init__(self, handler): self._my_session_id = util.id() - roles = {u'broker': role.RoleBrokerFeatures(), u'dealer': role.RoleDealerFeatures()} + roles = {'broker': role.RoleBrokerFeatures(), 'dealer': role.RoleDealerFeatures()} msg = message.Welcome(self._my_session_id, roles) self._handler.onMessage(msg) @@ -80,25 +78,25 @@ def send(self, msg): reply = None if isinstance(msg, message.Publish): - if msg.topic.startswith(u'com.myapp'): + if msg.topic.startswith('com.myapp'): if msg.acknowledge: reply = message.Published(msg.request, self._fake_router_session._request_id_gen.next()) elif len(msg.topic) == 0: - reply = message.Error(message.Publish.MESSAGE_TYPE, msg.request, u'wamp.error.invalid_uri') - elif msg.topic.startswith(u'noreply.'): + reply = message.Error(message.Publish.MESSAGE_TYPE, msg.request, 'wamp.error.invalid_uri') + elif msg.topic.startswith('noreply.'): pass else: - reply = message.Error(message.Publish.MESSAGE_TYPE, msg.request, u'wamp.error.not_authorized') + reply = message.Error(message.Publish.MESSAGE_TYPE, msg.request, 'wamp.error.not_authorized') elif isinstance(msg, message.Call): - if msg.procedure == u'com.myapp.procedure1': + if msg.procedure == 'com.myapp.procedure1': reply = message.Result(msg.request, args=[100]) - elif msg.procedure == u'com.myapp.procedure2': + elif msg.procedure == 'com.myapp.procedure2': reply = message.Result(msg.request, args=[1, 2, 3]) - elif msg.procedure == u'com.myapp.procedure3': - reply = message.Result(msg.request, args=[1, 2, 3], kwargs={u'foo': u'bar', u'baz': 23}) + elif msg.procedure == 'com.myapp.procedure3': + reply = message.Result(msg.request, args=[1, 2, 3], kwargs={'foo': 'bar', 'baz': 23}) - elif msg.procedure.startswith(u'com.myapp.myproc'): + elif msg.procedure.startswith('com.myapp.myproc'): registration = self._registrations[msg.procedure] request = self._fake_router_session._request_id_gen.next() if request in self._invocations: @@ -111,7 +109,7 @@ def send(self, msg): receive_progress=msg.receive_progress, ) else: - reply = message.Error(message.Call.MESSAGE_TYPE, msg.request, u'wamp.error.no_such_procedure') + reply = message.Error(message.Call.MESSAGE_TYPE, msg.request, 'wamp.error.no_such_procedure') elif isinstance(msg, message.Yield): if msg.request in self._invocations: @@ -189,13 +187,13 @@ def test_prefix(self): class Prefix(ApplicationSession): - @uri.register(u'method_name') + @uri.register('method_name') def some_method(self): pass session = Prefix() session._transport = mock.Mock() - session.register(session, prefix=u"com.example.prefix.") + session.register(session, prefix="com.example.prefix.") # we should have registered one method, with the prefix # put in front @@ -203,7 +201,7 @@ def some_method(self): call = session._transport.mock_calls[0] self.assertEqual("send", call[0]) reg = call.call_list()[0][1][0] - self.assertEqual(u"com.example.prefix.method_name", reg.procedure) + self.assertEqual("com.example.prefix.method_name", reg.procedure) def test_auto_name(self): @@ -215,14 +213,14 @@ def some_method(self): session = Magic() session._transport = mock.Mock() - session.register(session, prefix=u"com.example.") + session.register(session, prefix="com.example.") # Should auto-discover name by passing uri=None above self.assertEqual(1, len(session._transport.mock_calls)) call = session._transport.mock_calls[0] self.assertEqual("send", call[0]) reg = call.call_list()[0][1][0] - self.assertEqual(u"com.example.some_method", reg.procedure) + self.assertEqual("com.example.some_method", reg.procedure) class TestPublisher(unittest.TestCase): @@ -231,22 +229,22 @@ def test_publish(self): handler = ApplicationSession() MockTransport(handler) - publication = yield handler.publish(u'com.myapp.topic1') + publication = yield handler.publish('com.myapp.topic1') self.assertEqual(publication, None) - publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3) + publication = yield handler.publish('com.myapp.topic1', 1, 2, 3) self.assertEqual(publication, None) - publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo=23, bar='hello') + publication = yield handler.publish('com.myapp.topic1', 1, 2, 3, foo=23, bar='hello') self.assertEqual(publication, None) - publication = yield handler.publish(u'com.myapp.topic1', options=types.PublishOptions(exclude_me=False)) + publication = yield handler.publish('com.myapp.topic1', options=types.PublishOptions(exclude_me=False)) self.assertEqual(publication, None) - publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo=23, bar='hello', options=types.PublishOptions(exclude_me=False, exclude=[100, 200, 300])) + publication = yield handler.publish('com.myapp.topic1', 1, 2, 3, foo=23, bar='hello', options=types.PublishOptions(exclude_me=False, exclude=[100, 200, 300])) self.assertEqual(publication, None) - publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo=23, bar='hello', options=types.PublishOptions(exclude_me=False, exclude=[100, 200, 300], retain=True)) + publication = yield handler.publish('com.myapp.topic1', 1, 2, 3, foo=23, bar='hello', options=types.PublishOptions(exclude_me=False, exclude=[100, 200, 300], retain=True)) self.assertEqual(publication, None) @inlineCallbacks @@ -258,20 +256,20 @@ def test_publish_outstanding_errors(self): # handled specially in MockTransport; so this request will # be outstanding publication = handler.publish( - u'noreply.foo', + 'noreply.foo', options=types.PublishOptions(acknowledge=True), ) # "leave" the session, which should trigger errbacks on # all outstanding requests. - details = types.CloseDetails(reason=u'testing', message=u'how are you?') + details = types.CloseDetails(reason='testing', message='how are you?') yield handler.onLeave(details) # ensure we got our errback try: yield publication except ApplicationError as e: - self.assertEqual(u'testing', e.error) - self.assertEqual(u'how are you?', e.message) + self.assertEqual('testing', e.error) + self.assertEqual('how are you?', e.message) @inlineCallbacks def test_publish_outstanding_errors_async_errback(self): @@ -283,7 +281,7 @@ def test_publish_outstanding_errors_async_errback(self): # handled specially in MockTransport; so this request will # be outstanding publication_d = handler.publish( - u'noreply.foo', + 'noreply.foo', options=types.PublishOptions(acknowledge=True), ) # further, we add an errback that does some arbitrary async work @@ -295,7 +293,7 @@ def errback(fail): publication_d.addErrback(errback) # "leave" the session, which should trigger errbacks on # all outstanding requests. - details = types.CloseDetails(reason=u'testing', message=u'how are you?') + details = types.CloseDetails(reason='testing', message='how are you?') handler.onLeave(details) # since our errback is async, onLeave should not have @@ -311,27 +309,27 @@ def errback(fail): try: yield publication_d except ApplicationError as e: - self.assertEqual(u'testing', e.error) - self.assertEqual(u'how are you?', e.message) + self.assertEqual('testing', e.error) + self.assertEqual('how are you?', e.message) @inlineCallbacks def test_publish_acknowledged(self): handler = ApplicationSession() MockTransport(handler) - publication = yield handler.publish(u'com.myapp.topic1', options=types.PublishOptions(acknowledge=True)) + publication = yield handler.publish('com.myapp.topic1', options=types.PublishOptions(acknowledge=True)) self.assertTrue(type(publication.id) == int) - publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, options=types.PublishOptions(acknowledge=True)) + publication = yield handler.publish('com.myapp.topic1', 1, 2, 3, options=types.PublishOptions(acknowledge=True)) self.assertTrue(type(publication.id) == int) - publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo=23, bar='hello', options=types.PublishOptions(acknowledge=True)) + publication = yield handler.publish('com.myapp.topic1', 1, 2, 3, foo=23, bar='hello', options=types.PublishOptions(acknowledge=True)) self.assertTrue(type(publication.id) == int) - publication = yield handler.publish(u'com.myapp.topic1', options=types.PublishOptions(exclude_me=False, acknowledge=True)) + publication = yield handler.publish('com.myapp.topic1', options=types.PublishOptions(exclude_me=False, acknowledge=True)) self.assertTrue(type(publication.id) == int) - publication = yield handler.publish(u'com.myapp.topic1', 1, 2, 3, foo=23, bar='hello', options=types.PublishOptions(exclude_me=False, exclude=[100, 200, 300], acknowledge=True)) + publication = yield handler.publish('com.myapp.topic1', 1, 2, 3, foo=23, bar='hello', options=types.PublishOptions(exclude_me=False, exclude=[100, 200, 300], acknowledge=True)) self.assertTrue(type(publication.id) == int) @inlineCallbacks @@ -341,8 +339,8 @@ def test_publish_undefined_exception(self): options = types.PublishOptions(acknowledge=True) - yield self.assertFailure(handler.publish(u'de.myapp.topic1', options=options), ApplicationError) - yield self.assertFailure(handler.publish(u'foobar', options=options), ApplicationError) + yield self.assertFailure(handler.publish('de.myapp.topic1', options=options), ApplicationError) + yield self.assertFailure(handler.publish('foobar', options=options), ApplicationError) @inlineCallbacks def test_publish_defined_exception(self): @@ -352,29 +350,29 @@ def test_publish_defined_exception(self): options = types.PublishOptions(acknowledge=True) handler.define(NotAuthorized) - yield self.assertFailure(handler.publish(u'de.myapp.topic1', options=options), NotAuthorized) + yield self.assertFailure(handler.publish('de.myapp.topic1', options=options), NotAuthorized) handler.define(InvalidUri) - yield self.assertFailure(handler.publish(u'foobar', options=options), NotAuthorized) + yield self.assertFailure(handler.publish('foobar', options=options), NotAuthorized) @inlineCallbacks def test_call(self): handler = ApplicationSession() MockTransport(handler) - res = yield handler.call(u'com.myapp.procedure1') + res = yield handler.call('com.myapp.procedure1') self.assertEqual(res, 100) - res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3) + res = yield handler.call('com.myapp.procedure1', 1, 2, 3) self.assertEqual(res, 100) - res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3, foo=23, bar='hello') + res = yield handler.call('com.myapp.procedure1', 1, 2, 3, foo=23, bar='hello') self.assertEqual(res, 100) - res = yield handler.call(u'com.myapp.procedure1', options=types.CallOptions(timeout=10000)) + res = yield handler.call('com.myapp.procedure1', options=types.CallOptions(timeout=10000)) self.assertEqual(res, 100) - res = yield handler.call(u'com.myapp.procedure1', 1, 2, 3, foo=23, bar='hello', options=types.CallOptions(timeout=10000)) + res = yield handler.call('com.myapp.procedure1', 1, 2, 3, foo=23, bar='hello', options=types.CallOptions(timeout=10000)) self.assertEqual(res, 100) @inlineCallbacks @@ -382,12 +380,12 @@ def test_call_with_complex_result(self): handler = ApplicationSession() MockTransport(handler) - res = yield handler.call(u'com.myapp.procedure2') + res = yield handler.call('com.myapp.procedure2') self.assertIsInstance(res, types.CallResult) self.assertEqual(res.results, (1, 2, 3)) self.assertEqual(res.kwresults, {}) - res = yield handler.call(u'com.myapp.procedure3') + res = yield handler.call('com.myapp.procedure3') self.assertIsInstance(res, types.CallResult) self.assertEqual(res.results, (1, 2, 3)) self.assertEqual(res.kwresults, {'foo': 'bar', 'baz': 23}) @@ -400,13 +398,13 @@ def test_subscribe(self): def on_event(*args, **kwargs): print("got event", args, kwargs) - subscription = yield handler.subscribe(on_event, u'com.myapp.topic1') + subscription = yield handler.subscribe(on_event, 'com.myapp.topic1') self.assertTrue(type(subscription.id) == int) - subscription = yield handler.subscribe(on_event, u'com.myapp.topic1', options=types.SubscribeOptions(match=u'wildcard')) + subscription = yield handler.subscribe(on_event, 'com.myapp.topic1', options=types.SubscribeOptions(match='wildcard')) self.assertTrue(type(subscription.id) == int) - subscription = yield handler.subscribe(on_event, u'com.myapp.topic1', options=types.SubscribeOptions(match=u'wildcard', get_retained=True)) + subscription = yield handler.subscribe(on_event, 'com.myapp.topic1', options=types.SubscribeOptions(match='wildcard', get_retained=True)) self.assertTrue(type(subscription.id) == int) @inlineCallbacks @@ -418,9 +416,9 @@ def test_double_subscribe(self): event1 = Deferred() subscription0 = yield handler.subscribe( - lambda: event0.callback(42), u'com.myapp.topic1') + lambda: event0.callback(42), 'com.myapp.topic1') subscription1 = yield handler.subscribe( - lambda: event1.callback('foo'), u'com.myapp.topic1') + lambda: event1.callback('foo'), 'com.myapp.topic1') # same topic, same ID self.assertTrue(subscription0.id == subscription1.id) @@ -428,7 +426,7 @@ def test_double_subscribe(self): # message) and then do an actual publish event. The IDs # are the same, so we just do one Event. publish = yield handler.publish( - u'com.myapp.topic1', + 'com.myapp.topic1', options=types.PublishOptions(acknowledge=True, exclude_me=False), ) handler.onMessage(message.Event(subscription0.id, publish.id)) @@ -459,9 +457,9 @@ def onMessage(msg): event1 = Deferred() subscription0 = yield handler.subscribe( - lambda: event0.callback(42), u'com.myapp.topic1') + lambda: event0.callback(42), 'com.myapp.topic1') subscription1 = yield handler.subscribe( - lambda: event1.callback('foo'), u'com.myapp.topic1') + lambda: event1.callback('foo'), 'com.myapp.topic1') self.assertTrue(subscription0.id == subscription1.id) yield subscription1.unsubscribe() @@ -470,7 +468,7 @@ def onMessage(msg): # message) and then do an actual publish event. Note the # IDs are the same, so there's only one Event. publish = yield handler.publish( - u'com.myapp.topic1', + 'com.myapp.topic1', options=types.PublishOptions(acknowledge=True, exclude_me=False), ) handler.onMessage(message.Event(subscription0.id, publish.id)) @@ -502,9 +500,9 @@ def onMessage(msg): event1 = Deferred() subscription0 = yield handler.subscribe( - lambda: event0.callback(42), u'com.myapp.topic1') + lambda: event0.callback(42), 'com.myapp.topic1') subscription1 = yield handler.subscribe( - lambda: event1.callback('foo'), u'com.myapp.topic1') + lambda: event1.callback('foo'), 'com.myapp.topic1') self.assertTrue(subscription0.id == subscription1.id) yield subscription0.unsubscribe() @@ -519,7 +517,7 @@ def onMessage(msg): # the Event should be an error, as we have no # subscriptions left. publish = yield handler.publish( - u'com.myapp.topic1', + 'com.myapp.topic1', options=types.PublishOptions(acknowledge=True, exclude_me=False), ) try: @@ -554,9 +552,9 @@ def second(*args, **kw): event1.callback(args) subscription0 = yield handler.subscribe( - lambda arg: event0.callback(arg), u'com.myapp.topic1') + lambda arg: event0.callback(arg), 'com.myapp.topic1') subscription1 = yield handler.subscribe( - second, u'com.myapp.topic1', + second, 'com.myapp.topic1', types.SubscribeOptions(details_arg='boom'), ) # same topic, same ID @@ -565,7 +563,7 @@ def second(*args, **kw): # MockTransport gives us the ack reply and then we do our # own event message. publish = yield handler.publish( - u'com.myapp.topic1', + 'com.myapp.topic1', options=types.PublishOptions(acknowledge=True, exclude_me=False), ) # note that the protocol serializer converts all sequences @@ -600,12 +598,12 @@ def observer(e, msg): def boom(): raise error_instance - sub = yield handler.subscribe(boom, u'com.myapp.topic1') + sub = yield handler.subscribe(boom, 'com.myapp.topic1') # MockTransport gives us the ack reply and then we do our # own event message publish = yield handler.publish( - u'com.myapp.topic1', + 'com.myapp.topic1', options=types.PublishOptions(acknowledge=True, exclude_me=False), ) msg = message.Event(sub.id, publish.id) @@ -623,7 +621,7 @@ def test_unsubscribe(self): def on_event(*args, **kwargs): print("got event", args, kwargs) - subscription = yield handler.subscribe(on_event, u'com.myapp.topic1') + subscription = yield handler.subscribe(on_event, 'com.myapp.topic1') yield subscription.unsubscribe() @inlineCallbacks @@ -634,10 +632,10 @@ def test_register(self): def on_call(*args, **kwargs): print("got call", args, kwargs) - registration = yield handler.register(on_call, u'com.myapp.procedure1') + registration = yield handler.register(on_call, 'com.myapp.procedure1') self.assertTrue(type(registration.id) == int) - registration = yield handler.register(on_call, u'com.myapp.procedure1', options=types.RegisterOptions(match=u'prefix')) + registration = yield handler.register(on_call, 'com.myapp.procedure1', options=types.RegisterOptions(match='prefix')) self.assertTrue(type(registration.id) == int) @inlineCallbacks @@ -648,7 +646,7 @@ def test_unregister(self): def on_call(*args, **kwargs): print("got call", args, kwargs) - registration = yield handler.register(on_call, u'com.myapp.procedure1') + registration = yield handler.register(on_call, 'com.myapp.procedure1') yield registration.unregister() def test_unregister_no_such_registration(self): @@ -675,7 +673,7 @@ def on_call(*args, **kwargs): on_call.called = True on_call.called = False - registration = yield handler.register(on_call, u'com.myapp.procedure1') + registration = yield handler.register(on_call, 'com.myapp.procedure1') transport.drop_registration(registration.id) self.assertFalse(on_call.called) @@ -711,9 +709,9 @@ def test_invoke(self): def myproc1(): return 23 - yield handler.register(myproc1, u'com.myapp.myproc1') + yield handler.register(myproc1, 'com.myapp.myproc1') - res = yield handler.call(u'com.myapp.myproc1') + res = yield handler.call('com.myapp.myproc1') self.assertEqual(res, 23) @inlineCallbacks @@ -724,10 +722,10 @@ def test_invoke_twice(self): def myproc1(): return 23 - yield handler.register(myproc1, u'com.myapp.myproc1') + yield handler.register(myproc1, 'com.myapp.myproc1') - d0 = handler.call(u'com.myapp.myproc1') - d1 = handler.call(u'com.myapp.myproc1') + d0 = handler.call('com.myapp.myproc1') + d1 = handler.call('com.myapp.myproc1') res = yield DeferredList([d0, d1]) self.assertEqual(res, [(True, 23), (True, 23)]) @@ -757,11 +755,11 @@ def verify_seq_id(orig, msg): def myproc1(): return 23 - yield handler0.register(myproc1, u'com.myapp.myproc1') - yield handler1.register(myproc1, u'com.myapp.myproc1') + yield handler0.register(myproc1, 'com.myapp.myproc1') + yield handler1.register(myproc1, 'com.myapp.myproc1') - d0 = handler0.call(u'com.myapp.myproc1') - d1 = handler1.call(u'com.myapp.myproc1') + d0 = handler0.call('com.myapp.myproc1') + d1 = handler1.call('com.myapp.myproc1') res = yield DeferredList([d0, d1]) self.assertEqual(res, [(True, 23), (True, 23)]) @@ -782,10 +780,10 @@ def bing(): raise name_error # see MockTransport, must start with "com.myapp.myproc" - yield handler.register(bing, u'com.myapp.myproc99') + yield handler.register(bing, 'com.myapp.myproc99') try: - yield handler.call(u'com.myapp.myproc99') + yield handler.call('com.myapp.myproc99') self.fail("Expected an error") except Exception as e: # XXX should/could we export all the builtin types? @@ -820,11 +818,11 @@ def progress(arg): # see MockTransport, must start with "com.myapp.myproc" yield handler.register( bing, - u'com.myapp.myproc2', + 'com.myapp.myproc2', types.RegisterOptions(details_arg='details'), ) res = yield handler.call( - u'com.myapp.myproc2', + 'com.myapp.myproc2', options=types.CallOptions(on_progress=progress), ) self.assertEqual(42, res) @@ -864,12 +862,12 @@ def progress(arg, something=None): # see MockTransport, must start with "com.myapp.myproc" yield handler.register( bing, - u'com.myapp.myproc2', + 'com.myapp.myproc2', types.RegisterOptions(details_arg='details'), ) res = yield handler.call( - u'com.myapp.myproc2', + 'com.myapp.myproc2', 'arg', options=types.CallOptions(on_progress=progress), key='word', @@ -905,12 +903,12 @@ def progress(): # see MockTransport, must start with "com.myapp.myproc" yield handler.register( bing, - u'com.myapp.myproc2', + 'com.myapp.myproc2', types.RegisterOptions(details_arg='details'), ) res = yield handler.call( - u'com.myapp.myproc2', + 'com.myapp.myproc2', options=types.CallOptions(on_progress=progress), ) self.assertEqual(42, res) @@ -937,12 +935,12 @@ def progress(key=None): # see MockTransport, must start with "com.myapp.myproc" yield handler.register( bing, - u'com.myapp.myproc2', + 'com.myapp.myproc2', types.RegisterOptions(details_arg='details'), ) res = yield handler.call( - u'com.myapp.myproc2', + 'com.myapp.myproc2', options=types.CallOptions(on_progress=progress), ) self.assertEqual(42, res) @@ -958,9 +956,9 @@ def test_call_exception_runtimeerror(self): def raiser(): raise exception - registration0 = yield handler.register(raiser, u"com.myapp.myproc_error") + registration0 = yield handler.register(raiser, "com.myapp.myproc_error") try: - yield handler.call(u'com.myapp.myproc_error') + yield handler.call('com.myapp.myproc_error') self.fail() except Exception as e: self.assertIsInstance(e, ApplicationError) @@ -977,9 +975,9 @@ def test_call_exception_bare(self): def raiser(): raise exception - registration0 = yield handler.register(raiser, u"com.myapp.myproc_error") + registration0 = yield handler.register(raiser, "com.myapp.myproc_error") try: - yield handler.call(u'com.myapp.myproc_error') + yield handler.call('com.myapp.myproc_error') self.fail() except Exception as e: self.assertIsInstance(e, ApplicationError) @@ -988,19 +986,19 @@ def raiser(): # ## variant 1: works # def test_publish1(self): - # d = self.handler.publish(u'de.myapp.topic1') + # d = self.handler.publish('de.myapp.topic1') # self.assertFailure(d, ApplicationError) # ## variant 2: works # @inlineCallbacks # def test_publish2(self): - # yield self.assertFailure(self.handler.publish(u'de.myapp.topic1'), ApplicationError) + # yield self.assertFailure(self.handler.publish('de.myapp.topic1'), ApplicationError) # ## variant 3: does NOT work # @inlineCallbacks # def test_publish3(self): # with self.assertRaises(ApplicationError): - # yield self.handler.publish(u'de.myapp.topic1') + # yield self.handler.publish('de.myapp.topic1') class TestAuthenticator(unittest.TestCase): @@ -1008,13 +1006,13 @@ def test_inconsistent_authids(self): session = Session(mock.Mock()) auth0 = create_authenticator( "wampcra", - authid=u"alice", - secret=u"p4ssw0rd", + authid="alice", + secret="p4ssw0rd", ) auth1 = create_authenticator( "wampcra", - authid=u"bob", - secret=u"password42", + authid="bob", + secret="password42", ) session.add_authenticator(auth0) diff --git a/autobahn/wamp/test/test_protocol_peer.py b/autobahn/wamp/test/test_protocol_peer.py index e8df03f62..9c0e067fb 100644 --- a/autobahn/wamp/test/test_protocol_peer.py +++ b/autobahn/wamp/test/test_protocol_peer.py @@ -24,11 +24,10 @@ # ############################################################################### -from __future__ import absolute_import import os # we need to select a txaio subsystem because we're importing the base -# protocol classes here for testing purposes. "normally" you'd import +# protocol classes here for testing purposes. "normally" yo'd import # from autobahn.twisted.wamp or autobahn.asyncio.wamp explicitly. import txaio if os.environ.get('USE_TWISTED', False): @@ -49,11 +48,11 @@ class TestPeerExceptions(unittest.TestCase): def test_exception_from_message(self): session = protocol.BaseSession() - @wamp.error(u"com.myapp.error1") + @wamp.error("com.myapp.error1") class AppError1(Exception): pass - @wamp.error(u"com.myapp.error2") + @wamp.error("com.myapp.error2") class AppError2(Exception): pass @@ -61,46 +60,46 @@ class AppError2(Exception): session.define(AppError2) # map defined errors to user exceptions - emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1') + emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error1') exc = session._exception_from_message(emsg) self.assertIsInstance(exc, AppError1) self.assertEqual(exc.args, ()) - emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error2') + emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error2') exc = session._exception_from_message(emsg) self.assertIsInstance(exc, AppError2) self.assertEqual(exc.args, ()) # map undefined error to (generic) exception - emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3') + emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error3') exc = session._exception_from_message(emsg) self.assertIsInstance(exc, exception.ApplicationError) - self.assertEqual(exc.error, u'com.myapp.error3') + self.assertEqual(exc.error, 'com.myapp.error3') self.assertEqual(exc.args, ()) self.assertEqual(exc.kwargs, {}) - emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3', args=[1, 2, u'hello']) + emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error3', args=[1, 2, 'hello']) exc = session._exception_from_message(emsg) self.assertIsInstance(exc, exception.ApplicationError) - self.assertEqual(exc.error, u'com.myapp.error3') - self.assertEqual(exc.args, (1, 2, u'hello')) + self.assertEqual(exc.error, 'com.myapp.error3') + self.assertEqual(exc.args, (1, 2, 'hello')) self.assertEqual(exc.kwargs, {}) - emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3', args=[1, 2, u'hello'], kwargs={u'foo': 23, u'bar': u'baz'}) + emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error3', args=[1, 2, 'hello'], kwargs={'foo': 23, 'bar': 'baz'}) exc = session._exception_from_message(emsg) self.assertIsInstance(exc, exception.ApplicationError) - self.assertEqual(exc.error, u'com.myapp.error3') - self.assertEqual(exc.args, (1, 2, u'hello')) - self.assertEqual(exc.kwargs, {u'foo': 23, u'bar': u'baz'}) + self.assertEqual(exc.error, 'com.myapp.error3') + self.assertEqual(exc.args, (1, 2, 'hello')) + self.assertEqual(exc.kwargs, {'foo': 23, 'bar': 'baz'}) def test_message_from_exception(self): session = protocol.BaseSession() - @wamp.error(u"com.myapp.error1") + @wamp.error("com.myapp.error1") class AppError1(Exception): pass - @wamp.error(u"com.myapp.error2") + @wamp.error("com.myapp.error2") class AppError2(Exception): pass diff --git a/autobahn/wamp/test/test_runner.py b/autobahn/wamp/test/test_runner.py index f402da3d5..cefca7314 100644 --- a/autobahn/wamp/test/test_runner.py +++ b/autobahn/wamp/test/test_runner.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import, print_function - import os import unittest from txaio.testutil import replace_loop @@ -81,7 +79,7 @@ def test_connect_error(self, *args): except ImportError: raise unittest.SkipTest('No twisted') - runner = ApplicationRunner(u'ws://localhost:1', u'realm') + runner = ApplicationRunner('ws://localhost:1', 'realm') exception = ConnectionRefusedError("It's a trap!") with patch('twisted.internet.reactor', FakeReactor(exception)) as mockreactor: @@ -92,15 +90,9 @@ def test_connect_error(self, *args): ) self.assertTrue(mockreactor.stop_called) else: - # Asyncio tests. - try: - import asyncio - from unittest.mock import patch, Mock - except ImportError: - # Trollius >= 0.3 was renamed to asyncio - # noinspection PyUnresolvedReferences - import trollius as asyncio - from mock import patch, Mock + import asyncio + from unittest.mock import patch, Mock + from autobahn.asyncio.wamp import ApplicationRunner class TestApplicationRunner(unittest.TestCase): @@ -126,7 +118,7 @@ def test_explicit_SSLContext(self): with patch.object(asyncio, 'get_event_loop', return_value=loop): loop.run_until_complete = Mock(return_value=(Mock(), Mock())) ssl = {} - runner = ApplicationRunner(u'ws://127.0.0.1:8080/ws', u'realm', + runner = ApplicationRunner('ws://127.0.0.1:8080/ws', 'realm', ssl=ssl) runner.run('_unused_') self.assertIs(ssl, loop.create_connection.call_args[1]['ssl']) @@ -140,7 +132,7 @@ def test_omitted_SSLContext_insecure(self): with replace_loop(Mock()) as loop: with patch.object(asyncio, 'get_event_loop', return_value=loop): loop.run_until_complete = Mock(return_value=(Mock(), Mock())) - runner = ApplicationRunner(u'ws://127.0.0.1:8080/ws', u'realm') + runner = ApplicationRunner('ws://127.0.0.1:8080/ws', 'realm') runner.run('_unused_') self.assertIs(False, loop.create_connection.call_args[1]['ssl']) @@ -153,7 +145,7 @@ def test_omitted_SSLContext_secure(self): with replace_loop(Mock()) as loop: with patch.object(asyncio, 'get_event_loop', return_value=loop): loop.run_until_complete = Mock(return_value=(Mock(), Mock())) - runner = ApplicationRunner(u'wss://127.0.0.1:8080/wss', u'realm') + runner = ApplicationRunner('wss://127.0.0.1:8080/wss', 'realm') runner.run(self.fail) self.assertIs(True, loop.create_connection.call_args[1]['ssl']) @@ -164,7 +156,7 @@ def test_conflict_SSL_True_with_ws_url(self): ''' with replace_loop(Mock()) as loop: loop.run_until_complete = Mock(return_value=(Mock(), Mock())) - runner = ApplicationRunner(u'ws://127.0.0.1:8080/wss', u'realm', + runner = ApplicationRunner('ws://127.0.0.1:8080/wss', 'realm', ssl=True) error = (r'^ssl argument value passed to ApplicationRunner ' r'conflicts with the "ws:" prefix of the url ' @@ -196,7 +188,7 @@ def test_conflict_SSLContext_with_ws_url(self): with replace_loop(Mock()) as loop: loop.run_until_complete = Mock(return_value=(Mock(), Mock())) - runner = ApplicationRunner(u'ws://127.0.0.1:8080/wss', u'realm', + runner = ApplicationRunner('ws://127.0.0.1:8080/wss', 'realm', ssl=context) error = (r'^ssl argument value passed to ApplicationRunner ' r'conflicts with the "ws:" prefix of the url ' diff --git a/autobahn/wamp/test/test_serializer.py b/autobahn/wamp/test/test_serializer.py index ce2848d10..65543939f 100644 --- a/autobahn/wamp/test/test_serializer.py +++ b/autobahn/wamp/test/test_serializer.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os import unittest @@ -42,47 +40,47 @@ def generate_test_messages(): This list of WAMP message does not contain any binary app payloads! """ msgs = [ - message.Hello(u"realm1", {u'subscriber': role.RoleSubscriberFeatures()}), + message.Hello("realm1", {'subscriber': role.RoleSubscriberFeatures()}), message.Goodbye(), message.Yield(123456), - message.Yield(123456, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}), - message.Yield(123456, args=[u'hello']), + message.Yield(123456, args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}), + message.Yield(123456, args=['hello']), message.Yield(123456, progress=True), message.Interrupt(123456), message.Interrupt(123456, mode=message.Interrupt.KILL), message.Invocation(123456, 789123), - message.Invocation(123456, 789123, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}), + message.Invocation(123456, 789123, args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}), message.Invocation(123456, 789123, timeout=10000), message.Result(123456), - message.Result(123456, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}), + message.Result(123456, args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}), message.Result(123456, progress=True), message.Cancel(123456), message.Cancel(123456, mode=message.Cancel.KILL), - message.Call(123456, u'com.myapp.procedure1'), - message.Call(123456, u'com.myapp.procedure1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}), - message.Call(123456, u'com.myapp.procedure1', timeout=10000), + message.Call(123456, 'com.myapp.procedure1'), + message.Call(123456, 'com.myapp.procedure1', args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}), + message.Call(123456, 'com.myapp.procedure1', timeout=10000), message.Unregistered(123456), message.Unregister(123456, 789123), message.Registered(123456, 789123), - message.Register(123456, u'com.myapp.procedure1'), - message.Register(123456, u'com.myapp.procedure1', match=u'prefix'), - message.Register(123456, u'com.myapp.procedure1', invoke=u'roundrobin'), + message.Register(123456, 'com.myapp.procedure1'), + message.Register(123456, 'com.myapp.procedure1', match='prefix'), + message.Register(123456, 'com.myapp.procedure1', invoke='roundrobin'), message.Event(123456, 789123), - message.Event(123456, 789123, args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}), + message.Event(123456, 789123, args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}), message.Event(123456, 789123, publisher=300), message.Published(123456, 789123), - message.Publish(123456, u'com.myapp.topic1'), - message.Publish(123456, u'com.myapp.topic1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}), - message.Publish(123456, u'com.myapp.topic1', exclude_me=False, exclude=[300], eligible=[100, 200, 300]), + message.Publish(123456, 'com.myapp.topic1'), + message.Publish(123456, 'com.myapp.topic1', args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}), + message.Publish(123456, 'com.myapp.topic1', exclude_me=False, exclude=[300], eligible=[100, 200, 300]), message.Unsubscribed(123456), message.Unsubscribe(123456, 789123), message.Subscribed(123456, 789123), - message.Subscribe(123456, u'com.myapp.topic1'), - message.Subscribe(123456, u'com.myapp.topic1', match=message.Subscribe.MATCH_PREFIX), - message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1'), - message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1', args=[1, 2, 3], kwargs={u'foo': 23, u'bar': u'hello'}), - message.Call(123456, u'com.myapp.\u4f60\u597d\u4e16\u754c', args=[1, 2, 3]), - message.Result(123456, args=[1, 2, 3], kwargs={u'en': u'Hello World', u'jp': u'\u3053\u3093\u306b\u3061\u306f\u4e16\u754c'}) + message.Subscribe(123456, 'com.myapp.topic1'), + message.Subscribe(123456, 'com.myapp.topic1', match=message.Subscribe.MATCH_PREFIX), + message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error1'), + message.Error(message.Call.MESSAGE_TYPE, 123456, 'com.myapp.error1', args=[1, 2, 3], kwargs={'foo': 23, 'bar': 'hello'}), + message.Call(123456, 'com.myapp.\u4f60\u597d\u4e16\u754c', args=[1, 2, 3]), + message.Result(123456, args=[1, 2, 3], kwargs={'en': 'Hello World', 'jp': '\u3053\u3093\u306b\u3061\u306f\u4e16\u754c'}) ] return [(False, msg) for msg in msgs] @@ -106,7 +104,7 @@ def generate_test_messages_binary(): os.urandom(512), os.urandom(1024)]: msgs.append(message.Event(123456, 789123, args=[binary])) - msgs.append(message.Event(123456, 789123, args=[binary], kwargs={u'foo': binary})) + msgs.append(message.Event(123456, 789123, args=[binary], kwargs={'foo': binary})) return [(True, msg) for msg in msgs] @@ -140,13 +138,13 @@ def test_basic(self): message.Event(123456, 789123, args=[1, 2, 3], - kwargs={u'foo': 23, u'bar': u'hello'}, + kwargs={'foo': 23, 'bar': 'hello'}, publisher=666, retained=True), message.Publish(123456, 'com.example.topic1', args=[1, 2, 3], - kwargs={u'foo': 23, u'bar': u'hello'}, + kwargs={'foo': 23, 'bar': 'hello'}, retain=True) ] @@ -183,8 +181,8 @@ def test_deep_equal_msg(self): Test deep object equality assert (because I am paranoid). """ v = os.urandom(10) - o1 = [1, 2, {u'foo': u'bar', u'bar': v, u'baz': [9, 3, 2], u'goo': {u'moo': [1, 2, 3]}}, v] - o2 = [1, 2, {u'goo': {u'moo': [1, 2, 3]}, u'bar': v, u'baz': [9, 3, 2], u'foo': u'bar'}, v] + o1 = [1, 2, {'foo': 'bar', 'bar': v, 'baz': [9, 3, 2], 'goo': {'moo': [1, 2, 3]}}, v] + o2 = [1, 2, {'goo': {'moo': [1, 2, 3]}, 'bar': v, 'baz': [9, 3, 2], 'foo': 'bar'}, v] self.assertEqual(o1, o2) def test_roundtrip_msg(self): diff --git a/autobahn/wamp/test/test_uri_pattern.py b/autobahn/wamp/test/test_uri_pattern.py index bb189dbb2..bc6906e0a 100644 --- a/autobahn/wamp/test/test_uri_pattern.py +++ b/autobahn/wamp/test/test_uri_pattern.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn import wamp from autobahn.wamp.uri import Pattern, RegisterOptions, SubscribeOptions @@ -35,52 +33,52 @@ class TestUris(unittest.TestCase): def test_invalid_uris(self): - for u in [u"", - u"com.myapp..update", - u"com.myapp.<123:int>.update", - u"com.myapp.<:product>.update", - u"com.myapp..update", - u"com.myapp..update", + for u in ["", + "com.myapp..update", + "com.myapp.<123:int>.update", + "com.myapp.<:product>.update", + "com.myapp..update", + "com.myapp..update", ]: self.assertRaises(Exception, Pattern, u, Pattern.URI_TARGET_ENDPOINT) def test_valid_uris(self): - for u in [u"com.myapp.proc1", - u"123", - u"com.myapp..update", - u"com.myapp...list" - u"com.myapp.something..update" + for u in ["com.myapp.proc1", + "123", + "com.myapp..update", + "com.myapp...list" + "com.myapp.something..update" ]: p = Pattern(u, Pattern.URI_TARGET_ENDPOINT) self.assertIsInstance(p, Pattern) def test_parse_uris(self): tests = [ - (u"com.myapp..update", [ - (u"com.myapp.0.update", {u'product': 0}), - (u"com.myapp.123456.update", {u'product': 123456}), - (u"com.myapp.aaa.update", None), - (u"com.myapp..update", None), - (u"com.myapp.0.delete", None), + ("com.myapp..update", [ + ("com.myapp.0.update", {'product': 0}), + ("com.myapp.123456.update", {'product': 123456}), + ("com.myapp.aaa.update", None), + ("com.myapp..update", None), + ("com.myapp.0.delete", None), ] ), - (u"com.myapp..update", [ - (u"com.myapp.box.update", {u'product': u'box'}), - (u"com.myapp.123456.update", {u'product': u'123456'}), - (u"com.myapp..update", None), + ("com.myapp..update", [ + ("com.myapp.box.update", {'product': 'box'}), + ("com.myapp.123456.update", {'product': '123456'}), + ("com.myapp..update", None), ] ), - (u"com.myapp..update", [ - (u"com.myapp.0.update", {u'product': u'0'}), - (u"com.myapp.abc.update", {u'product': u'abc'}), - (u"com.myapp..update", None), + ("com.myapp..update", [ + ("com.myapp.0.update", {'product': '0'}), + ("com.myapp.abc.update", {'product': 'abc'}), + ("com.myapp..update", None), ] ), - (u"com.myapp...list", [ - (u"com.myapp.cosmetic.shampoo.list", {u'category': u'cosmetic', u'subcategory': u'shampoo'}), - (u"com.myapp...list", None), - (u"com.myapp.cosmetic..list", None), - (u"com.myapp..shampoo.list", None), + ("com.myapp...list", [ + ("com.myapp.cosmetic.shampoo.list", {'category': 'cosmetic', 'subcategory': 'shampoo'}), + ("com.myapp...list", None), + ("com.myapp.cosmetic..list", None), + ("com.myapp..shampoo.list", None), ] ) ] @@ -100,7 +98,7 @@ class TestDecorators(unittest.TestCase): def test_decorate_endpoint(self): - @wamp.register(u"com.calculator.square") + @wamp.register("com.calculator.square") def square(_): """Do nothing.""" @@ -111,10 +109,10 @@ def square(_): self.assertTrue(square._wampuris[0].is_endpoint()) self.assertFalse(square._wampuris[0].is_handler()) self.assertFalse(square._wampuris[0].is_exception()) - self.assertEqual(square._wampuris[0].uri(), u"com.calculator.square") + self.assertEqual(square._wampuris[0].uri(), "com.calculator.square") self.assertEqual(square._wampuris[0]._type, Pattern.URI_TYPE_EXACT) - @wamp.register(u"com.myapp.product..update") + @wamp.register("com.myapp.product..update") def update_product(product=None, label=None): """Do nothing.""" @@ -125,10 +123,10 @@ def update_product(product=None, label=None): self.assertTrue(update_product._wampuris[0].is_endpoint()) self.assertFalse(update_product._wampuris[0].is_handler()) self.assertFalse(update_product._wampuris[0].is_exception()) - self.assertEqual(update_product._wampuris[0].uri(), u"com.myapp.product..update") + self.assertEqual(update_product._wampuris[0].uri(), "com.myapp.product..update") self.assertEqual(update_product._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) - @wamp.register(u"com.myapp...update") + @wamp.register("com.myapp...update") def update(category=None, cid=None): """Do nothing.""" @@ -139,11 +137,11 @@ def update(category=None, cid=None): self.assertTrue(update._wampuris[0].is_endpoint()) self.assertFalse(update._wampuris[0].is_handler()) self.assertFalse(update._wampuris[0].is_exception()) - self.assertEqual(update._wampuris[0].uri(), u"com.myapp...update") + self.assertEqual(update._wampuris[0].uri(), "com.myapp...update") self.assertEqual(update._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) - @wamp.register(u"com.myapp.circle.", - RegisterOptions(match=u"wildcard", details_arg="details")) + @wamp.register("com.myapp.circle.", + RegisterOptions(match="wildcard", details_arg="details")) def circle(name=None, details=None): """ Do nothing. """ @@ -152,16 +150,16 @@ def circle(name=None, details=None): self.assertEqual(len(circle._wampuris), 1) self.assertIsInstance(circle._wampuris[0], Pattern) self.assertIsInstance(circle._wampuris[0].options, RegisterOptions) - self.assertEqual(circle._wampuris[0].options.match, u"wildcard") + self.assertEqual(circle._wampuris[0].options.match, "wildcard") self.assertEqual(circle._wampuris[0].options.details_arg, "details") self.assertTrue(circle._wampuris[0].is_endpoint()) self.assertFalse(circle._wampuris[0].is_handler()) self.assertFalse(circle._wampuris[0].is_exception()) - self.assertEqual(circle._wampuris[0].uri(), u"com.myapp.circle.") + self.assertEqual(circle._wampuris[0].uri(), "com.myapp.circle.") self.assertEqual(circle._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) - @wamp.register(u"com.myapp.something..update", - RegisterOptions(match=u"wildcard", details_arg="details")) + @wamp.register("com.myapp.something..update", + RegisterOptions(match="wildcard", details_arg="details")) def something(dynamic=None, details=None): """ Do nothing. """ self.assertTrue(hasattr(something, '_wampuris')) @@ -169,17 +167,17 @@ def something(dynamic=None, details=None): self.assertEqual(len(something._wampuris), 1) self.assertIsInstance(something._wampuris[0], Pattern) self.assertIsInstance(something._wampuris[0].options, RegisterOptions) - self.assertEqual(something._wampuris[0].options.match, u"wildcard") + self.assertEqual(something._wampuris[0].options.match, "wildcard") self.assertEqual(something._wampuris[0].options.details_arg, "details") self.assertTrue(something._wampuris[0].is_endpoint()) self.assertFalse(something._wampuris[0].is_handler()) self.assertFalse(something._wampuris[0].is_exception()) - self.assertEqual(something._wampuris[0].uri(), u"com.myapp.something..update") + self.assertEqual(something._wampuris[0].uri(), "com.myapp.something..update") self.assertEqual(something._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) def test_decorate_handler(self): - @wamp.subscribe(u"com.myapp.on_shutdown") + @wamp.subscribe("com.myapp.on_shutdown") def on_shutdown(): """Do nothing.""" @@ -190,10 +188,10 @@ def on_shutdown(): self.assertFalse(on_shutdown._wampuris[0].is_endpoint()) self.assertTrue(on_shutdown._wampuris[0].is_handler()) self.assertFalse(on_shutdown._wampuris[0].is_exception()) - self.assertEqual(on_shutdown._wampuris[0].uri(), u"com.myapp.on_shutdown") + self.assertEqual(on_shutdown._wampuris[0].uri(), "com.myapp.on_shutdown") self.assertEqual(on_shutdown._wampuris[0]._type, Pattern.URI_TYPE_EXACT) - @wamp.subscribe(u"com.myapp.product..on_update") + @wamp.subscribe("com.myapp.product..on_update") def on_product_update(product=None, label=None): """Do nothing.""" @@ -204,10 +202,10 @@ def on_product_update(product=None, label=None): self.assertFalse(on_product_update._wampuris[0].is_endpoint()) self.assertTrue(on_product_update._wampuris[0].is_handler()) self.assertFalse(on_product_update._wampuris[0].is_exception()) - self.assertEqual(on_product_update._wampuris[0].uri(), u"com.myapp.product..on_update") + self.assertEqual(on_product_update._wampuris[0].uri(), "com.myapp.product..on_update") self.assertEqual(on_product_update._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) - @wamp.subscribe(u"com.myapp...on_update") + @wamp.subscribe("com.myapp...on_update") def on_update(category=None, cid=None, label=None): """Do nothing.""" @@ -218,11 +216,11 @@ def on_update(category=None, cid=None, label=None): self.assertFalse(on_update._wampuris[0].is_endpoint()) self.assertTrue(on_update._wampuris[0].is_handler()) self.assertFalse(on_update._wampuris[0].is_exception()) - self.assertEqual(on_update._wampuris[0].uri(), u"com.myapp...on_update") + self.assertEqual(on_update._wampuris[0].uri(), "com.myapp...on_update") self.assertEqual(on_update._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) - @wamp.subscribe(u"com.myapp.on.", - SubscribeOptions(match=u"wildcard", details_arg="details")) + @wamp.subscribe("com.myapp.on.", + SubscribeOptions(match="wildcard", details_arg="details")) def on_event(event=None, details=None): """ Do nothing. """ @@ -231,17 +229,17 @@ def on_event(event=None, details=None): self.assertEqual(len(on_event._wampuris), 1) self.assertIsInstance(on_event._wampuris[0], Pattern) self.assertIsInstance(on_event._wampuris[0].options, SubscribeOptions) - self.assertEqual(on_event._wampuris[0].options.match, u"wildcard") + self.assertEqual(on_event._wampuris[0].options.match, "wildcard") self.assertEqual(on_event._wampuris[0].options.details_arg, "details") self.assertFalse(on_event._wampuris[0].is_endpoint()) self.assertTrue(on_event._wampuris[0].is_handler()) self.assertFalse(on_event._wampuris[0].is_exception()) - self.assertEqual(on_event._wampuris[0].uri(), u"com.myapp.on.") + self.assertEqual(on_event._wampuris[0].uri(), "com.myapp.on.") self.assertEqual(on_event._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) def test_decorate_exception(self): - @wamp.error(u"com.myapp.error") + @wamp.error("com.myapp.error") class AppError(Exception): """Do nothing.""" @@ -252,10 +250,10 @@ class AppError(Exception): self.assertFalse(AppError._wampuris[0].is_endpoint()) self.assertFalse(AppError._wampuris[0].is_handler()) self.assertTrue(AppError._wampuris[0].is_exception()) - self.assertEqual(AppError._wampuris[0].uri(), u"com.myapp.error") + self.assertEqual(AppError._wampuris[0].uri(), "com.myapp.error") self.assertEqual(AppError._wampuris[0]._type, Pattern.URI_TYPE_EXACT) - @wamp.error(u"com.myapp.product..product_inactive") + @wamp.error("com.myapp.product..product_inactive") class ProductInactiveError(Exception): """Do nothing.""" @@ -266,10 +264,10 @@ class ProductInactiveError(Exception): self.assertFalse(ProductInactiveError._wampuris[0].is_endpoint()) self.assertFalse(ProductInactiveError._wampuris[0].is_handler()) self.assertTrue(ProductInactiveError._wampuris[0].is_exception()) - self.assertEqual(ProductInactiveError._wampuris[0].uri(), u"com.myapp.product..product_inactive") + self.assertEqual(ProductInactiveError._wampuris[0].uri(), "com.myapp.product..product_inactive") self.assertEqual(ProductInactiveError._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) - @wamp.error(u"com.myapp...inactive") + @wamp.error("com.myapp...inactive") class ObjectInactiveError(Exception): """Do nothing.""" @@ -280,62 +278,62 @@ class ObjectInactiveError(Exception): self.assertFalse(ObjectInactiveError._wampuris[0].is_endpoint()) self.assertFalse(ObjectInactiveError._wampuris[0].is_handler()) self.assertTrue(ObjectInactiveError._wampuris[0].is_exception()) - self.assertEqual(ObjectInactiveError._wampuris[0].uri(), u"com.myapp...inactive") + self.assertEqual(ObjectInactiveError._wampuris[0].uri(), "com.myapp...inactive") self.assertEqual(ObjectInactiveError._wampuris[0]._type, Pattern.URI_TYPE_WILDCARD) def test_match_decorated_endpoint(self): - @wamp.register(u"com.calculator.square") + @wamp.register("com.calculator.square") def square(x): return x - args, kwargs = square._wampuris[0].match(u"com.calculator.square") + args, kwargs = square._wampuris[0].match("com.calculator.square") self.assertEqual(square(666, **kwargs), 666) - @wamp.register(u"com.myapp.product..update") + @wamp.register("com.myapp.product..update") def update_product(product=None, label=None): return product, label - args, kwargs = update_product._wampuris[0].match(u"com.myapp.product.123456.update") + args, kwargs = update_product._wampuris[0].match("com.myapp.product.123456.update") kwargs['label'] = "foobar" self.assertEqual(update_product(**kwargs), (123456, "foobar")) - @wamp.register(u"com.myapp...update") + @wamp.register("com.myapp...update") def update(category=None, cid=None, label=None): return category, cid, label - args, kwargs = update._wampuris[0].match(u"com.myapp.product.123456.update") + args, kwargs = update._wampuris[0].match("com.myapp.product.123456.update") kwargs['label'] = "foobar" self.assertEqual(update(**kwargs), ("product", 123456, "foobar")) def test_match_decorated_handler(self): - @wamp.subscribe(u"com.myapp.on_shutdown") + @wamp.subscribe("com.myapp.on_shutdown") def on_shutdown(): pass - args, kwargs = on_shutdown._wampuris[0].match(u"com.myapp.on_shutdown") + args, kwargs = on_shutdown._wampuris[0].match("com.myapp.on_shutdown") self.assertEqual(on_shutdown(**kwargs), None) - @wamp.subscribe(u"com.myapp.product..on_update") + @wamp.subscribe("com.myapp.product..on_update") def on_product_update(product=None, label=None): return product, label - args, kwargs = on_product_update._wampuris[0].match(u"com.myapp.product.123456.on_update") + args, kwargs = on_product_update._wampuris[0].match("com.myapp.product.123456.on_update") kwargs['label'] = "foobar" self.assertEqual(on_product_update(**kwargs), (123456, "foobar")) - @wamp.subscribe(u"com.myapp...on_update") + @wamp.subscribe("com.myapp...on_update") def on_update(category=None, cid=None, label=None): return category, cid, label - args, kwargs = on_update._wampuris[0].match(u"com.myapp.product.123456.on_update") + args, kwargs = on_update._wampuris[0].match("com.myapp.product.123456.on_update") kwargs['label'] = "foobar" self.assertEqual(on_update(**kwargs), ("product", 123456, "foobar")) def test_match_decorated_exception(self): - @wamp.error(u"com.myapp.error") + @wamp.error("com.myapp.error") class AppError(Exception): def __init__(self, msg): @@ -345,11 +343,11 @@ def __eq__(self, other): return self.__class__ == other.__class__ and \ self.args == other.args - args, kwargs = AppError._wampuris[0].match(u"com.myapp.error") + args, kwargs = AppError._wampuris[0].match("com.myapp.error") # noinspection PyArgumentList - self.assertEqual(AppError(u"fuck", **kwargs), AppError(u"fuck")) + self.assertEqual(AppError("fuck", **kwargs), AppError("fuck")) - @wamp.error(u"com.myapp.product..product_inactive") + @wamp.error("com.myapp.product..product_inactive") class ProductInactiveError(Exception): def __init__(self, msg, product=None): @@ -361,10 +359,10 @@ def __eq__(self, other): self.args == other.args and \ self.product == other.product - args, kwargs = ProductInactiveError._wampuris[0].match(u"com.myapp.product.123456.product_inactive") + args, kwargs = ProductInactiveError._wampuris[0].match("com.myapp.product.123456.product_inactive") self.assertEqual(ProductInactiveError("fuck", **kwargs), ProductInactiveError("fuck", 123456)) - @wamp.error(u"com.myapp...inactive") + @wamp.error("com.myapp...inactive") class ObjectInactiveError(Exception): def __init__(self, msg, category=None, product=None): @@ -378,7 +376,7 @@ def __eq__(self, other): self.category == other.category and \ self.product == other.product - args, kwargs = ObjectInactiveError._wampuris[0].match(u"com.myapp.product.123456.inactive") + args, kwargs = ObjectInactiveError._wampuris[0].match("com.myapp.product.123456.inactive") self.assertEqual(ObjectInactiveError("fuck", **kwargs), ObjectInactiveError("fuck", "product", 123456)) @@ -453,7 +451,7 @@ def test_decorate_exception_non_exception(self): def test(): # noinspection PyUnusedLocal - @wamp.error(u"com.test.error") + @wamp.error("com.test.error") class Foo(object): pass @@ -462,8 +460,8 @@ class Foo(object): def test_decorate_endpoint_multiple(self): # noinspection PyUnusedLocal - @wamp.register(u"com.oldapp.oldproc") - @wamp.register(u"com.calculator.square") + @wamp.register("com.oldapp.oldproc") + @wamp.register("com.calculator.square") def square(x): """Do nothing.""" @@ -478,21 +476,21 @@ def square(x): self.assertFalse(square._wampuris[i].is_exception()) self.assertEqual(square._wampuris[i]._type, Pattern.URI_TYPE_EXACT) - self.assertEqual(square._wampuris[0].uri(), u"com.calculator.square") - self.assertEqual(square._wampuris[1].uri(), u"com.oldapp.oldproc") + self.assertEqual(square._wampuris[0].uri(), "com.calculator.square") + self.assertEqual(square._wampuris[1].uri(), "com.oldapp.oldproc") def test_marshal_decorated_exception(self): - @wamp.error(u"com.myapp.error") + @wamp.error("com.myapp.error") class AppError(Exception): pass try: raise AppError("fuck") except Exception as e: - self.assertEqual(e._wampuris[0].uri(), u"com.myapp.error") + self.assertEqual(e._wampuris[0].uri(), "com.myapp.error") - @wamp.error(u"com.myapp.product..product_inactive") + @wamp.error("com.myapp.product..product_inactive") class ProductInactiveError(Exception): def __init__(self, msg, product=None): @@ -502,7 +500,7 @@ def __init__(self, msg, product=None): try: raise ProductInactiveError("fuck", 123456) except Exception as e: - self.assertEqual(e._wampuris[0].uri(), u"com.myapp.product..product_inactive") + self.assertEqual(e._wampuris[0].uri(), "com.myapp.product..product_inactive") session = MockSession() session.define(AppError) @@ -518,44 +516,44 @@ class AppError(Exception): # an URI to be provided self.assertRaises(Exception, session.define, AppError) - session.define(AppError, u"com.myapp.error") + session.define(AppError, "com.myapp.error") - exc = session.map_error(u"com.myapp.error") + exc = session.map_error("com.myapp.error") self.assertIsInstance(exc, AppError) def test_define_exception_decorated(self): session = MockSession() - @wamp.error(u"com.myapp.error") + @wamp.error("com.myapp.error") class AppError(Exception): pass # when defining a decorated exception # an URI must not be provided - self.assertRaises(Exception, session.define, AppError, u"com.myapp.error") + self.assertRaises(Exception, session.define, AppError, "com.myapp.error") session.define(AppError) - exc = session.map_error(u"com.myapp.error") + exc = session.map_error("com.myapp.error") self.assertIsInstance(exc, AppError) def test_map_exception_undefined(self): session = MockSession() - exc = session.map_error(u"com.myapp.error") + exc = session.map_error("com.myapp.error") self.assertIsInstance(exc, Exception) def test_map_exception_args(self): session = MockSession() - @wamp.error(u"com.myapp.error") + @wamp.error("com.myapp.error") class AppError(Exception): pass - @wamp.error(u"com.myapp.error.product_inactive") + @wamp.error("com.myapp.error.product_inactive") class ProductInactiveError(Exception): def __init__(self, product=None): self.product = product @@ -565,13 +563,13 @@ def __init__(self, product=None): session.define(ProductInactiveError) for test in [ - # (u"com.myapp.foo.error", [], {}, KwException), - (u"com.myapp.error", [], {}, AppError), - (u"com.myapp.error", ["you are doing it wrong"], {}, AppError), - (u"com.myapp.error", ["you are doing it wrong", 1, 2, 3], {}, AppError), + # ("com.myapp.foo.error", [], {}, KwException), + ("com.myapp.error", [], {}, AppError), + ("com.myapp.error", ["you are doing it wrong"], {}, AppError), + ("com.myapp.error", ["you are doing it wrong", 1, 2, 3], {}, AppError), - (u"com.myapp.error.product_inactive", [], {}, ProductInactiveError), - (u"com.myapp.error.product_inactive", [], {"product": 123456}, ProductInactiveError), + ("com.myapp.error.product_inactive", [], {}, ProductInactiveError), + ("com.myapp.error.product_inactive", [], {"product": 123456}, ProductInactiveError), ]: error, args, kwargs, ecls = test exc = session.map_error(error, args, kwargs) diff --git a/autobahn/wamp/test/test_user_handler_errors.py b/autobahn/wamp/test/test_user_handler_errors.py index 35570badc..f7294b77d 100644 --- a/autobahn/wamp/test/test_user_handler_errors.py +++ b/autobahn/wamp/test/test_user_handler_errors.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os if os.environ.get('USE_TWISTED', False): @@ -55,7 +53,7 @@ class MockApplicationSession(ApplicationSession): def __init__(self, *args, **kw): ApplicationSession.__init__(self, *args, **kw) self.errors = [] - self._realm = u'dummy' + self._realm = 'dummy' self._transport = MockTransport() def onUserError(self, e, msg): @@ -90,7 +88,7 @@ def create_mock_welcome(): return message.Welcome( 1234, { - u'broker': role.RoleBrokerFeatures(), + 'broker': role.RoleBrokerFeatures(), }, ) @@ -142,7 +140,7 @@ def test_on_leave(self): session = MockApplicationSession() exception = RuntimeError("boom") session.onLeave = exception_raiser(exception) - msg = message.Abort(u"testing") + msg = message.Abort("testing") # we haven't done anything, so this is "abort before we've # connected" @@ -156,7 +154,7 @@ def test_on_leave_deferred(self): session = MockApplicationSession() exception = RuntimeError("boom") session.onLeave = async_exception_raiser(exception) - msg = message.Abort(u"testing") + msg = message.Abort("testing") # we haven't done anything, so this is "abort before we've # connected" @@ -212,7 +210,7 @@ def test_on_leave_after_bad_challenge(self): session.onChallenge = exception_raiser(exception) # make a challenge (which will fail, and then the # subsequent onLeave will also fail) - msg = message.Challenge(u"foo") + msg = message.Challenge("foo") session.onMessage(msg) self.assertEqual(2, len(session.errors)) @@ -250,7 +248,7 @@ def test_on_challenge(self): session = MockApplicationSession() exception = RuntimeError("such challenge") session.onChallenge = exception_raiser(exception) - msg = message.Challenge(u"foo") + msg = message.Challenge("foo") # execute session.onMessage(msg) @@ -269,7 +267,7 @@ def test_on_challenge_deferred(self): session = MockApplicationSession() exception = RuntimeError("such challenge") session.onChallenge = async_exception_raiser(exception) - msg = message.Challenge(u"foo") + msg = message.Challenge("foo") # execute session.onMessage(msg) diff --git a/autobahn/wamp/test/test_websocket.py b/autobahn/wamp/test/test_websocket.py index 0a1ecfafb..9aa5276bb 100644 --- a/autobahn/wamp/test/test_websocket.py +++ b/autobahn/wamp/test/test_websocket.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import os if os.environ.get('USE_TWISTED', False): diff --git a/autobahn/wamp/types.py b/autobahn/wamp/types.py index 7368ccc2f..b61009c3c 100644 --- a/autobahn/wamp/types.py +++ b/autobahn/wamp/types.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.util import public @@ -116,7 +114,7 @@ def __init__(self, realm=None, extra=None, keyring=None, controller=None, shared self.runner = runner def __str__(self): - return u"ComponentConfig(realm=<{}>, extra={}, keyring={}, controller={}, shared={}, runner={})".format(self.realm, self.extra, self.keyring, self.controller, self.shared, self.runner) + return "ComponentConfig(realm=<{}>, extra={}, keyring={}, controller={}, shared={}, runner={})".format(self.realm, self.extra, self.keyring, self.controller, self.shared, self.runner) @public @@ -177,7 +175,7 @@ def __init__(self, realm=None, authid=None, authrole=None, authmethod=None, auth self.authextra = authextra def __str__(self): - return u"Accept(realm=<{}>, authid=<{}>, authrole=<{}>, authmethod={}, authprovider={}, authextra={})".format(self.realm, self.authid, self.authrole, self.authmethod, self.authprovider, self.authextra) + return "Accept(realm=<{}>, authid=<{}>, authrole=<{}>, authmethod={}, authprovider={}, authextra={})".format(self.realm, self.authid, self.authrole, self.authmethod, self.authprovider, self.authextra) @public @@ -191,10 +189,10 @@ class Deny(HelloReturn): 'message', ) - def __init__(self, reason=u'wamp.error.not_authorized', message=None): + def __init__(self, reason='wamp.error.not_authorized', message=None): """ - :param reason: The reason of denying the authentication (an URI, e.g. ``u'wamp.error.not_authorized'``) + :param reason: The reason of denying the authentication (an URI, e.g. ``'wamp.error.not_authorized'``) :type reason: str :param message: A human readable message (for logging purposes). @@ -207,7 +205,7 @@ def __init__(self, reason=u'wamp.error.not_authorized', message=None): self.message = message def __str__(self): - return u"Deny(reason=<{}>, message='{}')".format(self.reason, self.message) + return "Deny(reason=<{}>, message='{}')".format(self.reason, self.message) @public @@ -238,7 +236,7 @@ def __init__(self, method, extra=None): self.extra = extra or {} def __str__(self): - return u"Challenge(method={}, extra={})".format(self.method, self.extra) + return "Challenge(method={}, extra={})".format(self.method, self.extra) @public @@ -316,7 +314,7 @@ def __init__(self, realm=None, authmethods=None, authid=None, authrole=None, aut self.resume_token = resume_token def __str__(self): - return u"HelloDetails(realm=<{}>, authmethods={}, authid=<{}>, authrole=<{}>, authextra={}, session_roles={}, pending_session={}, resumable={}, resume_session={}, resume_token={})".format(self.realm, self.authmethods, self.authid, self.authrole, self.authextra, self.session_roles, self.pending_session, self.resumable, self.resume_session, self.resume_token) + return "HelloDetails(realm=<{}>, authmethods={}, authid=<{}>, authrole=<{}>, authextra={}, session_roles={}, pending_session={}, resumable={}, resume_session={}, resume_token={})".format(self.realm, self.authmethods, self.authid, self.authrole, self.authextra, self.session_roles, self.pending_session, self.resumable, self.resume_session, self.resume_token) @public @@ -386,22 +384,22 @@ def __init__(self, realm, session, authid=None, authrole=None, authmethod=None, def marshal(self): obj = { - u'realm': self.realm, - u'session': self.session, - u'authid': self.authid, - u'authrole': self.authrole, - u'authmethod': self.authmethod, - u'authprovider': self.authprovider, - u'authextra': self.authextra, - u'serializer': self.serializer, - u'resumed': self.resumed, - u'resumable': self.resumable, - u'resume_token': self.resume_token + 'realm': self.realm, + 'session': self.session, + 'authid': self.authid, + 'authrole': self.authrole, + 'authmethod': self.authmethod, + 'authprovider': self.authprovider, + 'authextra': self.authextra, + 'serializer': self.serializer, + 'resumed': self.resumed, + 'resumable': self.resumable, + 'resume_token': self.resume_token } return obj def __str__(self): - return u""" + return """ SessionDetails(realm=<{}>, session={}, authid=<{}>, @@ -458,13 +456,13 @@ def __init__(self, session=None, authid=None, authrole=None): self.authrole = authrole def __str__(self): - return u"SessionIdent(session={}, authid={}, authrole={})".format(self.session, self.authid, self.authrole) + return "SessionIdent(session={}, authid={}, authrole={})".format(self.session, self.authid, self.authrole) def marshal(self): obj = { - u'session': self.session, - u'authid': self.authid, - u'authrole': self.authrole, + 'session': self.session, + 'authid': self.authid, + 'authrole': self.authrole, } return obj @@ -526,8 +524,8 @@ class CloseDetails(object): .. seealso:: :func:`autobahn.wamp.interfaces.ISession.onLeave` """ - REASON_DEFAULT = u"wamp.close.normal" - REASON_TRANSPORT_LOST = u"wamp.close.transport_lost" + REASON_DEFAULT = "wamp.close.normal" + REASON_TRANSPORT_LOST = "wamp.close.transport_lost" __slots__ = ( 'reason', @@ -551,13 +549,13 @@ def __init__(self, reason=None, message=None): def marshal(self): obj = { - u'reason': self.reason, - u'message': self.message + 'reason': self.reason, + 'message': self.message } return obj def __str__(self): - return u"CloseDetails(reason=<{}>, message='{}')".format(self.reason, self.message) + return "CloseDetails(reason=<{}>, message='{}')".format(self.reason, self.message) @public @@ -598,7 +596,7 @@ def __init__(self, match=None, details=None, details_arg=None, forward_for=None, :param get_retained: Whether the client wants the retained message we may have along with the subscription. :type get_retained: bool or None """ - assert(match is None or (type(match) == str and match in [u'exact', u'prefix', u'wildcard'])) + assert(match is None or (type(match) == str and match in ['exact', 'prefix', 'wildcard'])) assert(details is None or (type(details) == bool and details_arg is None)) assert(details_arg is None or type(details_arg) == str) # yes, "str" is correct here, since this is about Python identifiers! assert(get_retained is None or type(get_retained) is bool) @@ -635,18 +633,18 @@ def message_attr(self): options = {} if self.match is not None: - options[u'match'] = self.match + options['match'] = self.match if self.get_retained is not None: - options[u'get_retained'] = self.get_retained + options['get_retained'] = self.get_retained if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return options def __str__(self): - return u"SubscribeOptions(match={}, details={}, details_arg={}, get_retained={}, forward_for={})".format(self.match, self.details, self.details_arg, self.get_retained, self.forward_for) + return "SubscribeOptions(match={}, details={}, details_arg={}, get_retained={}, forward_for={})".format(self.match, self.details, self.details_arg, self.get_retained, self.forward_for) @public @@ -698,7 +696,7 @@ def __init__(self, subscription, publication, publisher=None, publisher_authid=N :type retained: bool or None :param enc_algo: Payload encryption algorithm that - was in use (currently, either ``None`` or ``u'cryptobox'``). + was in use (currently, either ``None`` or ``'cryptobox'``). :type enc_algo: str or None :param forward_for: When this Event is forwarded for a client (or from an intermediary router). @@ -731,7 +729,7 @@ def __init__(self, subscription, publication, publisher=None, publisher_authid=N self.forward_for = forward_for def __str__(self): - return u"EventDetails(subscription={}, publication={}, publisher={}, publisher_authid={}, publisher_authrole={}, topic=<{}>, retained={}, enc_algo={}, forward_for={})".format(self.subscription, self.publication, self.publisher, self.publisher_authid, self.publisher_authrole, self.topic, self.retained, self.enc_algo, self.forward_for) + return "EventDetails(subscription={}, publication={}, publisher={}, publisher_authid={}, publisher_authrole={}, topic=<{}>, retained={}, enc_algo={}, forward_for={})".format(self.subscription, self.publication, self.publisher, self.publisher_authid, self.publisher_authrole, self.topic, self.retained, self.enc_algo, self.forward_for) @public @@ -851,39 +849,39 @@ def message_attr(self): options = {} if self.acknowledge is not None: - options[u'acknowledge'] = self.acknowledge + options['acknowledge'] = self.acknowledge if self.exclude_me is not None: - options[u'exclude_me'] = self.exclude_me + options['exclude_me'] = self.exclude_me if self.exclude is not None: - options[u'exclude'] = self.exclude if type(self.exclude) == list else [self.exclude] + options['exclude'] = self.exclude if type(self.exclude) == list else [self.exclude] if self.exclude_authid is not None: - options[u'exclude_authid'] = self.exclude_authid if type(self.exclude_authid) == list else [self.exclude_authid] + options['exclude_authid'] = self.exclude_authid if type(self.exclude_authid) == list else [self.exclude_authid] if self.exclude_authrole is not None: - options[u'exclude_authrole'] = self.exclude_authrole if type(self.exclude_authrole) == list else [self.exclude_authrole] + options['exclude_authrole'] = self.exclude_authrole if type(self.exclude_authrole) == list else [self.exclude_authrole] if self.eligible is not None: - options[u'eligible'] = self.eligible if type(self.eligible) == list else [self.eligible] + options['eligible'] = self.eligible if type(self.eligible) == list else [self.eligible] if self.eligible_authid is not None: - options[u'eligible_authid'] = self.eligible_authid if type(self.eligible_authid) == list else [self.eligible_authid] + options['eligible_authid'] = self.eligible_authid if type(self.eligible_authid) == list else [self.eligible_authid] if self.eligible_authrole is not None: - options[u'eligible_authrole'] = self.eligible_authrole if type(self.eligible_authrole) == list else [self.eligible_authrole] + options['eligible_authrole'] = self.eligible_authrole if type(self.eligible_authrole) == list else [self.eligible_authrole] if self.retain is not None: - options[u'retain'] = self.retain + options['retain'] = self.retain if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return options def __str__(self): - return u"PublishOptions(acknowledge={}, exclude_me={}, exclude={}, exclude_authid={}, exclude_authrole={}, eligible={}, eligible_authid={}, eligible_authrole={}, retain={}, forward_for={})".format(self.acknowledge, self.exclude_me, self.exclude, self.exclude_authid, self.exclude_authrole, self.eligible, self.eligible_authid, self.eligible_authrole, self.retain, self.forward_for) + return "PublishOptions(acknowledge={}, exclude_me={}, exclude={}, exclude_authid={}, exclude_authrole={}, eligible={}, eligible_authid={}, eligible_authrole={}, retain={}, forward_for={})".format(self.acknowledge, self.exclude_me, self.exclude, self.exclude_authid, self.exclude_authrole, self.eligible, self.eligible_authid, self.eligible_authrole, self.retain, self.forward_for) @public @@ -942,8 +940,8 @@ def __init__(self, match=None, invoke=None, concurrency=None, force_reregister=N or via an intermediary router. :type forward_for: list[dict] """ - assert(match is None or (type(match) == str and match in [u'exact', u'prefix', u'wildcard'])) - assert(invoke is None or (type(invoke) == str and invoke in [u'single', u'first', u'last', u'roundrobin', u'random'])) + assert(match is None or (type(match) == str and match in ['exact', 'prefix', 'wildcard'])) + assert(invoke is None or (type(invoke) == str and invoke in ['single', 'first', 'last', 'roundrobin', 'random'])) assert(concurrency is None or (type(concurrency) == int and concurrency > 0)) assert(details is None or (type(details) == bool and details_arg is None)) assert(details_arg is None or type(details_arg) == str) # yes, "str" is correct here, since this is about Python identifiers! @@ -982,24 +980,24 @@ def message_attr(self): options = {} if self.match is not None: - options[u'match'] = self.match + options['match'] = self.match if self.invoke is not None: - options[u'invoke'] = self.invoke + options['invoke'] = self.invoke if self.concurrency is not None: - options[u'concurrency'] = self.concurrency + options['concurrency'] = self.concurrency if self.force_reregister is not None: - options[u'force_reregister'] = self.force_reregister + options['force_reregister'] = self.force_reregister if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for return options def __str__(self): - return u"RegisterOptions(match={}, invoke={}, concurrency={}, details={}, details_arg={}, force_reregister={}, forward_for={})".format(self.match, self.invoke, self.concurrency, self.details, self.details_arg, self.force_reregister, self.forward_for) + return "RegisterOptions(match={}, invoke={}, concurrency={}, details={}, details_arg={}, force_reregister={}, forward_for={})".format(self.match, self.invoke, self.concurrency, self.details, self.details_arg, self.force_reregister, self.forward_for) @public @@ -1078,7 +1076,7 @@ def __init__(self, registration, progress=None, caller=None, caller_authid=None, self.forward_for = forward_for def __str__(self): - return u"CallDetails(registration={}, progress={}, caller={}, caller_authid={}, caller_authrole={}, procedure=<{}>, enc_algo={}, forward_for={})".format(self.registration, self.progress, self.caller, self.caller_authid, self.caller_authrole, self.procedure, self.enc_algo, self.forward_for) + return "CallDetails(registration={}, progress={}, caller={}, caller_authid={}, caller_authrole={}, procedure=<{}>, enc_algo={}, forward_for={})".format(self.registration, self.progress, self.caller, self.caller_authid, self.caller_authrole, self.procedure, self.enc_algo, self.forward_for) @public @@ -1163,27 +1161,27 @@ def message_attr(self): # other attributes are for client-side/client-internal use only if self.timeout is not None: - options[u'timeout'] = self.timeout + options['timeout'] = self.timeout if self.on_progress is not None: - options[u'receive_progress'] = True + options['receive_progress'] = True if self.forward_for is not None: - options[u'forward_for'] = self.forward_for + options['forward_for'] = self.forward_for if self.caller is not None: - options[u'caller'] = self.caller + options['caller'] = self.caller if self.caller_authid is not None: - options[u'caller_authid'] = self.caller_authid + options['caller_authid'] = self.caller_authid if self.caller_authrole is not None: - options[u'caller_authrole'] = self.caller_authrole + options['caller_authrole'] = self.caller_authrole return options def __str__(self): - return u"CallOptions(on_progress={}, timeout={}, caller={}, caller_authid={}, caller_authrole={}, forward_for={}, details={})".format(self.on_progress, self.timeout, self.caller, self.caller_authid, self.caller_authrole, self.forward_for, self.details) + return "CallOptions(on_progress={}, timeout={}, caller={}, caller_authid={}, caller_authrole={}, forward_for={}, details={})".format(self.on_progress, self.timeout, self.caller, self.caller_authid, self.caller_authrole, self.forward_for, self.details) @public @@ -1241,7 +1239,7 @@ def __init__(self, *results, **kwresults): self.kwresults = kwresults def __str__(self): - return u"CallResult(results={}, kwresults={}, enc_algo={}, callee={}, callee_authid={}, callee_authrole={}, forward_for={})".format(self.results, self.kwresults, self.enc_algo, self.callee, self.callee_authid, self.callee_authrole, self.forward_for) + return "CallResult(results={}, kwresults={}, enc_algo={}, callee={}, callee_authid={}, callee_authrole={}, forward_for={})".format(self.results, self.kwresults, self.enc_algo, self.callee, self.callee_authid, self.callee_authrole, self.forward_for) @public diff --git a/autobahn/wamp/uri.py b/autobahn/wamp/uri.py index be7873b7d..15652f563 100644 --- a/autobahn/wamp/uri.py +++ b/autobahn/wamp/uri.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import - import re @@ -73,18 +71,18 @@ def convert_starred_uri(uri): """ assert(type(uri) == str) - cnt_stars = uri.count(u'*') + cnt_stars = uri.count('*') if cnt_stars == 0: - match = u'exact' + match = 'exact' - elif cnt_stars == 1 and uri[-1] == u'*': - match = u'prefix' + elif cnt_stars == 1 and uri[-1] == '*': + match = 'prefix' uri = uri[:-1] else: - match = u'wildcard' - uri = uri.replace(u'*', u'') + match = 'wildcard' + uri = uri.replace('*', '') return uri, match @@ -331,7 +329,7 @@ def register(uri, options=None): def decorate(f): assert(callable(f)) if uri is None: - real_uri = u'{}'.format(f.__name__) + real_uri = '{}'.format(f.__name__) else: real_uri = uri if not hasattr(f, '_wampuris'): diff --git a/autobahn/wamp/websocket.py b/autobahn/wamp/websocket.py index 3f235dcbc..280d3580d 100644 --- a/autobahn/wamp/websocket.py +++ b/autobahn/wamp/websocket.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import copy import traceback @@ -62,7 +60,7 @@ def onOpen(self): self._session.onOpen(self) except Exception as e: self.log.critical("{tb}", tb=traceback.format_exc()) - reason = u'WAMP Internal Error ({0})'.format(e) + reason = 'WAMP Internal Error ({0})'.format(e) self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_INTERNAL_ERROR, reason=reason) def onClose(self, wasClean, code, reason): @@ -98,12 +96,12 @@ def onMessage(self, payload, isBinary): except ProtocolError as e: self.log.critical("{tb}", tb=traceback.format_exc()) - reason = u'WAMP Protocol Error ({0})'.format(e) + reason = 'WAMP Protocol Error ({0})'.format(e) self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_PROTOCOL_ERROR, reason=reason) except Exception as e: self.log.critical("{tb}", tb=traceback.format_exc()) - reason = u'WAMP Internal Error ({0})'.format(e) + reason = 'WAMP Internal Error ({0})'.format(e) self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_INTERNAL_ERROR, reason=reason) def send(self, msg): @@ -122,7 +120,7 @@ def send(self, msg): except Exception as e: self.log.error("WAMP message serialization error: {}".format(e)) # all exceptions raised from above should be serialization errors .. - raise SerializationError(u"WAMP message serialization error: {0}".format(e)) + raise SerializationError("WAMP message serialization error: {0}".format(e)) else: self.sendMessage(payload, isBinary) else: @@ -158,11 +156,11 @@ def abort(self): def parseSubprotocolIdentifier(subprotocol): try: - s = subprotocol.split(u'.') - if s[0] != u'wamp': - raise Exception(u'WAMP WebSocket subprotocol identifier must start with "wamp", not "{}"'.format(s[0])) + s = subprotocol.split('.') + if s[0] != 'wamp': + raise Exception('WAMP WebSocket subprotocol identifier must start with "wamp", not "{}"'.format(s[0])) version = int(s[1]) - serializerId = u'.'.join(s[2:]) + serializerId = '.'.join(s[2:]) return version, serializerId except: return None, None @@ -190,10 +188,10 @@ def onConnect(self, request): return subprotocol, headers if self.STRICT_PROTOCOL_NEGOTIATION: - raise ConnectionDeny(ConnectionDeny.BAD_REQUEST, u'This server only speaks WebSocket subprotocols {}'.format(u', '.join(self.factory.protocols))) + raise ConnectionDeny(ConnectionDeny.BAD_REQUEST, 'This server only speaks WebSocket subprotocols {}'.format(', '.join(self.factory.protocols))) else: # assume wamp.2.json - self._serializer = copy.copy(self.factory._serializers[u'json']) + self._serializer = copy.copy(self.factory._serializers['json']) return None, headers @@ -210,10 +208,10 @@ def onConnect(self, response): """ if response.protocol not in self.factory.protocols: if self.STRICT_PROTOCOL_NEGOTIATION: - raise Exception(u'The server does not speak any of the WebSocket subprotocols {} we requested.'.format(u', '.join(self.factory.protocols))) + raise Exception('The server does not speak any of the WebSocket subprotocols {} we requested.'.format(', '.join(self.factory.protocols))) else: # assume wamp.2.json - serializerId = u'json' + serializerId = 'json' else: version, serializerId = parseSubprotocolIdentifier(response.protocol) @@ -279,13 +277,13 @@ def __init__(self, factory, serializers=None): pass if not serializers: - raise Exception(u'Could not import any WAMP serializer') + raise Exception('Could not import any WAMP serializer') self._serializers = {} for ser in serializers: self._serializers[ser.SERIALIZER_ID] = ser - self._protocols = [u'wamp.2.{}'.format(ser.SERIALIZER_ID) for ser in serializers] + self._protocols = ['wamp.2.{}'.format(ser.SERIALIZER_ID) for ser in serializers] class WampWebSocketServerFactory(WampWebSocketFactory): diff --git a/autobahn/websocket/__init__.py b/autobahn/websocket/__init__.py index d8cc4e8e3..f155733ed 100644 --- a/autobahn/websocket/__init__.py +++ b/autobahn/websocket/__init__.py @@ -25,8 +25,6 @@ ############################################################################### -from __future__ import absolute_import - from autobahn.websocket.types import ConnectionRequest, ConnectionResponse, \ ConnectionAccept, ConnectionDeny, Message, IncomingMessage, OutgoingMessage from autobahn.websocket.interfaces import IWebSocketChannel diff --git a/autobahn/websocket/compress.py b/autobahn/websocket/compress.py index 222cd0591..c49d5d521 100644 --- a/autobahn/websocket/compress.py +++ b/autobahn/websocket/compress.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.websocket.compress_base import \ PerMessageCompressOffer, \ PerMessageCompressOfferAccept, \ diff --git a/autobahn/websocket/compress_bzip2.py b/autobahn/websocket/compress_bzip2.py index 63fe271f7..28b0f95fa 100644 --- a/autobahn/websocket/compress_bzip2.py +++ b/autobahn/websocket/compress_bzip2.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import bz2 from autobahn.websocket.compress_base import PerMessageCompressOffer, \ diff --git a/autobahn/websocket/compress_deflate.py b/autobahn/websocket/compress_deflate.py index ab1d07ecc..3d2d8fa54 100644 --- a/autobahn/websocket/compress_deflate.py +++ b/autobahn/websocket/compress_deflate.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import zlib from autobahn.util import public diff --git a/autobahn/websocket/compress_snappy.py b/autobahn/websocket/compress_snappy.py index 7233f8074..ba0ffcdb1 100644 --- a/autobahn/websocket/compress_snappy.py +++ b/autobahn/websocket/compress_snappy.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import snappy from autobahn.websocket.compress_base import PerMessageCompressOffer, \ diff --git a/autobahn/websocket/protocol.py b/autobahn/websocket/protocol.py index 48150c7a7..f3be8029b 100755 --- a/autobahn/websocket/protocol.py +++ b/autobahn/websocket/protocol.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import binascii import hashlib import base64 @@ -366,7 +364,7 @@ class WebSocketProtocol(ObservableMixin): * :class:`autobahn.websocket.interfaces.IWebSocketChannelStreamingApi` """ - peer = u'' + peer = '' SUPPORTED_SPEC_VERSIONS = [10, 11, 12, 13, 14, 15, 16, 17, 18] """ @@ -579,12 +577,12 @@ def onMessageFrameBegin(self, length): self.wasMaxMessagePayloadSizeExceeded = True self._max_message_size_exceeded(self.message_data_total_length, self.maxMessagePayloadSize, - u'received WebSocket message size {} exceeds payload limit of {} octets'.format(self.message_data_total_length, self.maxMessagePayloadSize)) + 'received WebSocket message size {} exceeds payload limit of {} octets'.format(self.message_data_total_length, self.maxMessagePayloadSize)) elif 0 < self.maxFramePayloadSize < length: self.wasMaxFramePayloadSizeExceeded = True self._max_message_size_exceeded(length, self.maxFramePayloadSize, - u'received WebSocket frame size {} exceeds payload limit of {} octets'.format(length, self.maxFramePayloadSize)) + 'received WebSocket frame size {} exceeds payload limit of {} octets'.format(length, self.maxFramePayloadSize)) def onMessageFrameData(self, payload): """ @@ -597,7 +595,7 @@ def onMessageFrameData(self, payload): self.wasMaxMessagePayloadSizeExceeded = True self._max_message_size_exceeded(self.message_data_total_length, self.maxMessagePayloadSize, - u'received (partial) WebSocket message size {} (already) exceeds payload limit of {} octets'.format(self.message_data_total_length, self.maxMessagePayloadSize)) + 'received (partial) WebSocket message size {} (already) exceeds payload limit of {} octets'.format(self.message_data_total_length, self.maxMessagePayloadSize)) self.message_data.append(payload) else: self.frame_data.append(payload) @@ -701,7 +699,7 @@ def onCloseFrame(self, code, reasonRaw): # reserved close codes: 0-999, 1004, 1005, 1006, 1011-2999, >= 5000 # if code is not None and (code < 1000 or (1000 <= code <= 2999 and code not in WebSocketProtocol.CLOSE_STATUS_CODES_ALLOWED) or code >= 5000): - if self._protocol_violation(u'invalid close code {}'.format(code)): + if self._protocol_violation('invalid close code {}'.format(code)): return True else: self.remoteCloseCode = WebSocketProtocol.CLOSE_STATUS_CODE_NORMAL @@ -718,7 +716,7 @@ def onCloseFrame(self, code, reasonRaw): # the UTF8 must be valid _and_ end on a Unicode code point if not (val[0] and val[1]): - if self._invalid_payload(u'invalid close reason (non-UTF8 payload)'): + if self._invalid_payload('invalid close reason (non-UTF8 payload)'): return True else: self.remoteCloseReason = reasonRaw.decode('utf8') @@ -792,7 +790,7 @@ def onServerConnectionDropTimeout(self): if self.state != WebSocketProtocol.STATE_CLOSED: self.wasClean = False - self.wasNotCleanReason = u'WebSocket closing handshake timeout (server did not drop TCP connection in time)' + self.wasNotCleanReason = 'WebSocket closing handshake timeout (server did not drop TCP connection in time)' self.wasServerConnectionDropTimeout = True self.dropConnection(abort=True) else: @@ -808,7 +806,7 @@ def onOpenHandshakeTimeout(self): if self.state in [WebSocketProtocol.STATE_CONNECTING, WebSocketProtocol.STATE_PROXY_CONNECTING]: self.wasClean = False - self.wasNotCleanReason = u'WebSocket opening handshake timeout (peer did not finish the opening handshake in time)' + self.wasNotCleanReason = 'WebSocket opening handshake timeout (peer did not finish the opening handshake in time)' self.wasOpenHandshakeTimeout = True self.dropConnection(abort=True) elif self.state == WebSocketProtocol.STATE_OPEN: @@ -831,7 +829,7 @@ def onCloseHandshakeTimeout(self): if self.state != WebSocketProtocol.STATE_CLOSED: self.wasClean = False - self.wasNotCleanReason = u'WebSocket closing handshake timeout (peer did not finish the opening handshake in time)' + self.wasNotCleanReason = 'WebSocket closing handshake timeout (peer did not finish the opening handshake in time)' self.wasCloseHandshakeTimeout = True self.dropConnection(abort=True) else: @@ -843,7 +841,7 @@ def onAutoPingTimeout(self): did not reply in time to our ping. We drop the connection. """ self.wasClean = False - self.wasNotCleanReason = u'WebSocket ping timeout (peer did not respond with pong in time)' + self.wasNotCleanReason = 'WebSocket ping timeout (peer did not respond with pong in time)' self.autoPingTimeoutCall = None self.dropConnection(abort=True) @@ -878,7 +876,7 @@ def _max_message_size_exceeded(self, msg_size, max_msg_size, reason): else: raise PayloadExceededError(reason) - def _fail_connection(self, code=CLOSE_STATUS_CODE_GOING_AWAY, reason=u'going away'): + def _fail_connection(self, code=CLOSE_STATUS_CODE_GOING_AWAY, reason='going away'): """ Fails the WebSocket connection. """ @@ -890,7 +888,7 @@ def _fail_connection(self, code=CLOSE_STATUS_CODE_GOING_AWAY, reason=u'going awa if self.failByDrop: # brutally drop the TCP connection self.wasClean = False - self.wasNotCleanReason = u'I dropped the WebSocket TCP connection: {0}'.format(reason) + self.wasNotCleanReason = 'I dropped the WebSocket TCP connection: {0}'.format(reason) self.dropConnection(abort=True) else: @@ -1124,7 +1122,7 @@ def _connectionLost(self, reason): if reason_string: self.wasNotCleanReason = reason_string else: - self.wasNotCleanReason = u'peer dropped the TCP connection without previous WebSocket closing handshake' + self.wasNotCleanReason = 'peer dropped the TCP connection without previous WebSocket closing handshake' self._onClose(self.wasClean, WebSocketProtocol.CLOSE_STATUS_CODE_ABNORMAL_CLOSE, "connection was closed uncleanly (%s)" % self.wasNotCleanReason) else: self._onClose(self.wasClean, self.remoteCloseCode, self.remoteCloseReason) @@ -1382,19 +1380,19 @@ def processData(self): if self._perMessageCompress is not None and frame_rsv == 4: pass else: - if self._protocol_violation(u'RSV = {} and no extension negotiated'.format(frame_rsv)): + if self._protocol_violation('RSV = {} and no extension negotiated'.format(frame_rsv)): return False # all client-to-server frames MUST be masked # if self.factory.isServer and self.requireMaskedClientFrames and not frame_masked: - if self._protocol_violation(u'unmasked client-to-server frame'): + if self._protocol_violation('unmasked client-to-server frame'): return False # all server-to-client frames MUST NOT be masked # if not self.factory.isServer and not self.acceptMaskedServerFrames and frame_masked: - if self._protocol_violation(u'masked server-to-client frame'): + if self._protocol_violation('masked server-to-client frame'): return False # check frame @@ -1404,32 +1402,32 @@ def processData(self): # control frames MUST NOT be fragmented # if not frame_fin: - if self._protocol_violation(u'fragmented control frame'): + if self._protocol_violation('fragmented control frame'): return False # control frames MUST have payload 125 octets or less # if frame_payload_len1 > 125: - if self._protocol_violation(u'control frame with payload length > 125 octets'): + if self._protocol_violation('control frame with payload length > 125 octets'): return False # check for reserved control frame opcodes # if frame_opcode not in [8, 9, 10]: - if self._protocol_violation(u'control frame using reserved opcode {}'.format(frame_opcode)): + if self._protocol_violation('control frame using reserved opcode {}'.format(frame_opcode)): return False # close frame : if there is a body, the first two bytes of the body MUST be a 2-byte # unsigned integer (in network byte order) representing a status code # if frame_opcode == 8 and frame_payload_len1 == 1: - if self._protocol_violation(u'received close control frame with payload len 1'): + if self._protocol_violation('received close control frame with payload len 1'): return False # control frames MUST NOT be compressed # if self._perMessageCompress is not None and frame_rsv == 4: - if self._protocol_violation(u'received compressed control frame [{}]'.format(self._perMessageCompress.EXTENSION_NAME)): + if self._protocol_violation('received compressed control frame [{}]'.format(self._perMessageCompress.EXTENSION_NAME)): return False else: # data frame @@ -1437,25 +1435,25 @@ def processData(self): # check for reserved data frame opcodes # if frame_opcode not in [0, 1, 2]: - if self._protocol_violation(u'data frame using reserved opcode {}'.format(frame_opcode)): + if self._protocol_violation('data frame using reserved opcode {}'.format(frame_opcode)): return False # check opcode vs message fragmentation state 1/2 # if not self.inside_message and frame_opcode == 0: - if self._protocol_violation(u'received continuation data frame outside fragmented message'): + if self._protocol_violation('received continuation data frame outside fragmented message'): return False # check opcode vs message fragmentation state 2/2 # if self.inside_message and frame_opcode != 0: - if self._protocol_violation(u'received non-continuation data frame while inside fragmented message'): + if self._protocol_violation('received non-continuation data frame while inside fragmented message'): return False # continuation data frames MUST NOT have the compressed bit set # if self._perMessageCompress is not None and frame_rsv == 4 and self.inside_message: - if self._protocol_violation(u'received continuation data frame with compress bit set [{}]'.format(self._perMessageCompress.EXTENSION_NAME)): + if self._protocol_violation('received continuation data frame with compress bit set [{}]'.format(self._perMessageCompress.EXTENSION_NAME)): return False # compute complete header length @@ -1488,16 +1486,16 @@ def processData(self): if frame_payload_len1 == 126: frame_payload_len = struct.unpack("!H", self.data[i:i + 2])[0] if frame_payload_len < 126: - if self._protocol_violation(u'invalid data frame length (not using minimal length encoding)'): + if self._protocol_violation('invalid data frame length (not using minimal length encoding)'): return False i += 2 elif frame_payload_len1 == 127: frame_payload_len = struct.unpack("!Q", self.data[i:i + 8])[0] if frame_payload_len > 0x7FFFFFFFFFFFFFFF: # 2**63 - if self._protocol_violation(u'invalid data frame length (>2^63)'): + if self._protocol_violation('invalid data frame length (>2^63)'): return False if frame_payload_len < 65536: - if self._protocol_violation(u'invalid data frame length (not using minimal length encoding)'): + if self._protocol_violation('invalid data frame length (not using minimal length encoding)'): return False i += 8 else: @@ -1661,7 +1659,7 @@ def onFrameData(self, payload): if self.utf8validateIncomingCurrentMessage: self.utf8validateLast = self.utf8validator.validate(payload) if not self.utf8validateLast[0]: - if self._invalid_payload(u'encountered invalid UTF-8 while processing text message at payload octet index {}'.format(self.utf8validateLast[3])): + if self._invalid_payload('encountered invalid UTF-8 while processing text message at payload octet index {}'.format(self.utf8validateLast[3])): return False self._onMessageFrameData(payload) @@ -1693,7 +1691,7 @@ def onFrameEnd(self): # if self.utf8validateIncomingCurrentMessage: if not self.utf8validateLast[1]: - if self._invalid_payload(u'UTF-8 text message payload ended within Unicode code point at payload octet index {}'.format(self.utf8validateLast[3])): + if self._invalid_payload('UTF-8 text message payload ended within Unicode code point at payload octet index {}'.format(self.utf8validateLast[3])): return False if self.state == WebSocketProtocol.STATE_OPEN: @@ -2228,7 +2226,7 @@ def sendMessage(self, if 0 < self.maxMessagePayloadSize < payload_len: self.wasMaxMessagePayloadSizeExceeded = True - emsg = u'tried to send WebSocket message with size {} exceeding payload limit of {} octets'.format(payload_len, self.maxMessagePayloadSize) + emsg = 'tried to send WebSocket message with size {} exceeding payload limit of {} octets'.format(payload_len, self.maxMessagePayloadSize) self.log.warn(emsg) raise PayloadExceededError(emsg) @@ -3197,7 +3195,7 @@ def resetProtocolOptions(self): self.closeHandshakeTimeout = 1 self.tcpNoDelay = True self.serveFlashSocketPolicy = False - self.flashSocketPolicy = u''' + self.flashSocketPolicy = ''' \x00''' @@ -3825,7 +3823,7 @@ def processHandshake(self): except Exception as e: # immediately close the WS connection # - self._fail_connection(1000, u'{}'.format(e)) + self._fail_connection(1000, '{}'.format(e)) else: # fire handler on derived class # diff --git a/autobahn/websocket/test/test_protocol.py b/autobahn/websocket/test/test_protocol.py index aa05d648c..5763c868f 100644 --- a/autobahn/websocket/test/test_protocol.py +++ b/autobahn/websocket/test/test_protocol.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import, print_function - import os import unittest from hashlib import sha1 @@ -159,7 +157,7 @@ def test_sendClose_str_reason(self): """ sendClose with a str reason works. """ - self.protocol.sendClose(code=1000, reason=u"oh no") + self.protocol.sendClose(code=1000, reason="oh no") # We closed properly self.assertEqual(self.transport._written[2:], b"\x03\xe8oh no") @@ -169,7 +167,7 @@ def test_sendClose_unicode_reason(self): """ sendClose with a unicode reason works. """ - self.protocol.sendClose(code=1000, reason=u"oh no") + self.protocol.sendClose(code=1000, reason="oh no") # We closed properly self.assertEqual(self.transport._written[2:], b"\x03\xe8oh no") @@ -179,7 +177,7 @@ def test_sendClose_toolong(self): """ sendClose with a too-long reason will truncate it. """ - self.protocol.sendClose(code=1000, reason=u"abc" * 1000) + self.protocol.sendClose(code=1000, reason="abc" * 1000) # We closed properly self.assertEqual(self.transport._written[2:], @@ -191,7 +189,7 @@ def test_sendClose_reason_with_no_code(self): Trying to sendClose with a reason but no code will raise an Exception. """ with self.assertRaises(Exception) as e: - self.protocol.sendClose(reason=u"abc") + self.protocol.sendClose(reason="abc") self.assertIn("close reason without close code", str(e.exception)) diff --git a/autobahn/websocket/test/test_websocket.py b/autobahn/websocket/test/test_websocket.py index 54661014e..3384d0e1e 100644 --- a/autobahn/websocket/test/test_websocket.py +++ b/autobahn/websocket/test/test_websocket.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import, print_function - import os import struct diff --git a/autobahn/websocket/test/test_websocket_url.py b/autobahn/websocket/test/test_websocket_url.py index db9e992a0..1f1b8b060 100644 --- a/autobahn/websocket/test/test_websocket_url.py +++ b/autobahn/websocket/test/test_websocket_url.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - import unittest from autobahn.websocket.util import create_url, parse_url diff --git a/autobahn/websocket/types.py b/autobahn/websocket/types.py index 20c05e63e..e783809cb 100644 --- a/autobahn/websocket/types.py +++ b/autobahn/websocket/types.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.util import public import json @@ -214,7 +212,7 @@ def __init__(self, peer, is_secure, secure_channel_id): :param dict secure_channel_id: information about our channel-binding or None if not using TLS. The only channel-binding currently is `tls-unique` so if this is a - `dict` it will be: `{u'tls-unique': bytes}` + `dict` it will be: `{'tls-unique': bytes}` """ self.peer = peer self.is_secure = is_secure diff --git a/autobahn/websocket/util.py b/autobahn/websocket/util.py index cfacd9707..5e884f62c 100644 --- a/autobahn/websocket/util.py +++ b/autobahn/websocket/util.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.util import public from urllib import parse as urlparse @@ -81,27 +79,27 @@ def create_url(hostname, port=None, isSecure=False, path=None, params=None): assert type(isSecure) == bool if hostname == 'unix': - netloc = u"unix:%s" % port + netloc = "unix:%s" % port else: assert port is None or (type(port) == int and port in range(0, 65535)) if port is not None: - netloc = u"%s:%d" % (hostname, port) + netloc = "%s:%d" % (hostname, port) else: if isSecure: - netloc = u"%s:443" % hostname + netloc = "%s:443" % hostname else: - netloc = u"%s:80" % hostname + netloc = "%s:80" % hostname if isSecure: - scheme = u"wss" + scheme = "wss" else: - scheme = u"ws" + scheme = "ws" if path is not None: ppath = urlparse.quote(path) else: - ppath = u"/" + ppath = "/" if params is not None: query = urlparse.urlencode(params) @@ -161,7 +159,7 @@ def parse_url(url): resource = ppath params = {} - if parsed.hostname == u"unix": + if parsed.hostname == "unix": # Unix domain sockets sockets # ws://unix:/tmp/file.sock => unix:/tmp/file.sock => /tmp/file.sock diff --git a/autobahn/xbr/__init__.py b/autobahn/xbr/__init__.py index 2f5ba42c5..3bf45a00f 100644 --- a/autobahn/xbr/__init__.py +++ b/autobahn/xbr/__init__.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - try: from mnemonic import Mnemonic from autobahn.xbr._mnemonic import mnemonic_to_private_key diff --git a/autobahn/xbr/test/test_mnemonic.py b/autobahn/xbr/test/test_mnemonic.py index 65e0c6791..a66f364b1 100644 --- a/autobahn/xbr/test/test_mnemonic.py +++ b/autobahn/xbr/test/test_mnemonic.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from autobahn.xbr import HAS_XBR if HAS_XBR: diff --git a/docker/aarch64/app/client_aio.py b/docker/aarch64/app/client_aio.py index 5fc4b08d7..f50843291 100644 --- a/docker/aarch64/app/client_aio.py +++ b/docker/aarch64/app/client_aio.py @@ -1,11 +1,8 @@ -import os import argparse -import txaio +import asyncio +import os -try: - import asyncio -except ImportError: - import trollius as asyncio +import txaio from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner @@ -17,7 +14,7 @@ class ClientSession(ApplicationSession): def onConnect(self): self.log.info("Client connected") - self.join(self.config.realm, [u'anonymous']) + self.join(self.config.realm, ['anonymous']) def onChallenge(self, challenge): self.log.info("Challenge for method {authmethod} received", authmethod=challenge.method) @@ -45,8 +42,8 @@ def onDisconnect(self): if __name__ == '__main__': # Crossbar.io connection configuration - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -64,7 +61,7 @@ def onDisconnect(self): # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } # now actually run a WAMP client using our session class ClientSession diff --git a/docker/aarch64/app/client_publish.py b/docker/aarch64/app/client_publish.py index b910707d1..5a542dfcb 100644 --- a/docker/aarch64/app/client_publish.py +++ b/docker/aarch64/app/client_publish.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function -from os import environ import os import argparse from twisted.internet.defer import inlineCallbacks @@ -45,14 +43,14 @@ def onJoin(self, details): counter = 0 while True: print('backend publishing com.myapp.hello', counter) - self.publish(u'com.myapp.hello', "Hello World %d"%counter) + self.publish('com.myapp.hello', "Hello World %d"%counter) counter += 1 yield sleep(1) if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -63,7 +61,7 @@ def onJoin(self, details): args = parser.parse_args() # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) diff --git a/docker/aarch64/app/client_rpc_callee.py b/docker/aarch64/app/client_rpc_callee.py index 591332241..b5c915342 100644 --- a/docker/aarch64/app/client_rpc_callee.py +++ b/docker/aarch64/app/client_rpc_callee.py @@ -47,7 +47,7 @@ def utcnow(): return now.strftime("%Y-%m-%dT%H:%M:%SZ") try: - yield self.register(utcnow, u'my.com.date') + yield self.register(utcnow, 'my.com.date') except Exception as e: print("failed to register procedure: {}".format(e)) else: @@ -55,8 +55,8 @@ def utcnow(): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -67,7 +67,7 @@ def utcnow(): args = parser.parse_args() # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) diff --git a/docker/aarch64/app/client_rpc_caller.py b/docker/aarch64/app/client_rpc_caller.py index 6c1f28866..90ee21d73 100644 --- a/docker/aarch64/app/client_rpc_caller.py +++ b/docker/aarch64/app/client_rpc_caller.py @@ -42,7 +42,7 @@ class ClientSession(ApplicationSession): def onJoin(self, details): print("session attached") try: - now = yield self.call(u'my.com.date') + now = yield self.call('my.com.date') except Exception as e: print("Error: {}".format(e)) else: @@ -56,8 +56,8 @@ def onDisconnect(self): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -68,7 +68,7 @@ def onDisconnect(self): args = parser.parse_args() # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) diff --git a/docker/aarch64/app/client_subscribe.py b/docker/aarch64/app/client_subscribe.py index c85737f53..1945ee53f 100644 --- a/docker/aarch64/app/client_subscribe.py +++ b/docker/aarch64/app/client_subscribe.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function -from os import environ import os import argparse @@ -45,7 +43,7 @@ class ClientSession(ApplicationSession): def onJoin(self, details): print("session attached") self.received = 0 - sub = yield self.subscribe(self.on_event, u'com.myapp.hello') + sub = yield self.subscribe(self.on_event, 'com.myapp.hello') print("Subscribed to com.myapp.hello with {}".format(sub.id)) def on_event(self, i): @@ -63,8 +61,8 @@ def onDisconnect(self): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -77,10 +75,10 @@ def onDisconnect(self): extra=dict( max_events=5, # [A] pass in additional configuration ) - #url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://192.168.0.15:8080/ws") + #url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://192.168.0.15:8080/ws") #if six.PY2 and type(url) == six.binary_type: # url = url.decode('utf8') - #realm = u"realm1" + #realm = "realm1" runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) runner.run(ClientSession, auto_reconnect=True) diff --git a/docker/aarch64/app/client_tx.py b/docker/aarch64/app/client_tx.py index 21cc60619..28954916e 100644 --- a/docker/aarch64/app/client_tx.py +++ b/docker/aarch64/app/client_tx.py @@ -14,7 +14,7 @@ class ClientSession(ApplicationSession): def onConnect(self): self.log.info("Client connected") - self.join(self.config.realm, [u'anonymous']) + self.join(self.config.realm, ['anonymous']) def onChallenge(self, challenge): self.log.info("Challenge for method {authmethod} received", authmethod=challenge.method) @@ -42,8 +42,8 @@ def onDisconnect(self): if __name__ == '__main__': # Crossbar.io connection configuration - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -61,7 +61,7 @@ def onDisconnect(self): # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } # now actually run a WAMP client using our session class ClientSession diff --git a/docker/armhf/app/client_aio.py b/docker/armhf/app/client_aio.py index 5fc4b08d7..f50843291 100644 --- a/docker/armhf/app/client_aio.py +++ b/docker/armhf/app/client_aio.py @@ -1,11 +1,8 @@ -import os import argparse -import txaio +import asyncio +import os -try: - import asyncio -except ImportError: - import trollius as asyncio +import txaio from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner @@ -17,7 +14,7 @@ class ClientSession(ApplicationSession): def onConnect(self): self.log.info("Client connected") - self.join(self.config.realm, [u'anonymous']) + self.join(self.config.realm, ['anonymous']) def onChallenge(self, challenge): self.log.info("Challenge for method {authmethod} received", authmethod=challenge.method) @@ -45,8 +42,8 @@ def onDisconnect(self): if __name__ == '__main__': # Crossbar.io connection configuration - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -64,7 +61,7 @@ def onDisconnect(self): # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } # now actually run a WAMP client using our session class ClientSession diff --git a/docker/armhf/app/client_publish.py b/docker/armhf/app/client_publish.py index b910707d1..5a542dfcb 100644 --- a/docker/armhf/app/client_publish.py +++ b/docker/armhf/app/client_publish.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function -from os import environ import os import argparse from twisted.internet.defer import inlineCallbacks @@ -45,14 +43,14 @@ def onJoin(self, details): counter = 0 while True: print('backend publishing com.myapp.hello', counter) - self.publish(u'com.myapp.hello', "Hello World %d"%counter) + self.publish('com.myapp.hello', "Hello World %d"%counter) counter += 1 yield sleep(1) if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -63,7 +61,7 @@ def onJoin(self, details): args = parser.parse_args() # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) diff --git a/docker/armhf/app/client_rpc_callee.py b/docker/armhf/app/client_rpc_callee.py index 591332241..b5c915342 100644 --- a/docker/armhf/app/client_rpc_callee.py +++ b/docker/armhf/app/client_rpc_callee.py @@ -47,7 +47,7 @@ def utcnow(): return now.strftime("%Y-%m-%dT%H:%M:%SZ") try: - yield self.register(utcnow, u'my.com.date') + yield self.register(utcnow, 'my.com.date') except Exception as e: print("failed to register procedure: {}".format(e)) else: @@ -55,8 +55,8 @@ def utcnow(): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -67,7 +67,7 @@ def utcnow(): args = parser.parse_args() # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) diff --git a/docker/armhf/app/client_rpc_caller.py b/docker/armhf/app/client_rpc_caller.py index 6c1f28866..90ee21d73 100644 --- a/docker/armhf/app/client_rpc_caller.py +++ b/docker/armhf/app/client_rpc_caller.py @@ -42,7 +42,7 @@ class ClientSession(ApplicationSession): def onJoin(self, details): print("session attached") try: - now = yield self.call(u'my.com.date') + now = yield self.call('my.com.date') except Exception as e: print("Error: {}".format(e)) else: @@ -56,8 +56,8 @@ def onDisconnect(self): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -68,7 +68,7 @@ def onDisconnect(self): args = parser.parse_args() # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) diff --git a/docker/armhf/app/client_subscribe.py b/docker/armhf/app/client_subscribe.py index c85737f53..1945ee53f 100644 --- a/docker/armhf/app/client_subscribe.py +++ b/docker/armhf/app/client_subscribe.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function -from os import environ import os import argparse @@ -45,7 +43,7 @@ class ClientSession(ApplicationSession): def onJoin(self, details): print("session attached") self.received = 0 - sub = yield self.subscribe(self.on_event, u'com.myapp.hello') + sub = yield self.subscribe(self.on_event, 'com.myapp.hello') print("Subscribed to com.myapp.hello with {}".format(sub.id)) def on_event(self, i): @@ -63,8 +61,8 @@ def onDisconnect(self): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -77,10 +75,10 @@ def onDisconnect(self): extra=dict( max_events=5, # [A] pass in additional configuration ) - #url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://192.168.0.15:8080/ws") + #url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://192.168.0.15:8080/ws") #if six.PY2 and type(url) == six.binary_type: # url = url.decode('utf8') - #realm = u"realm1" + #realm = "realm1" runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra) runner.run(ClientSession, auto_reconnect=True) diff --git a/docker/armhf/app/client_tx.py b/docker/armhf/app/client_tx.py index 21cc60619..28954916e 100644 --- a/docker/armhf/app/client_tx.py +++ b/docker/armhf/app/client_tx.py @@ -14,7 +14,7 @@ class ClientSession(ApplicationSession): def onConnect(self): self.log.info("Client connected") - self.join(self.config.realm, [u'anonymous']) + self.join(self.config.realm, ['anonymous']) def onChallenge(self, challenge): self.log.info("Challenge for method {authmethod} received", authmethod=challenge.method) @@ -42,8 +42,8 @@ def onDisconnect(self): if __name__ == '__main__': # Crossbar.io connection configuration - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -61,7 +61,7 @@ def onDisconnect(self): # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } # now actually run a WAMP client using our session class ClientSession diff --git a/docker/x86_64/app/client_aio.py b/docker/x86_64/app/client_aio.py index 5fc4b08d7..f50843291 100644 --- a/docker/x86_64/app/client_aio.py +++ b/docker/x86_64/app/client_aio.py @@ -1,11 +1,8 @@ -import os import argparse -import txaio +import asyncio +import os -try: - import asyncio -except ImportError: - import trollius as asyncio +import txaio from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner @@ -17,7 +14,7 @@ class ClientSession(ApplicationSession): def onConnect(self): self.log.info("Client connected") - self.join(self.config.realm, [u'anonymous']) + self.join(self.config.realm, ['anonymous']) def onChallenge(self, challenge): self.log.info("Challenge for method {authmethod} received", authmethod=challenge.method) @@ -45,8 +42,8 @@ def onDisconnect(self): if __name__ == '__main__': # Crossbar.io connection configuration - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -64,7 +61,7 @@ def onDisconnect(self): # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } # now actually run a WAMP client using our session class ClientSession diff --git a/docker/x86_64/app/client_appsession_publish.py b/docker/x86_64/app/client_appsession_publish.py index e7698d311..2b5c7aa04 100644 --- a/docker/x86_64/app/client_appsession_publish.py +++ b/docker/x86_64/app/client_appsession_publish.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function -from os import environ import os from twisted.internet.defer import inlineCallbacks @@ -44,18 +42,18 @@ def onJoin(self, details): counter = 0 while True: print('backend publishing com.myapp.hello', counter) - self.publish(u'com.myapp.hello', "Hello World %d"%counter) + self.publish('com.myapp.hello', "Hello World %d"%counter) counter += 1 yield sleep(1) if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=url, realm=realm, extra=extra) diff --git a/docker/x86_64/app/client_appsession_rpc_callee.py b/docker/x86_64/app/client_appsession_rpc_callee.py index 8e64c3ae3..b61be8176 100644 --- a/docker/x86_64/app/client_appsession_rpc_callee.py +++ b/docker/x86_64/app/client_appsession_rpc_callee.py @@ -46,7 +46,7 @@ def utcnow(): return now.strftime("%Y-%m-%dT%H:%M:%SZ") try: - yield self.register(utcnow, u'com.timeservice.now') + yield self.register(utcnow, 'com.timeservice.now') except Exception as e: print("failed to register procedure: {}".format(e)) else: @@ -54,12 +54,12 @@ def utcnow(): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=url, realm=realm, extra=extra) diff --git a/docker/x86_64/app/client_appsession_rpc_caller.py b/docker/x86_64/app/client_appsession_rpc_caller.py index 55d7742f6..a5df05384 100644 --- a/docker/x86_64/app/client_appsession_rpc_caller.py +++ b/docker/x86_64/app/client_appsession_rpc_caller.py @@ -41,7 +41,7 @@ class ClientSession(ApplicationSession): def onJoin(self, details): print("session attached") try: - now = yield self.call(u'com.timeservice.now') + now = yield self.call('com.timeservice.now') except Exception as e: print("Error: {}".format(e)) else: @@ -55,12 +55,12 @@ def onDisconnect(self): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } runner = ApplicationRunner(url=url, realm=realm, extra=extra) diff --git a/docker/x86_64/app/client_appsession_subscribe.py b/docker/x86_64/app/client_appsession_subscribe.py index 5aeb6af41..eb8c13457 100644 --- a/docker/x86_64/app/client_appsession_subscribe.py +++ b/docker/x86_64/app/client_appsession_subscribe.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function -from os import environ import os from twisted.internet import reactor @@ -44,7 +42,7 @@ class ClientSession(ApplicationSession): def onJoin(self, details): print("session attached") self.received = 0 - sub = yield self.subscribe(self.on_event, u'com.myapp.hello') + sub = yield self.subscribe(self.on_event, 'com.myapp.hello') print("Subscribed to com.myapp.hello with {}".format(sub.id)) def on_event(self, i): @@ -62,8 +60,8 @@ def onDisconnect(self): if __name__ == '__main__': - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # any extra info we want to forward to our ClientSession (in self.config.extra) extra=dict( diff --git a/docker/x86_64/app/client_component_publish.py b/docker/x86_64/app/client_component_publish.py index 8b2670af0..aec8bf9f6 100644 --- a/docker/x86_64/app/client_component_publish.py +++ b/docker/x86_64/app/client_component_publish.py @@ -4,8 +4,8 @@ import os import argparse -url = os.environ.get('CBURL', u'ws://localhost:8080/ws') -realmv = os.environ.get('CBREALM', u'realm1') +url = os.environ.get('CBURL', 'ws://localhost:8080/ws') +realmv = os.environ.get('CBREALM', 'realm1') print(url, realmv) component = Component(transports=url, realm=realmv) @@ -17,7 +17,7 @@ def joined(session, details): counter = 0 while True: # publish() only returns a Deferred if we asked for an acknowledgement - session.publish(u'com.myapp.hello', "Hello World {0}".format(counter)) + session.publish('com.myapp.hello', "Hello World {0}".format(counter)) counter += 1 yield sleep(1) diff --git a/docker/x86_64/app/client_component_rpc_callee.py b/docker/x86_64/app/client_component_rpc_callee.py index 8226f278e..c6835de8e 100644 --- a/docker/x86_64/app/client_component_rpc_callee.py +++ b/docker/x86_64/app/client_component_rpc_callee.py @@ -5,8 +5,8 @@ import argparse import datetime -url = os.environ.get('CBURL', u'ws://localhost:8080/ws') -realmv = os.environ.get('CBREALM', u'realm1') +url = os.environ.get('CBURL', 'ws://localhost:8080/ws') +realmv = os.environ.get('CBREALM', 'realm1') print(url, realmv) component = Component(transports=url, realm=realmv) @@ -26,7 +26,7 @@ def utcnow(): return now.strftime("%Y-%m-%dT%H:%M:%SZ") try: - yield session.register(utcnow, u'com.myapp.date') + yield session.register(utcnow, 'com.myapp.date') print("procedure registered") except Exception as e: print("could not register procedure: {0}".format(e)) diff --git a/docker/x86_64/app/client_component_rpc_caller.py b/docker/x86_64/app/client_component_rpc_caller.py index 4916ead8e..c9bb06d4a 100644 --- a/docker/x86_64/app/client_component_rpc_caller.py +++ b/docker/x86_64/app/client_component_rpc_caller.py @@ -5,8 +5,8 @@ import argparse import datetime -url = os.environ.get('CBURL', u'ws://localhost:8080/ws') -realmv = os.environ.get('CBREALM', u'realm1') +url = os.environ.get('CBURL', 'ws://localhost:8080/ws') +realmv = os.environ.get('CBREALM', 'realm1') print(url, realmv) component = Component(transports=url, realm=realmv) @@ -16,7 +16,7 @@ def joined(session, details): print("session ready") try: - res = yield session.call(u'com.myapp.date') + res = yield session.call('com.myapp.date') print("\ncall result: {}\n".format(res)) except Exception as e: print("call error: {0}".format(e)) diff --git a/docker/x86_64/app/client_component_subscribe.py b/docker/x86_64/app/client_component_subscribe.py index 66e0d4140..e0622e9e9 100644 --- a/docker/x86_64/app/client_component_subscribe.py +++ b/docker/x86_64/app/client_component_subscribe.py @@ -3,8 +3,8 @@ from twisted.internet.defer import inlineCallbacks import os -url = os.environ.get('CBURL', u'ws://localhost:8080/ws') -realmvalue = os.environ.get('CBREALM', u'realm1') +url = os.environ.get('CBURL', 'ws://localhost:8080/ws') +realmvalue = os.environ.get('CBREALM', 'realm1') component = Component(transports=url, realm=realmvalue) @@ -17,7 +17,7 @@ def oncounter(count): print("event received: {0}", count) try: - yield session.subscribe(oncounter, u'com.myapp.hello') + yield session.subscribe(oncounter, 'com.myapp.hello') print("subscribed to topic") except Exception as e: print("could not subscribe to topic: {0}".format(e)) diff --git a/docker/x86_64/app/client_tx.py b/docker/x86_64/app/client_tx.py index 21cc60619..28954916e 100644 --- a/docker/x86_64/app/client_tx.py +++ b/docker/x86_64/app/client_tx.py @@ -14,7 +14,7 @@ class ClientSession(ApplicationSession): def onConnect(self): self.log.info("Client connected") - self.join(self.config.realm, [u'anonymous']) + self.join(self.config.realm, ['anonymous']) def onChallenge(self, challenge): self.log.info("Challenge for method {authmethod} received", authmethod=challenge.method) @@ -42,8 +42,8 @@ def onDisconnect(self): if __name__ == '__main__': # Crossbar.io connection configuration - url = os.environ.get('CBURL', u'ws://localhost:8080/ws') - realm = os.environ.get('CBREALM', u'realm1') + url = os.environ.get('CBURL', 'ws://localhost:8080/ws') + realm = os.environ.get('CBREALM', 'realm1') # parse command line parameters parser = argparse.ArgumentParser() @@ -61,7 +61,7 @@ def onDisconnect(self): # any extra info we want to forward to our ClientSession (in self.config.extra) extra = { - u'foobar': u'A custom value' + 'foobar': 'A custom value' } # now actually run a WAMP client using our session class ClientSession diff --git a/docs/conf.py b/docs/conf.py index ed4e90403..8675502b0 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -142,15 +142,15 @@ def autodoc_skip_member(app, what, name, obj, skip, options): master_doc = 'contents' # General information about the project. -project = u'autobahn' -author = u'Crossbar.io Project' -this_year = u'{0}'.format(time.strftime('%Y')) -if this_year != u'2012': - copyright = u'2012-{0}, Crossbar.io Technologies GmbH'.format(this_year) +project = 'autobahn' +author = 'Crossbar.io Project' +this_year = '{0}'.format(time.strftime('%Y')) +if this_year != '2012': + copyright = '2012-{0}, Crossbar.io Technologies GmbH'.format(this_year) else: - copyright = u'2012, Crossbar.io Technologies GmbH' + copyright = '2012, Crossbar.io Technologies GmbH' -# The version info for the project you're documenting, acts as replacement for +# The version info for the project yo're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # diff --git a/docs/listings/aio_complete.py b/docs/listings/aio_complete.py index 4eb7f0a0b..53b621185 100644 --- a/docs/listings/aio_complete.py +++ b/docs/listings/aio_complete.py @@ -11,30 +11,30 @@ # transports which both exist in the demo router transports=[ { - u"type": u"websocket", - u"url": u"ws://localhost:8080/auth_ws", - u"endpoint": { - u"type": u"tcp", - u"host": u"localhost", - u"port": 8080, + "type": "websocket", + "url": "ws://localhost:8080/auth_ws", + "endpoint": { + "type": "tcp", + "host": "localhost", + "port": 8080, }, # you can set various websocket options here if you want - u"options": { - u"open_handshake_timeout": 100, + "options": { + "open_handshake_timeout": 100, } }, ], # authentication can also be configured (this will only work on # the demo router on the first transport above) authentication={ - u"cryptosign": { - u'authid': u'alice', + "cryptosign": { + 'authid': 'alice', # this key should be loaded from disk, database etc never burned into code like this... - u'privkey': '6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c', + 'privkey': '6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c', } }, # must provide a realm - realm=u"crossbardemo", + realm="crossbardemo", ) @@ -43,13 +43,13 @@ async def join(session, details): print("joined {}: {}".format(session, details)) await sleep(1) print("Calling 'com.example'") - res = await session.call(u"example.foo", 42, something="nothing") + res = await session.call("example.foo", 42, something="nothing") print("Result: {}".format(res)) await session.leave() @component.register( - u"example.foo", + "example.foo", options=RegisterOptions(details_arg='details'), ) async def foo(*args, **kw): diff --git a/docs/listings/index.py b/docs/listings/index.py index 5d3ec2c42..9930ed833 100644 --- a/docs/listings/index.py +++ b/docs/listings/index.py @@ -5,20 +5,20 @@ demo = Component( transports=[ { - u"url": u"wss://demo.crossbar.io/ws", + "url": "wss://demo.crossbar.io/ws", } ], - realm=u"crossbardemo", + realm="crossbardemo", ) # 1. subscribe to a topic -@demo.subscribe(u'io.crossbar.demo.hello') +@demo.subscribe('io.crossbar.demo.hello') def hello(msg): print("Got hello: {}".format(msg)) # 2. register a procedure for remote calling -@demo.register(u'io.crossbar.demo.add2') +@demo.register('io.crossbar.demo.add2') def add2(x, y): return x + y diff --git a/docs/listings/programming.py b/docs/listings/programming.py index 714f8df13..038cccf21 100644 --- a/docs/listings/programming.py +++ b/docs/listings/programming.py @@ -12,30 +12,30 @@ # transports which both exist in the demo router transports=[ { - u"type": u"websocket", - u"url": u"ws://localhost:8080/auth_ws", - u"endpoint": { - u"type": u"tcp", - u"host": u"localhost", - u"port": 8080, + "type": "websocket", + "url": "ws://localhost:8080/auth_ws", + "endpoint": { + "type": "tcp", + "host": "localhost", + "port": 8080, }, # you can set various websocket options here if you want - u"options": { - u"open_handshake_timeout": 100, + "options": { + "open_handshake_timeout": 100, } }, ], # authentication can also be configured (this will only work on # the demo router on the first transport above) authentication={ - u"cryptosign": { - u'authid': u'alice', + "cryptosign": { + 'authid': 'alice', # this key should be loaded from disk, database etc never burned into code like this... - u'privkey': '6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c', + 'privkey': '6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c', } }, # must provide a realm - realm=u"crossbardemo", + realm="crossbardemo", ) @@ -45,13 +45,13 @@ def join(session, details): print("joined {}: {}".format(session, details)) yield sleep(1) print("Calling 'com.example'") - res = yield session.call(u"example.foo", 42, something="nothing") + res = yield session.call("example.foo", 42, something="nothing") print("Result: {}".format(res)) yield session.leave() @component.register( - u"example.foo", + "example.foo", options=RegisterOptions(details_arg='details'), ) @inlineCallbacks diff --git a/docs/listings/tx_complete.py b/docs/listings/tx_complete.py index 714f8df13..038cccf21 100644 --- a/docs/listings/tx_complete.py +++ b/docs/listings/tx_complete.py @@ -12,30 +12,30 @@ # transports which both exist in the demo router transports=[ { - u"type": u"websocket", - u"url": u"ws://localhost:8080/auth_ws", - u"endpoint": { - u"type": u"tcp", - u"host": u"localhost", - u"port": 8080, + "type": "websocket", + "url": "ws://localhost:8080/auth_ws", + "endpoint": { + "type": "tcp", + "host": "localhost", + "port": 8080, }, # you can set various websocket options here if you want - u"options": { - u"open_handshake_timeout": 100, + "options": { + "open_handshake_timeout": 100, } }, ], # authentication can also be configured (this will only work on # the demo router on the first transport above) authentication={ - u"cryptosign": { - u'authid': u'alice', + "cryptosign": { + 'authid': 'alice', # this key should be loaded from disk, database etc never burned into code like this... - u'privkey': '6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c', + 'privkey': '6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c', } }, # must provide a realm - realm=u"crossbardemo", + realm="crossbardemo", ) @@ -45,13 +45,13 @@ def join(session, details): print("joined {}: {}".format(session, details)) yield sleep(1) print("Calling 'com.example'") - res = yield session.call(u"example.foo", 42, something="nothing") + res = yield session.call("example.foo", 42, something="nothing") print("Result: {}".format(res)) yield session.leave() @component.register( - u"example.foo", + "example.foo", options=RegisterOptions(details_arg='details'), ) @inlineCallbacks diff --git a/docs/listings/webapp.py b/docs/listings/webapp.py index 66ffa97c3..e8ddab05c 100644 --- a/docs/listings/webapp.py +++ b/docs/listings/webapp.py @@ -23,7 +23,7 @@ def __init__(self, app, wamp_comp): self._wamp.on('join', self._initialize) self._wamp.on('leave', self._uninitialize) # hook up Klein routes - self._app.route(u"/", branch=True)(self._render_slash) + self._app.route("/", branch=True)(self._render_slash) def _initialize(self, session, details): print("Connected to WAMP router") @@ -38,15 +38,15 @@ def _render_slash(self, request): if self._session is None: request.setResponseCode(500) return b"No WAMP session\n" - self._session.publish(u"com.myapp.request_served") + self._session.publish("com.myapp.request_served") return b"Published to 'com.myapp.request_served'\n" @inlineCallbacks def main(reactor): component = Component( - transports=u"ws://localhost:8080/ws", - realm=u"crossbardemo", + transports="ws://localhost:8080/ws", + realm="crossbardemo", ) app = Klein() webapp = WebApplication(app, component) diff --git a/docs/websocket/programming.rst b/docs/websocket/programming.rst index 93805c912..9bacbc78b 100644 --- a/docs/websocket/programming.rst +++ b/docs/websocket/programming.rst @@ -193,11 +193,7 @@ Similar, here is the asyncio way if __name__ == '__main__': - try: - import asyncio - except ImportError: - ## Trollius >= 0.3 was renamed - import trollius as asyncio + import asyncio from autobahn.asyncio.websocket import WebSocketServerFactory factory = WebSocketServerFactory() @@ -471,12 +467,7 @@ Similar, here is the asyncio way :emphasize-lines: 9-11 if __name__ == '__main__': - - try: - import asyncio - except ImportError: - ## Trollius >= 0.3 was renamed - import trollius as asyncio + import asyncio from autobahn.asyncio.websocket import WebSocketClientFactory factory = WebSocketClientFactory() diff --git a/examples/asciinema-autobahn-demo.py b/examples/asciinema-autobahn-demo.py index a286b17bf..55e6539ef 100755 --- a/examples/asciinema-autobahn-demo.py +++ b/examples/asciinema-autobahn-demo.py @@ -51,7 +51,7 @@ def do_commands(lines): colors.red('# http://crossbar.io/autobahn example'), colors.red('# (Note there are many other examples to try)'), colors.red('#'), - colors.red("# I presume you've got a clone of https://github.com/crossbario/autobahn-python"), + colors.red("# I presume yo've got a clone of https://github.com/crossbario/autobahn-python"), colors.red("# in ~/autobahn-python"), "sleep 5", "clear", diff --git a/examples/asyncio/wamp/component/backend.py b/examples/asyncio/wamp/component/backend.py index 4e558dbd5..eaabb9cb6 100644 --- a/examples/asyncio/wamp/component/backend.py +++ b/examples/asyncio/wamp/component/backend.py @@ -15,7 +15,7 @@ transports=[ { "type": "websocket", - "url": u"wss://localhost:8083/ws", + "url": "wss://localhost:8083/ws", "endpoint": { "type": "tcp", "host": "localhost", @@ -27,7 +27,7 @@ } }, ], - realm=u"crossbardemo", + realm="crossbardemo", ) @@ -37,7 +37,7 @@ def join(session, details): @component.register( - u"example.foo", + "example.foo", options=RegisterOptions(details_arg='details'), ) @asyncio.coroutine diff --git a/examples/asyncio/wamp/component/frontend.py b/examples/asyncio/wamp/component/frontend.py index 581e89245..93d0c4831 100644 --- a/examples/asyncio/wamp/component/frontend.py +++ b/examples/asyncio/wamp/component/frontend.py @@ -11,42 +11,42 @@ def main(reactor, session): print("Client session={}".format(session)) try: - res = yield from session.register(lambda: None, u"com.foo.private") + res = yield from session.register(lambda: None, "com.foo.private") print("\n\nregistering 'com.foo.private' should have failed\n\n") except ApplicationError as e: print("registering 'com.foo.private' failed as expected: {}".format(e.error)) res = yield from session.register( - lambda: None, u"should.work", - options=RegisterOptions(match=u'exact'), + lambda: None, "should.work", + options=RegisterOptions(match='exact'), ) print("registered 'should.work' with id {}".format(res.id)) try: res = yield from session.register( - lambda: None, u"prefix.fail.", - options=RegisterOptions(match=u'prefix'), + lambda: None, "prefix.fail.", + options=RegisterOptions(match='prefix'), ) print("\n\nshould have failed\n\n") except ApplicationError as e: print("prefix-match 'prefix.fail.' failed as expected: {}".format(e.error)) print("calling 'example.foo'") - res = yield from session.call(u"example.foo") + res = yield from session.call("example.foo") print("example.foo() = {}".format(res)) print("done") component = Component( - transports=u"ws://localhost:8080/auth_ws", + transports="ws://localhost:8080/auth_ws", main=main, - realm=u"crossbardemo", + realm="crossbardemo", authentication={ - u"wampcra": { - u"authid": u"bob", - u"authrole": "dynamic_authed", - u"secret": u"p4ssw0rd", + "wampcra": { + "authid": "bob", + "authrole": "dynamic_authed", + "secret": "p4ssw0rd", } } ) diff --git a/examples/asyncio/wamp/overview/backend.py b/examples/asyncio/wamp/overview/backend.py index 50521bc16..158d8c0ab 100644 --- a/examples/asyncio/wamp/overview/backend.py +++ b/examples/asyncio/wamp/overview/backend.py @@ -10,19 +10,19 @@ async def onJoin(self, details): # this procedure if its connected to the same router and realm. def add2(x, y): return x + y - reg = await self.register(add2, u'com.myapp.add2') + reg = await self.register(add2, 'com.myapp.add2') print("registered 'com.myapp.add2' with id {}".format(reg.id)) # publish an event every second. The event payloads can be # anything JSON- and msgpack- serializable while True: - self.publish(u'com.myapp.hello', 'Hello, world!') + self.publish('com.myapp.hello', 'Hello, world!') await asyncio.sleep(1) if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws"), + "crossbardemo", ) runner.run(Component) diff --git a/examples/asyncio/wamp/overview/frontend.py b/examples/asyncio/wamp/overview/frontend.py index e1a06daeb..99b4f1f70 100644 --- a/examples/asyncio/wamp/overview/frontend.py +++ b/examples/asyncio/wamp/overview/frontend.py @@ -9,16 +9,16 @@ async def onJoin(self, details): # (any session that .publish()es to this topic). def onevent(msg): print("Got event: {}".format(msg)) - await self.subscribe(onevent, u'com.myapp.hello') + await self.subscribe(onevent, 'com.myapp.hello') # call a remote procedure. - res = await self.call(u'com.myapp.add2', 2, 3) + res = await self.call('com.myapp.add2', 2, 3) print("Got result: {}".format(res)) if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws"), + "crossbardemo", ) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/basic/backend.py b/examples/asyncio/wamp/pubsub/basic/backend.py index 79db0685a..0810907ee 100644 --- a/examples/asyncio/wamp/pubsub/basic/backend.py +++ b/examples/asyncio/wamp/pubsub/basic/backend.py @@ -38,13 +38,13 @@ async def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.topic1", counter) - self.publish(u'com.myapp.topic1', counter) + self.publish('com.myapp.topic1', counter) counter += 1 await asyncio.sleep(1) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/basic/frontend.py b/examples/asyncio/wamp/pubsub/basic/frontend.py index 3a188e93c..978ba896e 100644 --- a/examples/asyncio/wamp/pubsub/basic/frontend.py +++ b/examples/asyncio/wamp/pubsub/basic/frontend.py @@ -45,14 +45,14 @@ def on_event(i): if self.received > 5: self.leave() - await self.subscribe(on_event, u'com.myapp.topic1') + await self.subscribe(on_event, 'com.myapp.topic1') def onDisconnect(self): asyncio.get_event_loop().stop() if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/complex/backend.py b/examples/asyncio/wamp/pubsub/complex/backend.py index 2a1959fc6..c39060f3e 100644 --- a/examples/asyncio/wamp/pubsub/complex/backend.py +++ b/examples/asyncio/wamp/pubsub/complex/backend.py @@ -42,18 +42,18 @@ async def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.heartbeat") - self.publish(u'com.myapp.heartbeat') + self.publish('com.myapp.heartbeat') obj = {'counter': counter, 'foo': [1, 2, 3]} print("publish: com.myapp.topic2") - self.publish(u'com.myapp.topic2', random.randint(0, 100), 23, c="Hello", d=obj) + self.publish('com.myapp.topic2', random.randint(0, 100), 23, c="Hello", d=obj) counter += 1 await asyncio.sleep(1) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/complex/frontend.py b/examples/asyncio/wamp/pubsub/complex/frontend.py index 0358d8844..5a7450063 100644 --- a/examples/asyncio/wamp/pubsub/complex/frontend.py +++ b/examples/asyncio/wamp/pubsub/complex/frontend.py @@ -44,12 +44,12 @@ async def onJoin(self, details): def on_heartbeat(details=None): print("Got heartbeat (publication ID {})".format(details.publication)) - await self.subscribe(on_heartbeat, u'com.myapp.heartbeat', options=SubscribeOptions(details_arg='details')) + await self.subscribe(on_heartbeat, 'com.myapp.heartbeat', options=SubscribeOptions(details_arg='details')) def on_topic2(a, b, c=None, d=None): print("Got event: {} {} {} {}".format(a, b, c, d)) - await self.subscribe(on_topic2, u'com.myapp.topic2') + await self.subscribe(on_topic2, 'com.myapp.topic2') asyncio.get_event_loop().call_later(5, self.leave) def onDisconnect(self): @@ -57,7 +57,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/decorators/backend.py b/examples/asyncio/wamp/pubsub/decorators/backend.py index c6142b522..d459a9998 100644 --- a/examples/asyncio/wamp/pubsub/decorators/backend.py +++ b/examples/asyncio/wamp/pubsub/decorators/backend.py @@ -39,16 +39,16 @@ async def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.topic1", counter) - self.publish(u'com.myapp.topic1', counter) + self.publish('com.myapp.topic1', counter) print("publish: com.myapp.topic2 'Hello world.'") - self.publish(u'com.myapp.topic2', "Hello world.") + self.publish('com.myapp.topic2', "Hello world.") counter += 1 await asyncio.sleep(1) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/decorators/frontend.py b/examples/asyncio/wamp/pubsub/decorators/frontend.py index 82cc1b519..52053f861 100644 --- a/examples/asyncio/wamp/pubsub/decorators/frontend.py +++ b/examples/asyncio/wamp/pubsub/decorators/frontend.py @@ -51,14 +51,14 @@ async def onJoin(self, details): # res is an Failure instance print("Failed to subscribe handler: {}".format(res)) - @wamp.subscribe(u'com.myapp.topic1') + @wamp.subscribe('com.myapp.topic1') def onEvent1(self, i): print("Got event on topic1: {}".format(i)) self.received += 1 if self.received > 5: self.leave() - @wamp.subscribe(u'com.myapp.topic2') + @wamp.subscribe('com.myapp.topic2') def onEvent2(self, msg): print("Got event on topic2: {}".format(msg)) @@ -67,7 +67,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/options/backend.py b/examples/asyncio/wamp/pubsub/options/backend.py index 4852a7c38..e94fda4f5 100644 --- a/examples/asyncio/wamp/pubsub/options/backend.py +++ b/examples/asyncio/wamp/pubsub/options/backend.py @@ -40,11 +40,11 @@ async def onJoin(self, details): def on_event(i): print("Got event: {}".format(i)) - await self.subscribe(on_event, u'com.myapp.topic1') + await self.subscribe(on_event, 'com.myapp.topic1') counter = 0 while True: - publication = await self.publish(u'com.myapp.topic1', + publication = await self.publish('com.myapp.topic1', counter, options=PublishOptions(acknowledge=True, exclude_me=False)) print("Event published with publication ID {}".format(publication.id)) @@ -53,7 +53,7 @@ def on_event(i): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/options/frontend.py b/examples/asyncio/wamp/pubsub/options/frontend.py index 4156eb378..531446612 100644 --- a/examples/asyncio/wamp/pubsub/options/frontend.py +++ b/examples/asyncio/wamp/pubsub/options/frontend.py @@ -46,7 +46,7 @@ def on_event(i, details=None): if self.received > 5: self.leave() - await self.subscribe(on_event, u'com.myapp.topic1', + await self.subscribe(on_event, 'com.myapp.topic1', options=SubscribeOptions(details_arg='details')) def onDisconnect(self): @@ -54,7 +54,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/tls/backend_selfsigned.py b/examples/asyncio/wamp/pubsub/tls/backend_selfsigned.py index 41b8bc9bd..225dbc205 100644 --- a/examples/asyncio/wamp/pubsub/tls/backend_selfsigned.py +++ b/examples/asyncio/wamp/pubsub/tls/backend_selfsigned.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - import asyncio from os import environ from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner @@ -41,7 +39,7 @@ async def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.topic1", counter) - self.publish(u'com.myapp.topic1', counter) + self.publish('com.myapp.topic1', counter) counter += 1 await asyncio.sleep(1) @@ -54,8 +52,8 @@ async def onJoin(self, details): options = ssl.create_default_context(cadata=open(cert_path, 'r').read()) # ...which we pass as "ssl=" to ApplicationRunner (passed to loop.create_connection) runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"wss://127.0.0.1:8083/ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "wss://127.0.0.1:8083/ws"), + "crossbardemo", ssl=options, # try removing this, but still use self-signed cert ) runner.run(Component) diff --git a/examples/asyncio/wamp/pubsub/unsubscribe/backend.py b/examples/asyncio/wamp/pubsub/unsubscribe/backend.py index 8192f6bae..e7c58fef3 100644 --- a/examples/asyncio/wamp/pubsub/unsubscribe/backend.py +++ b/examples/asyncio/wamp/pubsub/unsubscribe/backend.py @@ -38,6 +38,6 @@ async def onJoin(self, details): counter = 0 while True: - self.publish(u'com.myapp.topic1', counter) + self.publish('com.myapp.topic1', counter) counter += 1 await asyncio.sleep(1) diff --git a/examples/asyncio/wamp/pubsub/unsubscribe/frontend.py b/examples/asyncio/wamp/pubsub/unsubscribe/frontend.py index 46cb9c37d..159e63900 100644 --- a/examples/asyncio/wamp/pubsub/unsubscribe/frontend.py +++ b/examples/asyncio/wamp/pubsub/unsubscribe/frontend.py @@ -55,7 +55,7 @@ async def on_event(i): await asyncio.sleep(5) await self.test() - self.subscription = await self.subscribe(on_event, u'com.myapp.topic1') + self.subscription = await self.subscribe(on_event, 'com.myapp.topic1') print("Subscribed with subscription ID {}".format(self.subscription.id)) async def onJoin(self, details): @@ -67,7 +67,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rawsocket/backend.py b/examples/asyncio/wamp/rawsocket/backend.py index 0a7376f60..b5c02fe53 100644 --- a/examples/asyncio/wamp/rawsocket/backend.py +++ b/examples/asyncio/wamp/rawsocket/backend.py @@ -19,12 +19,12 @@ async def onJoin(self, details): def add2(x, y): log.debug('add2 called with %s %s', x, y) return x + y - await self.register(add2, u'com.myapp.add2') + await self.register(add2, 'com.myapp.add2') # publish an event every second. The event payloads can be # anything JSON- and msgpack- serializable while True: - self.publish(u'com.myapp.hello', 'Hello, world! Time is %s' % datetime.utcnow()) + self.publish('com.myapp.hello', 'Hello, world! Time is %s' % datetime.utcnow()) log.debug('Published msg') await asyncio.sleep(1) @@ -36,6 +36,6 @@ def add2(x, y): path = os.path.join(os.path.dirname(__file__), '.crossbar/socket1') runner = ApplicationRunnerRawSocket( path, - u"realm1", + "realm1", ) runner.run(MyComponent, logging_level=level) diff --git a/examples/asyncio/wamp/rawsocket/frontend.py b/examples/asyncio/wamp/rawsocket/frontend.py index 1dc0fa18f..da7824623 100644 --- a/examples/asyncio/wamp/rawsocket/frontend.py +++ b/examples/asyncio/wamp/rawsocket/frontend.py @@ -17,13 +17,13 @@ async def onJoin(self, details): # (any session that .publish()es to this topic). def onevent(msg): log.info("Got event: {}".format(msg)) - await self.subscribe(onevent, u'com.myapp.hello') + await self.subscribe(onevent, 'com.myapp.hello') # call a remote procedure. count = 0 while True: try: - res = await self.call(u'com.myapp.add2', count, count+1) + res = await self.call('com.myapp.add2', count, count+1) log.info("Got result: {}".format(res)) except ApplicationError: pass @@ -38,5 +38,5 @@ def onevent(msg): level = 'debug' runner = ApplicationRunnerRawSocket( "tcp://localhost:9090", - u"realm1") + "realm1") runner.run(MyComponent, logging_level=level) diff --git a/examples/asyncio/wamp/rpc/arguments/backend.py b/examples/asyncio/wamp/rpc/arguments/backend.py index e2808ca54..bd970c375 100644 --- a/examples/asyncio/wamp/rpc/arguments/backend.py +++ b/examples/asyncio/wamp/rpc/arguments/backend.py @@ -44,25 +44,25 @@ def add2(a, b): return a + b def stars(nick="somebody", stars=0): - return u"{} starred {}x".format(nick, stars) + return "{} starred {}x".format(nick, stars) # noinspection PyUnusedLocal def orders(product, limit=5): - return [u"Product {}".format(i) for i in range(50)][:limit] + return ["Product {}".format(i) for i in range(50)][:limit] def arglen(*args, **kwargs): return [len(args), len(kwargs)] - await self.register(ping, u'com.arguments.ping') - await self.register(add2, u'com.arguments.add2') - await self.register(stars, u'com.arguments.stars') - await self.register(orders, u'com.arguments.orders') - await self.register(arglen, u'com.arguments.arglen') + await self.register(ping, 'com.arguments.ping') + await self.register(add2, 'com.arguments.add2') + await self.register(stars, 'com.arguments.stars') + await self.register(orders, 'com.arguments.orders') + await self.register(arglen, 'com.arguments.arglen') print("Registered methods; ready for frontend.") if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/arguments/frontend.py b/examples/asyncio/wamp/rpc/arguments/frontend.py index 285a59b1d..1dbba051a 100644 --- a/examples/asyncio/wamp/rpc/arguments/frontend.py +++ b/examples/asyncio/wamp/rpc/arguments/frontend.py @@ -36,40 +36,40 @@ class Component(ApplicationSession): async def onJoin(self, details): - await self.call(u'com.arguments.ping') + await self.call('com.arguments.ping') print("Pinged!") - res = await self.call(u'com.arguments.add2', 2, 3) + res = await self.call('com.arguments.add2', 2, 3) print("Add2: {}".format(res)) - starred = await self.call(u'com.arguments.stars') + starred = await self.call('com.arguments.stars') print("Starred 1: {}".format(starred)) - starred = await self.call(u'com.arguments.stars', nick=u'Homer') + starred = await self.call('com.arguments.stars', nick='Homer') print("Starred 2: {}".format(starred)) - starred = await self.call(u'com.arguments.stars', stars=5) + starred = await self.call('com.arguments.stars', stars=5) print("Starred 3: {}".format(starred)) - starred = await self.call(u'com.arguments.stars', nick=u'Homer', stars=5) + starred = await self.call('com.arguments.stars', nick='Homer', stars=5) print("Starred 4: {}".format(starred)) - orders = await self.call(u'com.arguments.orders', u'coffee') + orders = await self.call('com.arguments.orders', 'coffee') print("Orders 1: {}".format(orders)) - orders = await self.call(u'com.arguments.orders', u'coffee', limit=10) + orders = await self.call('com.arguments.orders', 'coffee', limit=10) print("Orders 2: {}".format(orders)) - arglengths = await self.call(u'com.arguments.arglen') + arglengths = await self.call('com.arguments.arglen') print("Arglen 1: {}".format(arglengths)) - arglengths = await self.call(u'com.arguments.arglen', 1, 2, 3) + arglengths = await self.call('com.arguments.arglen', 1, 2, 3) print("Arglen 1: {}".format(arglengths)) - arglengths = await self.call(u'com.arguments.arglen', a=1, b=2, c=3) + arglengths = await self.call('com.arguments.arglen', a=1, b=2, c=3) print("Arglen 2: {}".format(arglengths)) - arglengths = await self.call(u'com.arguments.arglen', 1, 2, 3, a=1, b=2, c=3) + arglengths = await self.call('com.arguments.arglen', 1, 2, 3, a=1, b=2, c=3) print("Arglen 3: {}".format(arglengths)) self.leave() @@ -79,7 +79,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/complex/backend.py b/examples/asyncio/wamp/rpc/complex/backend.py index c9210b8e3..4a002d901 100644 --- a/examples/asyncio/wamp/rpc/complex/backend.py +++ b/examples/asyncio/wamp/rpc/complex/backend.py @@ -41,17 +41,17 @@ async def onJoin(self, details): def add_complex(a, ai, b, bi): return CallResult(c=a + b, ci=ai + bi) - await self.register(add_complex, u'com.myapp.add_complex') + await self.register(add_complex, 'com.myapp.add_complex') def split_name(fullname): forename, surname = fullname.split() return CallResult(forename, surname) - await self.register(split_name, u'com.myapp.split_name') + await self.register(split_name, 'com.myapp.split_name') if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/complex/frontend.py b/examples/asyncio/wamp/rpc/complex/frontend.py index fe66b638f..6b72cb0e4 100644 --- a/examples/asyncio/wamp/rpc/complex/frontend.py +++ b/examples/asyncio/wamp/rpc/complex/frontend.py @@ -38,10 +38,10 @@ class Component(ApplicationSession): async def onJoin(self, details): - res = await self.call(u'com.myapp.add_complex', 2, 3, 4, 5) + res = await self.call('com.myapp.add_complex', 2, 3, 4, 5) print("Result: {} + {}i".format(res.kwresults['c'], res.kwresults['ci'])) - res = await self.call(u'com.myapp.split_name', 'Homer Simpson') + res = await self.call('com.myapp.split_name', 'Homer Simpson') print("Forname: {}, Surname: {}".format(res.results[0], res.results[1])) self.leave() @@ -51,7 +51,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/decorators/backend.py b/examples/asyncio/wamp/rpc/decorators/backend.py index 82b36af5d..90a9db625 100644 --- a/examples/asyncio/wamp/rpc/decorators/backend.py +++ b/examples/asyncio/wamp/rpc/decorators/backend.py @@ -51,15 +51,15 @@ async def onJoin(self, details): # res is an Failure instance print("Failed to register procedure: {}".format(res)) - @wamp.register(u'com.mathservice.add2') + @wamp.register('com.mathservice.add2') def add2(self, x, y): return x + y - @wamp.register(u'com.mathservice.mul2') + @wamp.register('com.mathservice.mul2') def mul2(self, x, y): return x * y - @wamp.register(u'com.mathservice.div2') + @wamp.register('com.mathservice.div2') def square(self, x, y): if y: return float(x) / float(y) @@ -68,7 +68,7 @@ def square(self, x, y): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/decorators/frontend.py b/examples/asyncio/wamp/rpc/decorators/frontend.py index 51346c875..f16018ac1 100644 --- a/examples/asyncio/wamp/rpc/decorators/frontend.py +++ b/examples/asyncio/wamp/rpc/decorators/frontend.py @@ -36,9 +36,9 @@ class Component(ApplicationSession): async def onJoin(self, details): - procs = [u'com.mathservice.add2', - u'com.mathservice.mul2', - u'com.mathservice.div2'] + procs = ['com.mathservice.add2', + 'com.mathservice.mul2', + 'com.mathservice.div2'] try: for proc in procs: @@ -54,7 +54,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/errors/backend.py b/examples/asyncio/wamp/rpc/errors/backend.py index 9822f8009..055073875 100644 --- a/examples/asyncio/wamp/rpc/errors/backend.py +++ b/examples/asyncio/wamp/rpc/errors/backend.py @@ -33,7 +33,7 @@ from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner -@wamp.error(u"com.myapp.error1") +@wamp.error("com.myapp.error1") class AppError1(Exception): """ An application specific exception that is decorated with a WAMP URI, @@ -57,23 +57,23 @@ def sqrt(x): # this also will raise, if x < 0 return math.sqrt(x) - await self.register(sqrt, u'com.myapp.sqrt') + await self.register(sqrt, 'com.myapp.sqrt') # raising WAMP application exceptions ## def checkname(name): if name in ['foo', 'bar']: - raise ApplicationError(u"com.myapp.error.reserved") + raise ApplicationError("com.myapp.error.reserved") if name.lower() != name.upper(): # forward positional arguments in exceptions - raise ApplicationError(u"com.myapp.error.mixed_case", name.lower(), name.upper()) + raise ApplicationError("com.myapp.error.mixed_case", name.lower(), name.upper()) if len(name) < 3 or len(name) > 10: # forward keyword arguments in exceptions - raise ApplicationError(u"com.myapp.error.invalid_length", min=3, max=10) + raise ApplicationError("com.myapp.error.invalid_length", min=3, max=10) - await self.register(checkname, u'com.myapp.checkname') + await self.register(checkname, 'com.myapp.checkname') # defining and automapping WAMP application exceptions ## @@ -83,11 +83,11 @@ def compare(a, b): if a < b: raise AppError1(b - a) - await self.register(compare, u'com.myapp.compare') + await self.register(compare, 'com.myapp.compare') if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/errors/frontend.py b/examples/asyncio/wamp/rpc/errors/frontend.py index b220997bf..a5950b984 100644 --- a/examples/asyncio/wamp/rpc/errors/frontend.py +++ b/examples/asyncio/wamp/rpc/errors/frontend.py @@ -33,7 +33,7 @@ from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner -@wamp.error(u"com.myapp.error1") +@wamp.error("com.myapp.error1") class AppError1(Exception): """ An application specific exception that is decorated with a WAMP URI, @@ -52,7 +52,7 @@ async def onJoin(self, details): ## for x in [2, 0, -2]: try: - res = await self.call(u'com.myapp.sqrt', x) + res = await self.call('com.myapp.sqrt', x) except Exception as e: print("Error: {} {}".format(e, e.args)) else: @@ -62,7 +62,7 @@ async def onJoin(self, details): ## for name in ['foo', 'a', '*' * 11, 'Hello']: try: - res = await self.call(u'com.myapp.checkname', name) + res = await self.call('com.myapp.checkname', name) except ApplicationError as e: print("Error: {} {} {} {}".format(e, e.error, e.args, e.kwargs)) else: @@ -73,7 +73,7 @@ async def onJoin(self, details): self.define(AppError1) try: - await self.call(u'com.myapp.compare', 3, 17) + await self.call('com.myapp.compare', 3, 17) except AppError1 as e: print("Compare Error: {}".format(e)) @@ -84,7 +84,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/options/backend.py b/examples/asyncio/wamp/rpc/options/backend.py index fab45674a..ec1b7f2a6 100644 --- a/examples/asyncio/wamp/rpc/options/backend.py +++ b/examples/asyncio/wamp/rpc/options/backend.py @@ -42,20 +42,20 @@ def square(val, details=None): print("square called from: {}".format(details.caller)) if val < 0: - self.publish(u'com.myapp.square_on_nonpositive', val) + self.publish('com.myapp.square_on_nonpositive', val) elif val == 0: if details.caller: options = PublishOptions(exclude=[details.caller]) else: options = None - self.publish(u'com.myapp.square_on_nonpositive', val, options=options) + self.publish('com.myapp.square_on_nonpositive', val, options=options) return val * val - await self.register(square, u'com.myapp.square', RegisterOptions(details_arg='details')) + await self.register(square, 'com.myapp.square', RegisterOptions(details_arg='details')) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/options/frontend.py b/examples/asyncio/wamp/rpc/options/frontend.py index fa30bfa2d..6ef0eb68b 100644 --- a/examples/asyncio/wamp/rpc/options/frontend.py +++ b/examples/asyncio/wamp/rpc/options/frontend.py @@ -40,10 +40,10 @@ async def onJoin(self, details): def on_event(val): print("Someone requested to square non-positive: {}".format(val)) - await self.subscribe(on_event, u'com.myapp.square_on_nonpositive') + await self.subscribe(on_event, 'com.myapp.square_on_nonpositive') for val in [2, 0, -2]: - res = await self.call(u'com.myapp.square', val, options=CallOptions()) + res = await self.call('com.myapp.square', val, options=CallOptions()) print("Squared {} = {}".format(val, res)) await self.leave() @@ -53,7 +53,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/progress/backend.py b/examples/asyncio/wamp/rpc/progress/backend.py index 47d313ee8..201e8d63f 100644 --- a/examples/asyncio/wamp/rpc/progress/backend.py +++ b/examples/asyncio/wamp/rpc/progress/backend.py @@ -46,11 +46,11 @@ async def longop(n, details=None): await asyncio.sleep(1 * n) return n - await self.register(longop, u'com.myapp.longop', RegisterOptions(details_arg='details')) + await self.register(longop, 'com.myapp.longop', RegisterOptions(details_arg='details')) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/progress/frontend.py b/examples/asyncio/wamp/rpc/progress/frontend.py index ebf99bd86..cae4b2153 100644 --- a/examples/asyncio/wamp/rpc/progress/frontend.py +++ b/examples/asyncio/wamp/rpc/progress/frontend.py @@ -40,7 +40,7 @@ async def onJoin(self, details): def on_progress(i): print("Progress: {}".format(i)) - res = await self.call(u'com.myapp.longop', 3, options=CallOptions(on_progress=on_progress)) + res = await self.call('com.myapp.longop', 3, options=CallOptions(on_progress=on_progress)) print("Final: {}".format(res)) @@ -51,7 +51,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/slowsquare/backend.py b/examples/asyncio/wamp/rpc/slowsquare/backend.py index 757fbb173..119c134fe 100644 --- a/examples/asyncio/wamp/rpc/slowsquare/backend.py +++ b/examples/asyncio/wamp/rpc/slowsquare/backend.py @@ -39,18 +39,18 @@ async def onJoin(self, details): def square(x): return x * x - await self.register(square, u'com.math.square') + await self.register(square, 'com.math.square') async def slowsquare(x, delay=1): await asyncio.sleep(delay) return x * x - await self.register(slowsquare, u'com.math.slowsquare') + await self.register(slowsquare, 'com.math.slowsquare') print("Registered com.math.slowsquare") if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/slowsquare/frontend.py b/examples/asyncio/wamp/rpc/slowsquare/frontend.py index 95400e58c..ae190e1a3 100644 --- a/examples/asyncio/wamp/rpc/slowsquare/frontend.py +++ b/examples/asyncio/wamp/rpc/slowsquare/frontend.py @@ -46,11 +46,11 @@ def got(started, msg, f): print("{}: {} in {}".format(msg, res, duration)) t1 = time.clock() - d1 = self.call(u'com.math.slowsquare', 3, 2) + d1 = self.call('com.math.slowsquare', 3, 2) d1.add_done_callback(partial(got, t1, "Slow Square")) t2 = time.clock() - d2 = self.call(u'com.math.square', 3) + d2 = self.call('com.math.square', 3) d2.add_done_callback(partial(got, t2, "Quick Square")) await asyncio.gather(d1, d2) @@ -62,7 +62,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/timeservice/backend.py b/examples/asyncio/wamp/rpc/timeservice/backend.py index c75727f7a..3eb914329 100644 --- a/examples/asyncio/wamp/rpc/timeservice/backend.py +++ b/examples/asyncio/wamp/rpc/timeservice/backend.py @@ -42,11 +42,11 @@ def utcnow(): now = datetime.datetime.utcnow() return now.strftime("%Y-%m-%dT%H:%M:%SZ") - await self.register(utcnow, u'com.timeservice.now') + await self.register(utcnow, 'com.timeservice.now') if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/rpc/timeservice/frontend.py b/examples/asyncio/wamp/rpc/timeservice/frontend.py index 74db4c4ae..d76c13a35 100644 --- a/examples/asyncio/wamp/rpc/timeservice/frontend.py +++ b/examples/asyncio/wamp/rpc/timeservice/frontend.py @@ -38,7 +38,7 @@ class Component(ApplicationSession): async def onJoin(self, details): try: - now = await self.call(u'com.timeservice.now') + now = await self.call('com.timeservice.now') except Exception as e: print("Error: {}".format(e)) else: @@ -51,7 +51,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/asyncio/wamp/session/series/backend.py b/examples/asyncio/wamp/session/series/backend.py index cedb122ab..4f850a5b8 100644 --- a/examples/asyncio/wamp/session/series/backend.py +++ b/examples/asyncio/wamp/session/series/backend.py @@ -41,4 +41,4 @@ def utcnow(): now = datetime.datetime.utcnow() return now.strftime("%Y-%m-%dT%H:%M:%SZ") - self.register(utcnow, u'com.timeservice.now') + self.register(utcnow, 'com.timeservice.now') diff --git a/examples/asyncio/wamp/session/series/frontend.py b/examples/asyncio/wamp/session/series/frontend.py index 199b0c1bf..c12d1406a 100644 --- a/examples/asyncio/wamp/session/series/frontend.py +++ b/examples/asyncio/wamp/session/series/frontend.py @@ -45,7 +45,7 @@ async def onJoin(self, details): print("Realm joined (WAMP session started).") try: - now = await self.call(u'com.timeservice.now') + now = await self.call('com.timeservice.now') except Exception as e: print("Error: {}".format(e)) else: @@ -57,7 +57,7 @@ def onLeave(self, details): print("Realm left (WAMP session ended).") self.count += 1 if self.count < 3: - self.join(u"realm1") + self.join("realm1") else: self.disconnect() diff --git a/examples/asyncio/websocket/echo/client.py b/examples/asyncio/websocket/echo/client.py index f82ced1cc..a353bf825 100644 --- a/examples/asyncio/websocket/echo/client.py +++ b/examples/asyncio/websocket/echo/client.py @@ -24,6 +24,8 @@ # ############################################################################### +import asyncio + from autobahn.asyncio.websocket import WebSocketClientProtocol, \ WebSocketClientFactory @@ -41,7 +43,7 @@ def onOpen(self): print("WebSocket connection open.") def hello(): - self.sendMessage(u"Hello, world!".encode('utf8')) + self.sendMessage("Hello, world!".encode('utf8')) self.sendMessage(b"\x00\x01\x03\x04", isBinary=True) self.factory.loop.call_later(1, hello) @@ -59,14 +61,7 @@ def onClose(self, wasClean, code, reason): if __name__ == '__main__': - - try: - import asyncio - except ImportError: - # Trollius >= 0.3 was renamed - import trollius as asyncio - - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = MyClientProtocol loop = asyncio.get_event_loop() diff --git a/examples/asyncio/websocket/echo/client_coroutines.py b/examples/asyncio/websocket/echo/client_coroutines.py index 0e0a9e533..39944a5c0 100644 --- a/examples/asyncio/websocket/echo/client_coroutines.py +++ b/examples/asyncio/websocket/echo/client_coroutines.py @@ -24,14 +24,11 @@ # ############################################################################### +import asyncio + from autobahn.asyncio.websocket import WebSocketClientProtocol, \ WebSocketClientFactory -try: - import asyncio -except ImportError: - import trollius as asyncio - class MyClientProtocol(WebSocketClientProtocol): @@ -43,7 +40,7 @@ async def onOpen(self): # start sending messages every second .. while True: - self.sendMessage(u"Hello, world!".encode('utf8')) + self.sendMessage("Hello, world!".encode('utf8')) self.sendMessage(b"\x00\x01\x03\x04", isBinary=True) await asyncio.sleep(1) @@ -59,7 +56,7 @@ def onClose(self, wasClean, code, reason): if __name__ == '__main__': - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = MyClientProtocol loop = asyncio.get_event_loop() diff --git a/examples/asyncio/websocket/echo/client_coroutines_py2.py b/examples/asyncio/websocket/echo/client_coroutines_py2.py deleted file mode 100644 index 3532c8d34..000000000 --- a/examples/asyncio/websocket/echo/client_coroutines_py2.py +++ /dev/null @@ -1,67 +0,0 @@ -############################################################################### -# -# The MIT License (MIT) -# -# Copyright (c) Crossbar.io Technologies GmbH -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -############################################################################### - -from autobahn.asyncio.websocket import WebSocketClientProtocol, \ - WebSocketClientFactory - -import trollius - - -class MyClientProtocol(WebSocketClientProtocol): - - def onConnect(self, response): - print("Server connected: {0}".format(response.peer)) - - @trollius.coroutine - def onOpen(self): - print("WebSocket connection open.") - - # start sending messages every second .. - while True: - self.sendMessage(u"Hello, world!".encode('utf8')) - self.sendMessage(b"\x00\x01\x03\x04", isBinary=True) - yield trollius.sleep(1) - - def onMessage(self, payload, isBinary): - if isBinary: - print("Binary message received: {0} bytes".format(len(payload))) - else: - print("Text message received: {0}".format(payload.decode('utf8'))) - - def onClose(self, wasClean, code, reason): - print("WebSocket connection closed: {0}".format(reason)) - - -if __name__ == '__main__': - - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") - factory.protocol = MyClientProtocol - - loop = trollius.get_event_loop() - coro = loop.create_connection(factory, '127.0.0.1', 9000) - loop.run_until_complete(coro) - loop.run_forever() - loop.close() diff --git a/examples/asyncio/websocket/echo/server.py b/examples/asyncio/websocket/echo/server.py index 0815a6158..d36b89033 100644 --- a/examples/asyncio/websocket/echo/server.py +++ b/examples/asyncio/websocket/echo/server.py @@ -24,6 +24,8 @@ # ############################################################################### +import asyncio + from autobahn.asyncio.websocket import WebSocketServerProtocol, \ WebSocketServerFactory @@ -50,9 +52,7 @@ def onClose(self, wasClean, code, reason): if __name__ == '__main__': - import asyncio - - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = MyServerProtocol loop = asyncio.get_event_loop() diff --git a/examples/asyncio/websocket/slowsquare/client.py b/examples/asyncio/websocket/slowsquare/client.py index 1c12b2966..89d56791c 100644 --- a/examples/asyncio/websocket/slowsquare/client.py +++ b/examples/asyncio/websocket/slowsquare/client.py @@ -24,6 +24,8 @@ # ############################################################################### +import asyncio + from autobahn.asyncio.websocket import WebSocketClientProtocol, \ WebSocketClientFactory @@ -51,9 +53,7 @@ def onClose(self, wasClean, code, reason): if __name__ == '__main__': - import asyncio - - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = SlowSquareClientProtocol loop = asyncio.get_event_loop() diff --git a/examples/asyncio/websocket/slowsquare/server.py b/examples/asyncio/websocket/slowsquare/server.py index 03cc0a4e3..3e905a057 100644 --- a/examples/asyncio/websocket/slowsquare/server.py +++ b/examples/asyncio/websocket/slowsquare/server.py @@ -24,11 +24,12 @@ # ############################################################################### -from autobahn.asyncio.websocket import WebSocketServerProtocol, \ - WebSocketServerFactory import asyncio import json +from autobahn.asyncio.websocket import WebSocketServerProtocol, \ + WebSocketServerFactory + class SlowSquareServerProtocol(WebSocketServerProtocol): @@ -52,7 +53,7 @@ async def onMessage(self, payload, isBinary): if __name__ == '__main__': - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = SlowSquareServerProtocol loop = asyncio.get_event_loop() diff --git a/examples/asyncio/websocket/slowsquare/server_py2.py b/examples/asyncio/websocket/slowsquare/server_py2.py deleted file mode 100644 index 142b80cdf..000000000 --- a/examples/asyncio/websocket/slowsquare/server_py2.py +++ /dev/null @@ -1,71 +0,0 @@ -############################################################################### -# -# The MIT License (MIT) -# -# Copyright (c) Crossbar.io Technologies GmbH -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -############################################################################### - -from autobahn.asyncio.websocket import WebSocketServerProtocol, \ - WebSocketServerFactory - -import json -import trollius - - -class SlowSquareServerProtocol(WebSocketServerProtocol): - - @trollius.coroutine - def slowsquare(self, x): - if x > 5: - raise Exception("number too large") - else: - yield trollius.sleep(1) - raise trollius.Return(x * x) - - @trollius.coroutine - def onMessage(self, payload, isBinary): - if not isBinary: - x = json.loads(payload.decode('utf8')) - try: - res = yield self.slowsquare(x) - except Exception as e: - self.sendClose(1000, "Exception raised: {0}".format(e)) - else: - self.sendMessage(json.dumps(res).encode('utf8')) - - -if __name__ == '__main__': - - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") - factory.protocol = SlowSquareServerProtocol - - loop = trollius.get_event_loop() - coro = loop.create_server(factory, '127.0.0.1', 9000) - server = loop.run_until_complete(coro) - - try: - loop.run_forever() - except KeyboardInterrupt: - pass - finally: - server.close() - loop.close() diff --git a/examples/run-all-examples.py b/examples/run-all-examples.py index c0b894608..9f2293839 100755 --- a/examples/run-all-examples.py +++ b/examples/run-all-examples.py @@ -1,7 +1,5 @@ #!/usr/bin/env python -from __future__ import print_function - # this is mostly for testing that the examples run without errors # # To use this script: diff --git a/examples/twisted/wamp/app/calculator/calculator.py b/examples/twisted/wamp/app/calculator/calculator.py index 186c49cb6..c6452779d 100644 --- a/examples/twisted/wamp/app/calculator/calculator.py +++ b/examples/twisted/wamp/app/calculator/calculator.py @@ -42,13 +42,13 @@ def onJoin(self, details): yield self.register(self) print("Ok, calculator procedures registered!") - @wamp.register(u'com.example.calculator.clear') + @wamp.register('com.example.calculator.clear') def clear(self, arg=None): self.op = None self.current = decimal.Decimal(0) return str(self.current) - @wamp.register(u'com.example.calculator.calc') + @wamp.register('com.example.calculator.calc') def calc(self, op, num): num = decimal.Decimal(num) if self.op: @@ -97,7 +97,7 @@ def calc(self, op, num): from autobahn.twisted.wamp import ApplicationRunner runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws"), + "crossbardemo", ) runner.run(Calculator) diff --git a/examples/twisted/wamp/app/crochet/example1/server.py b/examples/twisted/wamp/app/crochet/example1/server.py index 67c35b580..6954bc397 100644 --- a/examples/twisted/wamp/app/crochet/example1/server.py +++ b/examples/twisted/wamp/app/crochet/example1/server.py @@ -55,7 +55,7 @@ def publish(topic, *args, **kwargs): @app.route('/') def index(): app._visits += 1 - publish(u'com.example.on_visit', app._visits, msg="hello from flask") + publish('com.example.on_visit', app._visits, msg="hello from flask") return "Visit {}".format(app._visits) @@ -69,7 +69,7 @@ def index(): # @run_in_reactor def start_wamp(): - wapp.run(u"ws://127.0.0.1:8080/ws", u"realm1", start_reactor=False) + wapp.run("ws://127.0.0.1:8080/ws", "realm1", start_reactor=False) start_wamp() diff --git a/examples/twisted/wamp/app/crochet/example2/server.py b/examples/twisted/wamp/app/crochet/example2/server.py index 4844a7c03..c9195f949 100644 --- a/examples/twisted/wamp/app/crochet/example2/server.py +++ b/examples/twisted/wamp/app/crochet/example2/server.py @@ -40,13 +40,13 @@ wapp = Application() -@wapp.register(u'com.example.square') +@wapp.register('com.example.square') def square(x): print("square() called with {}".format(x)) return x * x -@wapp.register(u'com.example.slowsquare') +@wapp.register('com.example.slowsquare') def slowsquare(x): print("slowsquare() called with {}".format(x)) yield sleep(2) @@ -57,12 +57,12 @@ def slowsquare(x): # @wait_for(timeout=1) def call_square(x): - return wapp.session.call(u'com.example.square', x) + return wapp.session.call('com.example.square', x) @wait_for(timeout=5) def call_slowsquare(x): - return wapp.session.call(u'com.example.slowsquare', x) + return wapp.session.call('com.example.slowsquare', x) # our Flask app @@ -94,7 +94,7 @@ def slowsquare_submit(): # @run_in_reactor def start_wamp(): - wapp.run(u"ws://127.0.0.1:9000", u"realm1", standalone=True, start_reactor=False) + wapp.run("ws://127.0.0.1:9000", "realm1", standalone=True, start_reactor=False) start_wamp() diff --git a/examples/twisted/wamp/app/dbus/bridge.py b/examples/twisted/wamp/app/dbus/bridge.py index 6ce14b7bd..88b16a11f 100644 --- a/examples/twisted/wamp/app/dbus/bridge.py +++ b/examples/twisted/wamp/app/dbus/bridge.py @@ -49,7 +49,7 @@ def onJoin(self, details): print("Dbus notifier subscribed") @inlineCallbacks - @wamp.subscribe(u'com.example.dbus.on_notify') + @wamp.subscribe('com.example.dbus.on_notify') def onNotify(self, title, body, duration=2): print("Notification received: title = '{}', body = '{}', duration = {}".format(title, body, duration)) @@ -108,9 +108,9 @@ def onNotify(self, title, body, duration=2): # run WAMP application component from autobahn.twisted.wamp import ApplicationRunner - router = args.router or u'ws://127.0.0.1:9000' + router = args.router or 'ws://127.0.0.1:9000' - runner = ApplicationRunner(router, u"realm1", standalone=not args.router) + runner = ApplicationRunner(router, "realm1", standalone=not args.router) # start the component and the Twisted reactor .. runner.run(DbusNotifier) diff --git a/examples/twisted/wamp/app/hello/hello.py b/examples/twisted/wamp/app/hello/hello.py index b851c6f3f..bbbf216a5 100644 --- a/examples/twisted/wamp/app/hello/hello.py +++ b/examples/twisted/wamp/app/hello/hello.py @@ -29,7 +29,7 @@ from autobahn.twisted.wamp import Application -app = Application(u'com.example') +app = Application('com.example') @app.register() @@ -38,10 +38,10 @@ def add2(a, b): return a + b -@app.register(u'com.example.hello') +@app.register('com.example.hello') def hello(): print("hello() called") - res = yield app.session.call(u'com.example.add2', 2, 3) + res = yield app.session.call('com.example.add2', 2, 3) returnValue("Hello {}".format(res)) @@ -52,6 +52,6 @@ def onjoined(): if __name__ == "__main__": app.run( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws"), + "crossbardemo", ) diff --git a/examples/twisted/wamp/app/keyvalue/store.py b/examples/twisted/wamp/app/keyvalue/store.py index ce7166964..676d348d7 100644 --- a/examples/twisted/wamp/app/keyvalue/store.py +++ b/examples/twisted/wamp/app/keyvalue/store.py @@ -44,7 +44,7 @@ def onJoin(self, details): yield self.register(self) print("Ok, keyvalue-store procedures registered!") - @wamp.register(u"com.example.keyvalue.set") + @wamp.register("com.example.keyvalue.set") def set(self, key=None, value=None): if key is not None: k = str(key) @@ -57,7 +57,7 @@ def set(self, key=None, value=None): self.store.clear() self.store.sync() - @wamp.register(u"com.example.keyvalue.get") + @wamp.register("com.example.keyvalue.get") def get(self, key=None): if key is None: res = {} @@ -67,7 +67,7 @@ def get(self, key=None): else: return self.store.get(str(key), None) - @wamp.register(u"com.example.keyvalue.keys") + @wamp.register("com.example.keyvalue.keys") def keys(self): return self.store.keys() @@ -103,9 +103,9 @@ def keys(self): # run WAMP application component from autobahn.twisted.wamp import ApplicationRunner - router = args.router or u'ws://127.0.0.1:9000' + router = args.router or 'ws://127.0.0.1:9000' - runner = ApplicationRunner(router, u"realm1", standalone=not args.router) + runner = ApplicationRunner(router, "realm1", standalone=not args.router) # start the component and the Twisted reactor .. runner.run(KeyValueStore) diff --git a/examples/twisted/wamp/app/klein/example1/server_wamp.py b/examples/twisted/wamp/app/klein/example1/server_wamp.py index 226441c89..df6eb90f9 100644 --- a/examples/twisted/wamp/app/klein/example1/server_wamp.py +++ b/examples/twisted/wamp/app/klein/example1/server_wamp.py @@ -29,11 +29,11 @@ app = Application() -@app.register(u'com.example.square') +@app.register('com.example.square') def square(x): print("square() called with {}".format(x)) return x * x if __name__ == "__main__": - app.run(u"ws://127.0.0.1:9000", u"realm1", standalone=True) + app.run("ws://127.0.0.1:9000", "realm1", standalone=True) diff --git a/examples/twisted/wamp/app/klein/example1/server_web.py b/examples/twisted/wamp/app/klein/example1/server_web.py index ab6de2332..9ae885be2 100644 --- a/examples/twisted/wamp/app/klein/example1/server_web.py +++ b/examples/twisted/wamp/app/klein/example1/server_web.py @@ -36,7 +36,7 @@ @inlineCallbacks def square_submit(request): x = int(request.args.get('x', [0])[0]) - res = yield wampapp.session.call(u'com.example.square', x) + res = yield wampapp.session.call('com.example.square', x) returnValue("{} squared is {}".format(x, res)) @@ -48,4 +48,4 @@ def square_submit(request): log.startLogging(sys.stdout) reactor.listenTCP(8080, Site(app.resource())) - wampapp.run(u"ws://127.0.0.1:9000", u"realm1", standalone=False) + wampapp.run("ws://127.0.0.1:9000", "realm1", standalone=False) diff --git a/examples/twisted/wamp/app/klein/example2/server.py b/examples/twisted/wamp/app/klein/example2/server.py index 8f31aa195..8a46eb12b 100644 --- a/examples/twisted/wamp/app/klein/example2/server.py +++ b/examples/twisted/wamp/app/klein/example2/server.py @@ -33,7 +33,7 @@ # This is our WAMP application ## -wampapp = Application(u'com.example') +wampapp = Application('com.example') @wampapp.register() @@ -52,7 +52,7 @@ def square(x): @webapp.route('/') def home(request): webapp.visits += 1 - wampapp.session.publish(u'com.example.onvisit', visits=webapp.visits) + wampapp.session.publish('com.example.onvisit', visits=webapp.visits) page = webapp.templates.get_template('index.html') return page.render(visits=webapp.visits) @@ -60,7 +60,7 @@ def home(request): @webapp.route('/square/') @inlineCallbacks def square(request, x): - result = yield wampapp.session.call(u'com.example.square', x) + result = yield wampapp.session.call('com.example.square', x) page = webapp.templates.get_template('result.html') content = page.render(x=x, result=result) returnValue(content) @@ -80,4 +80,4 @@ def square_submit(request): log.startLogging(sys.stdout) reactor.listenTCP(8080, Site(webapp.resource())) - wampapp.run(u"ws://127.0.0.1:9000", u"realm1", standalone=True) + wampapp.run("ws://127.0.0.1:9000", "realm1", standalone=True) diff --git a/examples/twisted/wamp/app/serial2ws/serial2ws.py b/examples/twisted/wamp/app/serial2ws/serial2ws.py index b7f03c6a1..5129da63d 100644 --- a/examples/twisted/wamp/app/serial2ws/serial2ws.py +++ b/examples/twisted/wamp/app/serial2ws/serial2ws.py @@ -56,10 +56,10 @@ def lineReceived(self, line): print('Unable to parse value {0}'.format(line)) else: # create payload for WAMP event - payload = {u'id': data[0], u'value': data[1]} + payload = {'id': data[0], 'value': data[1]} # publish WAMP event to all subscribers on topic - self.session.publish(u"com.myapp.mcu.on_analog_value", payload) + self.session.publish("com.myapp.mcu.on_analog_value", payload) def controlLed(self, turnOn): """ @@ -95,7 +95,7 @@ def onJoin(self, details): print('Could not open serial port: {0}'.format(e)) self.leave() else: - yield self.register(serialProtocol.controlLed, u"com.myapp.mcu.control_led") + yield self.register(serialProtocol.controlLed, "com.myapp.mcu.control_led") if __name__ == '__main__': @@ -109,17 +109,17 @@ def onJoin(self, details): parser.add_argument("--baudrate", type=int, default=9600, choices=[300, 1200, 2400, 4800, 9600, 19200, 57600, 115200], help='Serial port baudrate.') - parser.add_argument("--port", type=str, default=u'/dev/ttyACM0', + parser.add_argument("--port", type=str, default='/dev/ttyACM0', help='Serial port to use (e.g. 3 for a COM port on Windows, /dev/ttyATH0 for Arduino Yun, /dev/ttyACM0 for Serial-over-USB on RaspberryPi.') parser.add_argument("--web", type=int, default=8000, help='Web port to use for embedded Web server. Use 0 to disable.') - router_default = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") + router_default = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") parser.add_argument("--router", type=str, default=router_default, help='WAMP router URL (a WAMP-over-WebSocket endpoint, default: "{}")'.format(router_default)) - parser.add_argument("--realm", type=str, default=u'crossbardemo', + parser.add_argument("--realm", type=str, default='crossbardemo', help='WAMP realm to join (default: "crossbardemo")') args = parser.parse_args() diff --git a/examples/twisted/wamp/app/subscribe_upon_call/subscribe_upon_call.py b/examples/twisted/wamp/app/subscribe_upon_call/subscribe_upon_call.py index cd8a0db9b..10b84e3ad 100644 --- a/examples/twisted/wamp/app/subscribe_upon_call/subscribe_upon_call.py +++ b/examples/twisted/wamp/app/subscribe_upon_call/subscribe_upon_call.py @@ -34,10 +34,10 @@ def onEvent(msg): print("got event: {}".format(msg)) -@app.register(u'com.example.triggersubscribe') +@app.register('com.example.triggersubscribe') def triggerSubscribe(): print("triggersubscribe() called") - yield app.session.subscribe(onEvent, u'com.example.topic1') + yield app.session.subscribe(onEvent, 'com.example.topic1') @app.signal('onjoined') @@ -46,4 +46,4 @@ def onjoined(): if __name__ == "__main__": - app.run(u"ws://127.0.0.1:8080/ws", u"realm1", standalone=True) + app.run("ws://127.0.0.1:8080/ws", "realm1", standalone=True) diff --git a/examples/twisted/wamp/auth/backend.py b/examples/twisted/wamp/auth/backend.py index 864c99342..ea4e7054f 100644 --- a/examples/twisted/wamp/auth/backend.py +++ b/examples/twisted/wamp/auth/backend.py @@ -43,14 +43,14 @@ def onJoin(self, details): if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/auth_ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), + "crossbardemo", ) def make(config): session = Component(config) session.add_authenticator( - u"wampcra", authid=u'username', secret=u'p4ssw0rd' + "wampcra", authid='username', secret='p4ssw0rd' ) return session runner.run(make) diff --git a/examples/twisted/wamp/auth/backend_salted.py b/examples/twisted/wamp/auth/backend_salted.py index a0105ffde..3842ba00e 100644 --- a/examples/twisted/wamp/auth/backend_salted.py +++ b/examples/twisted/wamp/auth/backend_salted.py @@ -35,8 +35,8 @@ # this is (one way) to get the encoded/salted secret to put in # config.json (see examples/router/.crossbar/config.json) print("encoded secret:", auth.derive_key( - secret=u's33kr1t', - salt=u'salt123', + secret='s33kr1t', + salt='salt123', iterations=100, keylen=32, ).decode('ascii')) @@ -54,14 +54,14 @@ def onJoin(self, details): if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/auth_ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), + "crossbardemo", ) def make(config): session = Component(config) session.add_authenticator( - u"wampcra", authid=u'salted', secret=u's33kr1t' + "wampcra", authid='salted', secret='s33kr1t' ) return session runner.run(make) diff --git a/examples/twisted/wamp/auth/frontend.py b/examples/twisted/wamp/auth/frontend.py index b40e17c30..926c52d07 100644 --- a/examples/twisted/wamp/auth/frontend.py +++ b/examples/twisted/wamp/auth/frontend.py @@ -43,16 +43,16 @@ def onJoin(self, details): if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/auth_ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), + "crossbardemo", ) def make(config): session = Component(config) session.add_authenticator( - u'cryptosign', - authid=u'alice', - privkey=u'6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c', + 'cryptosign', + authid='alice', + privkey='6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c', ) return session runner.run(make) diff --git a/examples/twisted/wamp/basic/client_using_apprunner.py b/examples/twisted/wamp/basic/client_using_apprunner.py index e9cde6b43..b23dade5d 100644 --- a/examples/twisted/wamp/basic/client_using_apprunner.py +++ b/examples/twisted/wamp/basic/client_using_apprunner.py @@ -34,10 +34,10 @@ def onChallenge(self, challenge): def onJoin(self, details): self.log.info('session joined: {}'.format(details)) - yield self.register(add2, u'com.example.add2') + yield self.register(add2, 'com.example.add2') for i in range(10): - res = yield self.call(u'com.example.add2', 23, i * self._countdown) + res = yield self.call('com.example.add2', 23, i * self._countdown) self.log.info('result: {}'.format(res)) yield self.leave() @@ -63,22 +63,22 @@ def onDisconnect(self): # create a WAMP session object. this is reused across multiple # reconnects (if automatically reconnected) - session = MyAppSession(ComponentConfig(u'crossbardemo', {})) + session = MyAppSession(ComponentConfig('crossbardemo', {})) # use WAMP-over-RawSocket - # runner = ApplicationRunner(u'rs://localhost:8080', u'crossbardemo') + # runner = ApplicationRunner('rs://localhost:8080', 'crossbardemo') # alternatively, use WAMP-over-Unix-socket runner = ApplicationRunner( - u'ws://localhost:8080', - u'crossbardemo', + 'ws://localhost:8080', + 'crossbardemo', ) # alternatively, use WAMP-over-WebSocket plain (standalone, not hooked in under Twisted Web) - #runner = ApplicationRunner(u'ws://localhost:8080/ws', u'crossbardemo') + #runner = ApplicationRunner('ws://localhost:8080/ws', 'crossbardemo') # alternatively, use WAMP-over-WebSocket running under Twisted Web (as a web resource) - # runner = ApplicationRunner(u'ws://localhost:8080/twws', u'crossbardemo') + # runner = ApplicationRunner('ws://localhost:8080/twws', 'crossbardemo') runner.run( session, diff --git a/examples/twisted/wamp/basic/client_using_clientservice.py b/examples/twisted/wamp/basic/client_using_clientservice.py index e22b1473e..c6d1e8f07 100644 --- a/examples/twisted/wamp/basic/client_using_clientservice.py +++ b/examples/twisted/wamp/basic/client_using_clientservice.py @@ -34,10 +34,10 @@ def onChallenge(self, challenge): def onJoin(self, details): self.log.info('session joined: {}'.format(details)) - yield self.register(add2, u'com.example.add2') + yield self.register(add2, 'com.example.add2') for i in range(10): - res = yield self.call(u'com.example.add2', 23, i) + res = yield self.call('com.example.add2', 23, i) self.log.info('result: {}'.format(res)) yield self.leave() @@ -63,10 +63,10 @@ def onDisconnect(self): # create a WAMP session object. this is reused across multiple # reconnects (if automatically reconnected) - session = MyAppSession(ComponentConfig(u'realm1', {})) + session = MyAppSession(ComponentConfig('realm1', {})) # create a WAMP transport factory - transport = WampWebSocketClientFactory(session, url=u'ws://localhost:8080/ws') + transport = WampWebSocketClientFactory(session, url='ws://localhost:8080/ws') # create a connecting endpoint endpoint = TCP4ClientEndpoint(reactor, 'localhost', 8080) diff --git a/examples/twisted/wamp/component/backend.py b/examples/twisted/wamp/component/backend.py index edaaf1612..92a720000 100644 --- a/examples/twisted/wamp/component/backend.py +++ b/examples/twisted/wamp/component/backend.py @@ -25,31 +25,31 @@ else: cert = Certificate.loadPEM(open(cert_fname, 'r').read()) options = optionsForClientTLS( - hostname=u'localhost', + hostname='localhost', trustRoot=cert, ) component = Component( transports=[ { - u"type": u"websocket", - u"url": u"ws://localhost:8080/ws", - u"endpoint": { - u"type": u"tcp", - u"host": u"localhost", - u"port": 8080, + "type": "websocket", + "url": "ws://localhost:8080/ws", + "endpoint": { + "type": "tcp", + "host": "localhost", + "port": 8080, # "tls": options, # "tls": { -# u"hostname": u"localhost", -# u"trust_root": cert_fname, +# "hostname": "localhost", +# "trust_root": cert_fname, # }, }, - u"options": { - u"open_handshake_timeout": 100, + "options": { + "open_handshake_timeout": 100, } }, ], - realm=u"crossbardemo", + realm="crossbardemo", ) @@ -59,7 +59,7 @@ def join(session, details): @component.register( - u"example.foo", + "example.foo", options=RegisterOptions(details_arg='details'), ) @inlineCallbacks diff --git a/examples/twisted/wamp/component/frontend.py b/examples/twisted/wamp/component/frontend.py index d64fe46c8..21881dc8d 100644 --- a/examples/twisted/wamp/component/frontend.py +++ b/examples/twisted/wamp/component/frontend.py @@ -11,42 +11,42 @@ def main(reactor, session): print("Client session={}".format(session)) try: - res = yield session.register(lambda: None, u"com.foo.private") + res = yield session.register(lambda: None, "com.foo.private") print("\n\nregistering 'com.foo.private' should have failed\n\n") except ApplicationError as e: print("registering 'com.foo.private' failed as expected: {}".format(e.error)) res = yield session.register( - lambda: None, u"should.work", - options=RegisterOptions(match=u'exact'), + lambda: None, "should.work", + options=RegisterOptions(match='exact'), ) print("registered 'should.work' with id {}".format(res.id)) try: res = yield session.register( - lambda: None, u"prefix.fail.", - options=RegisterOptions(match=u'prefix'), + lambda: None, "prefix.fail.", + options=RegisterOptions(match='prefix'), ) print("\n\nshould have failed\n\n") except ApplicationError as e: print("prefix-match 'prefix.fail.' failed as expected: {}".format(e.error)) print("calling 'example.foo'") - res = yield session.call(u"example.foo") + res = yield session.call("example.foo") print("example.foo() = {}".format(res)) print("done") component = Component( - transports=u"ws://localhost:8080/auth_ws", + transports="ws://localhost:8080/auth_ws", main=main, - realm=u"crossbardemo", + realm="crossbardemo", authentication={ - u"wampcra": { - u"authid": u"bob", - u"authrole": u"dynamic_authed", - u"secret": u"p4ssw0rd", + "wampcra": { + "authid": "bob", + "authrole": "dynamic_authed", + "secret": "p4ssw0rd", } } ) diff --git a/examples/twisted/wamp/component/frontend_cancel.py b/examples/twisted/wamp/component/frontend_cancel.py index 27b9ba8c0..ef6cfc5a9 100644 --- a/examples/twisted/wamp/component/frontend_cancel.py +++ b/examples/twisted/wamp/component/frontend_cancel.py @@ -9,7 +9,7 @@ @inlineCallbacks def main(reactor, session): print("Client session={}".format(session)) - d = session.call(u"example.foo", "some", "args") + d = session.call("example.foo", "some", "args") print("Called 'example.foo': {}".format(d)) print("cancel()-ing the above Deferred") @@ -24,9 +24,9 @@ def main(reactor, session): component = Component( - transports=u"ws://localhost:8080/auth_ws", + transports="ws://localhost:8080/auth_ws", main=main, - realm=u"crossbardemo", + realm="crossbardemo", ) diff --git a/examples/twisted/wamp/component/frontend_scram.py b/examples/twisted/wamp/component/frontend_scram.py index eb01d565b..5ea1b06ce 100644 --- a/examples/twisted/wamp/component/frontend_scram.py +++ b/examples/twisted/wamp/component/frontend_scram.py @@ -7,14 +7,14 @@ component = Component( - transports=u"ws://localhost:8080/auth_ws", - realm=u"crossbardemo", + transports="ws://localhost:8080/auth_ws", + realm="crossbardemo", authentication={ - u"scram": { - u"authid": u"carol", - u"authrole": u"authenticated", - u"password": u"p4ssw0rd", - u"kdf": u"argon2id13", + "scram": { + "authid": "carol", + "authrole": "authenticated", + "password": "p4ssw0rd", + "kdf": "argon2id13", } } ) diff --git a/examples/twisted/wamp/meta/backend.py b/examples/twisted/wamp/meta/backend.py index 99f8918e5..fab1a6b24 100644 --- a/examples/twisted/wamp/meta/backend.py +++ b/examples/twisted/wamp/meta/backend.py @@ -44,19 +44,19 @@ def onJoin(self, details): while True: counter += 1 - pub = yield self.publish(u'event.foo.{}'.format(counter), "some data") + pub = yield self.publish('event.foo.{}'.format(counter), "some data") print("published {}".format(pub)) yield sleep(1) - sub = yield self.subscribe(lambda: None, u'event.sub_{}'.format(counter)) + sub = yield self.subscribe(lambda: None, 'event.sub_{}'.format(counter)) print("subscribed {sub.id}".format(sub=sub)) yield sleep(1) - reg = yield self.register(lambda: 42, u'event.rpc.test_{}'.format(counter)) + reg = yield self.register(lambda: 42, 'event.rpc.test_{}'.format(counter)) print("registered {reg.id}".format(reg=reg)) yield sleep(1) - call = yield self.call(u'event.rpc.test_{}'.format(counter)) + call = yield self.call('event.rpc.test_{}'.format(counter)) print("called {}".format(call)) yield sleep(1) @@ -66,7 +66,7 @@ def onJoin(self, details): if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/auth_ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), + "crossbardemo", ) runner.run(Component) diff --git a/examples/twisted/wamp/meta/meta_listener.py b/examples/twisted/wamp/meta/meta_listener.py index ed2927f9a..4b63a5817 100644 --- a/examples/twisted/wamp/meta/meta_listener.py +++ b/examples/twisted/wamp/meta/meta_listener.py @@ -46,21 +46,21 @@ def got_meta(*args, **kw): details = kw.pop('details') print("meta: '{}' args={}, kw={}".format(details.topic, args, kw)) yield self.subscribe( - got_meta, u'', - options=SubscribeOptions(match=u'prefix', details_arg='details'), + got_meta, '', + options=SubscribeOptions(match='prefix', details_arg='details'), ) if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/auth_ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), + "crossbardemo", ) def make(config): session = Component(config) session.add_authenticator( - u"wampcra", authid=u'username', secret=u'p4ssw0rd' + "wampcra", authid='username', secret='p4ssw0rd' ) return session runner.run(make) diff --git a/examples/twisted/wamp/overview/backend.py b/examples/twisted/wamp/overview/backend.py index 3ea10d108..9530eb77f 100644 --- a/examples/twisted/wamp/overview/backend.py +++ b/examples/twisted/wamp/overview/backend.py @@ -11,7 +11,7 @@ def onJoin(self, details): # publish an event every second. The event payloads can be # anything JSON- and msgpack- serializable def publish(): - return self.publish(u'com.myapp.hello', 'Hello, world!') + return self.publish('com.myapp.hello', 'Hello, world!') LoopingCall(publish).start(1) # a remote procedure; see frontend.py for a Python front-end @@ -19,11 +19,11 @@ def publish(): # this procedure if its connected to the same router and realm. def add2(x, y): return x + y - yield self.register(add2, u'com.myapp.add2') + yield self.register(add2, 'com.myapp.add2') if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/overview/frontend.py b/examples/twisted/wamp/overview/frontend.py index a418e72b0..4e8c1f585 100644 --- a/examples/twisted/wamp/overview/frontend.py +++ b/examples/twisted/wamp/overview/frontend.py @@ -11,15 +11,15 @@ def onJoin(self, details): # (any session that .publish()es to this topic). def onevent(msg): print("Got event: {}".format(msg)) - yield self.subscribe(onevent, u'com.myapp.hello') + yield self.subscribe(onevent, 'com.myapp.hello') # call a remote procedure. - res = yield self.call(u'com.myapp.add2', 2, 3) + res = yield self.call('com.myapp.add2', 2, 3) print("Got result: {}".format(res)) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/basic/backend.py b/examples/twisted/wamp/pubsub/basic/backend.py index f7b56710b..7d5a81ef4 100644 --- a/examples/twisted/wamp/pubsub/basic/backend.py +++ b/examples/twisted/wamp/pubsub/basic/backend.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import print_function from os import environ from twisted.internet.defer import inlineCallbacks @@ -44,13 +43,13 @@ def onJoin(self, details): counter = 0 while True: print('backend publishing com.myapp.topic1', counter) - self.publish(u'com.myapp.topic1', counter) + self.publish('com.myapp.topic1', counter) counter += 1 yield sleep(1) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/basic/frontend.py b/examples/twisted/wamp/pubsub/basic/frontend.py index f817f1d9a..43b4c19d0 100644 --- a/examples/twisted/wamp/pubsub/basic/frontend.py +++ b/examples/twisted/wamp/pubsub/basic/frontend.py @@ -24,7 +24,6 @@ # ############################################################################### -from __future__ import print_function from os import environ from twisted.internet import reactor @@ -43,7 +42,7 @@ class Component(ApplicationSession): def onJoin(self, details): print("session attached") self.received = 0 - sub = yield self.subscribe(self.on_event, u'com.myapp.topic1') + sub = yield self.subscribe(self.on_event, 'com.myapp.topic1') print("Subscribed to com.myapp.topic1 with {}".format(sub.id)) def on_event(self, i): @@ -61,8 +60,8 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" extra=dict( max_events=5, # [A] pass in additional configuration ) diff --git a/examples/twisted/wamp/pubsub/complex/backend.py b/examples/twisted/wamp/pubsub/complex/backend.py index e13bf3435..d946e5901 100644 --- a/examples/twisted/wamp/pubsub/complex/backend.py +++ b/examples/twisted/wamp/pubsub/complex/backend.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - import random from os import environ @@ -48,11 +46,11 @@ def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.heartbeat") - self.publish(u'com.myapp.heartbeat') + self.publish('com.myapp.heartbeat') obj = {'counter': counter, 'foo': [1, 2, 3]} print("publish: com.myapp.topic2", obj) - self.publish(u'com.myapp.topic2', random.randint(0, 100), 23, + self.publish('com.myapp.topic2', random.randint(0, 100), 23, c="Hello", d=obj) counter += 1 @@ -60,7 +58,7 @@ def onJoin(self, details): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/complex/frontend.py b/examples/twisted/wamp/pubsub/complex/frontend.py index d31a323a2..664ee423b 100644 --- a/examples/twisted/wamp/pubsub/complex/frontend.py +++ b/examples/twisted/wamp/pubsub/complex/frontend.py @@ -50,14 +50,14 @@ def on_heartbeat(details=None): print("heartbeat (publication ID {})".format(details.publication)) yield self.subscribe( - on_heartbeat, u'com.myapp.heartbeat', + on_heartbeat, 'com.myapp.heartbeat', options=SubscribeOptions(details_arg='details') ) def on_topic2(a, b, c=None, d=None): print("Got event: {} {} {} {}".format(a, b, c, d)) - yield self.subscribe(on_topic2, u'com.myapp.topic2') + yield self.subscribe(on_topic2, 'com.myapp.topic2') reactor.callLater(5, self.leave) @@ -67,7 +67,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/decorators/backend.py b/examples/twisted/wamp/pubsub/decorators/backend.py index c661fccd8..d2737a67b 100644 --- a/examples/twisted/wamp/pubsub/decorators/backend.py +++ b/examples/twisted/wamp/pubsub/decorators/backend.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - from os import environ from twisted.internet.defer import inlineCallbacks @@ -45,17 +43,17 @@ def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.topic1", counter) - self.publish(u'com.myapp.topic1', counter) + self.publish('com.myapp.topic1', counter) print("publish: com.myapp.topic2") - self.publish(u'com.myapp.topic2', "Hello world.") + self.publish('com.myapp.topic2', "Hello world.") counter += 1 yield sleep(1) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/decorators/frontend.py b/examples/twisted/wamp/pubsub/decorators/frontend.py index 2b7727820..454124379 100644 --- a/examples/twisted/wamp/pubsub/decorators/frontend.py +++ b/examples/twisted/wamp/pubsub/decorators/frontend.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - from os import environ from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks @@ -55,11 +53,11 @@ def onJoin(self, details): if isinstance(sub, Failure): print("subscribe failed:", sub.getErrorMessage()) - @wamp.subscribe(u'com.myapp.topic1') + @wamp.subscribe('com.myapp.topic1') def onEvent1(self, i): print("Got event on topic1: {}".format(i)) - @wamp.subscribe(u'com.myapp.topic2') + @wamp.subscribe('com.myapp.topic2') def onEvent2(self, msg): print("Got event on topic2: {}".format(msg)) @@ -69,7 +67,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/options/backend.py b/examples/twisted/wamp/pubsub/options/backend.py index 0d0df60a1..dc1022518 100644 --- a/examples/twisted/wamp/pubsub/options/backend.py +++ b/examples/twisted/wamp/pubsub/options/backend.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - from os import environ from twisted.internet.defer import inlineCallbacks @@ -46,7 +44,7 @@ def onJoin(self, details): def on_event(i): print("Got event: {}".format(i)) - yield self.subscribe(on_event, u'com.myapp.topic1') + yield self.subscribe(on_event, 'com.myapp.topic1') counter = 0 while True: @@ -56,7 +54,7 @@ def on_event(i): exclude_me=False ) publication = yield self.publish( - u'com.myapp.topic1', counter, + 'com.myapp.topic1', counter, options=pub_options, ) print("Published with publication ID {}".format(publication.id)) @@ -65,7 +63,7 @@ def on_event(i): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/options/frontend.py b/examples/twisted/wamp/pubsub/options/frontend.py index 27a4523eb..61e50a1f3 100644 --- a/examples/twisted/wamp/pubsub/options/frontend.py +++ b/examples/twisted/wamp/pubsub/options/frontend.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - from os import environ from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks @@ -54,7 +52,7 @@ def on_event(i, details=None): if self.received > 5: self.leave() - yield self.subscribe(on_event, u'com.myapp.topic1', + yield self.subscribe(on_event, 'com.myapp.topic1', options=SubscribeOptions(details_arg='details')) def onDisconnect(self): @@ -63,7 +61,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/retained/backend.py b/examples/twisted/wamp/pubsub/retained/backend.py index c40d55213..a690636a1 100644 --- a/examples/twisted/wamp/pubsub/retained/backend.py +++ b/examples/twisted/wamp/pubsub/retained/backend.py @@ -42,7 +42,7 @@ class Component(Session): def onJoin(self, details): print("session attached {}".format(details)) - for topic in [u"com.example.history", u"com.example.no_history_here"]: + for topic in ["com.example.history", "com.example.no_history_here"]: print("publishing '{}' as retained event".format(topic)) pub = yield self.publish( topic, "some data, topic was '{}'".format(topic), @@ -53,7 +53,7 @@ def onJoin(self, details): if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/auth_ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), + "crossbardemo", ) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/retained/frontend.py b/examples/twisted/wamp/pubsub/retained/frontend.py index da75a0b43..b19980ac8 100644 --- a/examples/twisted/wamp/pubsub/retained/frontend.py +++ b/examples/twisted/wamp/pubsub/retained/frontend.py @@ -48,7 +48,7 @@ def got_event(*args, **kw): # note: we're relying on 'com.example.history' (the one with # event-history enabled) being last so that "pub" has the # right ID for wamp.subscription.get_events after the loop - for topic in [u"com.example.no_history_here", u"com.example.history"]: + for topic in ["com.example.no_history_here", "com.example.history"]: print("subscribing to '{}'".format(topic)) pub = yield self.subscribe( got_event, topic, @@ -56,7 +56,7 @@ def got_event(*args, **kw): ) print("id={}".format(pub.id)) - events = yield self.call(u"wamp.subscription.get_events", pub.id) + events = yield self.call("wamp.subscription.get_events", pub.id) print("Using the WAMP Meta API:") print("wamp.subscription.get_events {}: {}".format(pub.id, len(events))) for event in events: @@ -65,7 +65,7 @@ def got_event(*args, **kw): if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/auth_ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), + "crossbardemo", ) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/tls/backend_selfsigned.py b/examples/twisted/wamp/pubsub/tls/backend_selfsigned.py index 8a9f1b478..53427d2af 100644 --- a/examples/twisted/wamp/pubsub/tls/backend_selfsigned.py +++ b/examples/twisted/wamp/pubsub/tls/backend_selfsigned.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - from os import environ from os.path import join, split @@ -48,7 +46,7 @@ def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.topic1", counter) - yield self.publish(u'com.myapp.topic1', counter) + yield self.publish('com.myapp.topic1', counter) counter += 1 yield sleep(1) @@ -67,8 +65,8 @@ def onJoin(self, details): ) # ...which we pass as "ssl=" to ApplicationRunner (passed to SSL4ClientEndpoint) runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"wss://127.0.0.1:8083/ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "wss://127.0.0.1:8083/ws"), + "crossbardemo", ssl=options, # try removing this, but still use self-signed cert ) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/unsubscribe/backend.py b/examples/twisted/wamp/pubsub/unsubscribe/backend.py index 1e9e13026..a32c77d23 100644 --- a/examples/twisted/wamp/pubsub/unsubscribe/backend.py +++ b/examples/twisted/wamp/pubsub/unsubscribe/backend.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - from os import environ from twisted.internet.defer import inlineCallbacks @@ -45,13 +43,13 @@ def onJoin(self, details): counter = 0 while True: print("publish: com.myapp.topic1", counter) - self.publish(u'com.myapp.topic1', counter) + self.publish('com.myapp.topic1', counter) counter += 1 yield sleep(1) if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/pubsub/unsubscribe/frontend.py b/examples/twisted/wamp/pubsub/unsubscribe/frontend.py index c2f385003..37dacbdfd 100644 --- a/examples/twisted/wamp/pubsub/unsubscribe/frontend.py +++ b/examples/twisted/wamp/pubsub/unsubscribe/frontend.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import print_function - from os import environ from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks @@ -43,7 +41,7 @@ class Component(ApplicationSession): @inlineCallbacks def test(self): self.received = 0 - self.sub = yield self.subscribe(self.on_event, u'com.myapp.topic1') + self.sub = yield self.subscribe(self.on_event, 'com.myapp.topic1') print("Subscribed with subscription ID {}".format(self.sub.id)) @inlineCallbacks @@ -71,7 +69,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/arguments/backend.py b/examples/twisted/wamp/rpc/arguments/backend.py index f09c5aa52..4ec6a75ad 100644 --- a/examples/twisted/wamp/rpc/arguments/backend.py +++ b/examples/twisted/wamp/rpc/arguments/backend.py @@ -47,24 +47,24 @@ def add2(a, b): return a + b def stars(nick="somebody", stars=0): - return u"{} starred {}x".format(nick, stars) + return "{} starred {}x".format(nick, stars) def orders(product, limit=5): - return [u"Product {}".format(i) for i in range(50)][:limit] + return ["Product {}".format(i) for i in range(50)][:limit] def arglen(*args, **kwargs): return [len(args), len(kwargs)] - yield self.register(ping, u'com.arguments.ping') - yield self.register(add2, u'com.arguments.add2') - yield self.register(stars, u'com.arguments.stars') - yield self.register(orders, u'com.arguments.orders') - yield self.register(arglen, u'com.arguments.arglen') + yield self.register(ping, 'com.arguments.ping') + yield self.register(add2, 'com.arguments.add2') + yield self.register(stars, 'com.arguments.stars') + yield self.register(orders, 'com.arguments.orders') + yield self.register(arglen, 'com.arguments.arglen') print("Procedures registered; ready for frontend.") if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/arguments/frontend.py b/examples/twisted/wamp/rpc/arguments/frontend.py index ed722071f..a53dc3858 100644 --- a/examples/twisted/wamp/rpc/arguments/frontend.py +++ b/examples/twisted/wamp/rpc/arguments/frontend.py @@ -40,40 +40,40 @@ class Component(ApplicationSession): def onJoin(self, details): print("session attached") - yield self.call(u'com.arguments.ping') + yield self.call('com.arguments.ping') print("Pinged!") - res = yield self.call(u'com.arguments.add2', 2, 3) + res = yield self.call('com.arguments.add2', 2, 3) print("Add2: {}".format(res)) - starred = yield self.call(u'com.arguments.stars') + starred = yield self.call('com.arguments.stars') print("Starred 1: {}".format(starred)) - starred = yield self.call(u'com.arguments.stars', nick=u'Homer') + starred = yield self.call('com.arguments.stars', nick='Homer') print("Starred 2: {}".format(starred)) - starred = yield self.call(u'com.arguments.stars', stars=5) + starred = yield self.call('com.arguments.stars', stars=5) print("Starred 3: {}".format(starred)) - starred = yield self.call(u'com.arguments.stars', nick=u'Homer', stars=5) + starred = yield self.call('com.arguments.stars', nick='Homer', stars=5) print("Starred 4: {}".format(starred)) - orders = yield self.call(u'com.arguments.orders', u'coffee') + orders = yield self.call('com.arguments.orders', 'coffee') print("Orders 1: {}".format(orders)) - orders = yield self.call(u'com.arguments.orders', u'coffee', limit=10) + orders = yield self.call('com.arguments.orders', 'coffee', limit=10) print("Orders 2: {}".format(orders)) - arglengths = yield self.call(u'com.arguments.arglen') + arglengths = yield self.call('com.arguments.arglen') print("Arglen 1: {}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3) + arglengths = yield self.call('com.arguments.arglen', 1, 2, 3) print("Arglen 2: {}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', a=1, b=2, c=3) + arglengths = yield self.call('com.arguments.arglen', a=1, b=2, c=3) print("Arglen 3: {}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3, a=1, b=2, c=3) + arglengths = yield self.call('com.arguments.arglen', 1, 2, 3, a=1, b=2, c=3) print("Arglen 4: {}".format(arglengths)) self.leave() @@ -84,7 +84,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/authorize/authorizer.py b/examples/twisted/wamp/rpc/authorize/authorizer.py index c3e2ce8bd..2a6c68367 100644 --- a/examples/twisted/wamp/rpc/authorize/authorizer.py +++ b/examples/twisted/wamp/rpc/authorize/authorizer.py @@ -8,8 +8,8 @@ class MyAuthorizer(ApplicationSession): def onJoin(self, details): print("MyAuthorizer.onJoin({})".format(details)) try: - yield self.register(self.authorize, u'com.example.authorize') - yield self.register(self.scram_authorize, u'com.example.scram_auth') + yield self.register(self.authorize, 'com.example.authorize') + yield self.register(self.scram_authorize, 'com.example.scram_auth') print("MyAuthorizer: authorizer registered") except Exception as e: print("MyAuthorizer: failed to register authorizer procedure ({})".format(e)) @@ -17,14 +17,14 @@ def onJoin(self, details): def scram_authorize(self, realm, authid, details): print("dynamic SCRAM authorize: authid='{}', realm='{}'".format(authid, realm)) - if authid == u"carol" and realm == u"crossbardemo": + if authid == "carol" and realm == "crossbardemo": # this corresponds to client secret "p4ssw0rd" return { - u"role": "authenticated", - u"memory": 512, - u"kdf": "argon2id-13", - u"iterations": 4096, - u"salt": "accaa46d16de59a12db736c8ed2cc90c", + "role": "authenticated", + "memory": 512, + "kdf": "argon2id-13", + "iterations": 4096, + "salt": "accaa46d16de59a12db736c8ed2cc90c", "stored-key": "e699c745cc9e9876d8b61f9a14496bf6805a3391f5ecfbf7ae348a0034876485", "server-key": "92519a86d68146f15dffe50e27a6e479e41e5e40363b8714773dd8a4066ebb6c", } @@ -38,9 +38,9 @@ def authorize(self, details, uri, action, options): if False: print("I allow everything.") else: - if uri == u'com.foo.private': + if uri == 'com.foo.private': return False - if options.get(u"match", "exact") != u"exact": + if options.get("match", "exact") != "exact": print("only exact-match subscriptions allowed") return False return True diff --git a/examples/twisted/wamp/rpc/authorize/backend.py b/examples/twisted/wamp/rpc/authorize/backend.py index 6b13b00e2..fb382e4c9 100644 --- a/examples/twisted/wamp/rpc/authorize/backend.py +++ b/examples/twisted/wamp/rpc/authorize/backend.py @@ -46,9 +46,9 @@ def foo(*args, **kw): print("foo(): {} {}".format(args, kw)) return None reg = yield self.register( - foo, u'example.foo', + foo, 'example.foo', options=RegisterOptions( - invoke=u'roundrobin', + invoke='roundrobin', ) ) print("registered example.foo: {}".format(reg)) @@ -57,9 +57,9 @@ def bar(*args, **kw): print("bar(): {} {}".format(args, kw)) return None sub = yield self.subscribe( - bar, u"example.", + bar, "example.", options=SubscribeOptions( - match=u"prefix", + match="prefix", ) ) print("subscribed: {}".format(sub)) @@ -67,14 +67,14 @@ def bar(*args, **kw): if __name__ == '__main__': runner = ApplicationRunner( - environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/auth_ws"), - u"crossbardemo", + environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/auth_ws"), + "crossbardemo", ) def make(config): session = Component(config) session.add_authenticator( - u"wampcra", authid=u'bob', secret=u'p4ssw0rd' + "wampcra", authid='bob', secret='p4ssw0rd' ) return session runner.run(make) diff --git a/examples/twisted/wamp/rpc/cancel/backend.py b/examples/twisted/wamp/rpc/cancel/backend.py index 8e742fb51..fcc31ac47 100644 --- a/examples/twisted/wamp/rpc/cancel/backend.py +++ b/examples/twisted/wamp/rpc/cancel/backend.py @@ -46,19 +46,19 @@ def add2(a, b): return a + b def stars(nick = "somebody", stars = 0): - return u"{} starred {}x".format(nick, stars) + return "{} starred {}x".format(nick, stars) def orders(product, limit = 5): - return [u"Product {}".format(i) for i in range(50)][:limit] + return ["Product {}".format(i) for i in range(50)][:limit] def arglen(*args, **kwargs): return [len(args), len(kwargs)] - yield self.register(ping, u'com.arguments.ping') - yield self.register(add2, u'com.arguments.add2') - yield self.register(stars, u'com.arguments.stars') - yield self.register(orders, u'com.arguments.orders') - yield self.register(arglen, u'com.arguments.arglen') + yield self.register(ping, 'com.arguments.ping') + yield self.register(add2, 'com.arguments.add2') + yield self.register(stars, 'com.arguments.stars') + yield self.register(orders, 'com.arguments.orders') + yield self.register(arglen, 'com.arguments.arglen') print("procedures registered") diff --git a/examples/twisted/wamp/rpc/cancel/frontend.py b/examples/twisted/wamp/rpc/cancel/frontend.py index 95c87da6c..03b481fe6 100644 --- a/examples/twisted/wamp/rpc/cancel/frontend.py +++ b/examples/twisted/wamp/rpc/cancel/frontend.py @@ -40,40 +40,40 @@ class Component(ApplicationSession): def onJoin(self, details): print("session attached") - yield self.call(u'com.arguments.ping') + yield self.call('com.arguments.ping') print("Pinged!") - res = yield self.call(u'com.arguments.add2', 2, 3) + res = yield self.call('com.arguments.add2', 2, 3) print("Add2: {}".format(res)) - starred = yield self.call(u'com.arguments.stars') + starred = yield self.call('com.arguments.stars') print("Starred 1: {}".format(starred)) - starred = yield self.call(u'com.arguments.stars', nick = u'Homer') + starred = yield self.call('com.arguments.stars', nick = 'Homer') print("Starred 2: {}".format(starred)) - starred = yield self.call(u'com.arguments.stars', stars = 5) + starred = yield self.call('com.arguments.stars', stars = 5) print("Starred 3: {}".format(starred)) - starred = yield self.call(u'com.arguments.stars', nick = u'Homer', stars = 5) + starred = yield self.call('com.arguments.stars', nick = 'Homer', stars = 5) print("Starred 4: {}".format(starred)) - orders = yield self.call(u'com.arguments.orders', u'coffee') + orders = yield self.call('com.arguments.orders', 'coffee') print("Orders 1: {}".format(orders)) - orders = yield self.call(u'com.arguments.orders', u'coffee', limit = 10) + orders = yield self.call('com.arguments.orders', 'coffee', limit = 10) print("Orders 2: {}".format(orders)) - arglengths = yield self.call(u'com.arguments.arglen') + arglengths = yield self.call('com.arguments.arglen') print("Arglen 1: {}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3) + arglengths = yield self.call('com.arguments.arglen', 1, 2, 3) print("Arglen 2: {}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', a = 1, b = 2, c = 3) + arglengths = yield self.call('com.arguments.arglen', a = 1, b = 2, c = 3) print("Arglen 3: {}".format(arglengths)) - arglengths = yield self.call(u'com.arguments.arglen', 1, 2, 3, a = 1, b = 2, c = 3) + arglengths = yield self.call('com.arguments.arglen', 1, 2, 3, a = 1, b = 2, c = 3) print("Arglen 4: {}".format(arglengths)) self.leave() diff --git a/examples/twisted/wamp/rpc/complex/backend.py b/examples/twisted/wamp/rpc/complex/backend.py index 608b7d697..10e71bda9 100644 --- a/examples/twisted/wamp/rpc/complex/backend.py +++ b/examples/twisted/wamp/rpc/complex/backend.py @@ -45,19 +45,19 @@ def onJoin(self, details): def add_complex(a, ai, b, bi): return CallResult(c=a + b, ci=ai + bi) - yield self.register(add_complex, u'com.myapp.add_complex') + yield self.register(add_complex, 'com.myapp.add_complex') def split_name(fullname): forename, surname = fullname.split() return CallResult(forename, surname) - yield self.register(split_name, u'com.myapp.split_name') + yield self.register(split_name, 'com.myapp.split_name') print("procedures registered") if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/complex/frontend.py b/examples/twisted/wamp/rpc/complex/frontend.py index 846c39fc9..6a58152fa 100644 --- a/examples/twisted/wamp/rpc/complex/frontend.py +++ b/examples/twisted/wamp/rpc/complex/frontend.py @@ -41,10 +41,10 @@ class Component(ApplicationSession): def onJoin(self, details): print("session attached") - res = yield self.call(u'com.myapp.add_complex', 2, 3, 4, 5) + res = yield self.call('com.myapp.add_complex', 2, 3, 4, 5) print("Result: {} + {}i".format(res.kwresults['c'], res.kwresults['ci'])) - res = yield self.call(u'com.myapp.split_name', 'Homer Simpson') + res = yield self.call('com.myapp.split_name', 'Homer Simpson') print("Forname: {}, Surname: {}".format(res.results[0], res.results[1])) self.leave() @@ -55,7 +55,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/decorators/backend.py b/examples/twisted/wamp/rpc/decorators/backend.py index 26a690644..203bdd373 100644 --- a/examples/twisted/wamp/rpc/decorators/backend.py +++ b/examples/twisted/wamp/rpc/decorators/backend.py @@ -33,11 +33,11 @@ class MyService1(object): - @wamp.register(u'com.mathservice.add2') + @wamp.register('com.mathservice.add2') def add2(self, x, y): return x + y - @wamp.register(u'com.mathservice.mul2') + @wamp.register('com.mathservice.mul2') def mul2(self, x, y): return x * y @@ -74,11 +74,11 @@ def onJoin(self, details): else: print("registration ID {}: {}".format(res.id, res.procedure)) - @wamp.register(u'com.mathservice.square2') + @wamp.register('com.mathservice.square2') def square2(self, x, y): return x * x + y * y - @wamp.register(u'com.mathservice.div2') + @wamp.register('com.mathservice.div2') def div2(self, x, y): if y: return float(x) / float(y) @@ -87,7 +87,7 @@ def div2(self, x, y): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/decorators/frontend.py b/examples/twisted/wamp/rpc/decorators/frontend.py index 70a3771ab..1684e098c 100644 --- a/examples/twisted/wamp/rpc/decorators/frontend.py +++ b/examples/twisted/wamp/rpc/decorators/frontend.py @@ -40,10 +40,10 @@ class Component(ApplicationSession): def onJoin(self, details): print("session attached") - procs = [u'com.mathservice.add2', - u'com.mathservice.mul2', - u'com.mathservice.square2', - u'com.mathservice.div2'] + procs = ['com.mathservice.add2', + 'com.mathservice.mul2', + 'com.mathservice.square2', + 'com.mathservice.div2'] try: for proc in procs: @@ -60,7 +60,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/errors/backend.py b/examples/twisted/wamp/rpc/errors/backend.py index bcaca6c8d..f3e7e1f35 100644 --- a/examples/twisted/wamp/rpc/errors/backend.py +++ b/examples/twisted/wamp/rpc/errors/backend.py @@ -34,7 +34,7 @@ from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner -@wamp.error(u"com.myapp.error1") +@wamp.error("com.myapp.error1") class AppError1(Exception): """ An application specific exception that is decorated with a WAMP URI, @@ -60,23 +60,23 @@ def sqrt(x): # this also will raise, if x < 0 return math.sqrt(x) - yield self.register(sqrt, u'com.myapp.sqrt') + yield self.register(sqrt, 'com.myapp.sqrt') # raising WAMP application exceptions ## def checkname(name): if name in ['foo', 'bar']: - raise ApplicationError(u"com.myapp.error.reserved") + raise ApplicationError("com.myapp.error.reserved") if name.lower() != name.upper(): # forward positional arguments in exceptions - raise ApplicationError(u"com.myapp.error.mixed_case", name.lower(), name.upper()) + raise ApplicationError("com.myapp.error.mixed_case", name.lower(), name.upper()) if len(name) < 3 or len(name) > 10: # forward keyword arguments in exceptions - raise ApplicationError(u"com.myapp.error.invalid_length", min=3, max=10) + raise ApplicationError("com.myapp.error.invalid_length", min=3, max=10) - yield self.register(checkname, u'com.myapp.checkname') + yield self.register(checkname, 'com.myapp.checkname') # defining and automapping WAMP application exceptions ## @@ -86,13 +86,13 @@ def compare(a, b): if a < b: raise AppError1(b - a) - yield self.register(compare, u'com.myapp.compare') + yield self.register(compare, 'com.myapp.compare') print("procedures registered") if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/errors/frontend.py b/examples/twisted/wamp/rpc/errors/frontend.py index 373320777..8e173488a 100644 --- a/examples/twisted/wamp/rpc/errors/frontend.py +++ b/examples/twisted/wamp/rpc/errors/frontend.py @@ -35,7 +35,7 @@ from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner -@wamp.error(u"com.myapp.error1") +@wamp.error("com.myapp.error1") class AppError1(Exception): """ An application specific exception that is decorated with a WAMP URI, @@ -56,7 +56,7 @@ def onJoin(self, details): ## for x in [2, 0, -2]: try: - res = yield self.call(u'com.myapp.sqrt', x) + res = yield self.call('com.myapp.sqrt', x) except Exception as e: print("Error: {} {}".format(e, e.args)) else: @@ -66,7 +66,7 @@ def onJoin(self, details): ## for name in ['foo', 'a', '*' * 11, 'Hello']: try: - res = yield self.call(u'com.myapp.checkname', name) + res = yield self.call('com.myapp.checkname', name) except ApplicationError as e: print("Error: {} {} {} {}".format(e, e.error, e.args, e.kwargs)) else: @@ -77,7 +77,7 @@ def onJoin(self, details): self.define(AppError1) try: - yield self.call(u'com.myapp.compare', 3, 17) + yield self.call('com.myapp.compare', 3, 17) except AppError1 as e: print("Compare Error: {}".format(e)) @@ -90,7 +90,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/options/backend.py b/examples/twisted/wamp/rpc/options/backend.py index bbd6f221d..6e9f91cdb 100644 --- a/examples/twisted/wamp/rpc/options/backend.py +++ b/examples/twisted/wamp/rpc/options/backend.py @@ -46,22 +46,22 @@ def square(val, details=None): print("square called from: {}".format(details.caller)) if val < 0: - self.publish(u'com.myapp.square_on_nonpositive', val) + self.publish('com.myapp.square_on_nonpositive', val) elif val == 0: if details.caller: options = PublishOptions(exclude=[details.caller]) else: options = None - self.publish(u'com.myapp.square_on_nonpositive', val, options=options) + self.publish('com.myapp.square_on_nonpositive', val, options=options) return val * val - yield self.register(square, u'com.myapp.square', RegisterOptions(details_arg='details')) + yield self.register(square, 'com.myapp.square', RegisterOptions(details_arg='details')) print("procedure registered") if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/options/frontend.py b/examples/twisted/wamp/rpc/options/frontend.py index 43be49055..ab073f51b 100644 --- a/examples/twisted/wamp/rpc/options/frontend.py +++ b/examples/twisted/wamp/rpc/options/frontend.py @@ -44,10 +44,10 @@ def onJoin(self, details): def on_event(val): print("Someone requested to square non-positive: {}".format(val)) - yield self.subscribe(on_event, u'com.myapp.square_on_nonpositive') + yield self.subscribe(on_event, 'com.myapp.square_on_nonpositive') for val in [2, 0, -2]: - res = yield self.call(u'com.myapp.square', val, options=CallOptions()) + res = yield self.call('com.myapp.square', val, options=CallOptions()) print("Squared {} = {}".format(val, res)) self.leave() @@ -58,7 +58,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/progress/backend.py b/examples/twisted/wamp/rpc/progress/backend.py index b07ce1295..940db7013 100644 --- a/examples/twisted/wamp/rpc/progress/backend.py +++ b/examples/twisted/wamp/rpc/progress/backend.py @@ -53,13 +53,13 @@ def longop(n, details=None): yield sleep(1 * n) returnValue(n) - yield self.register(longop, u'com.myapp.longop', RegisterOptions(details_arg='details')) + yield self.register(longop, 'com.myapp.longop', RegisterOptions(details_arg='details')) print("procedures registered") if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/progress/frontend.py b/examples/twisted/wamp/rpc/progress/frontend.py index d43e64af0..bfc9d1ddd 100644 --- a/examples/twisted/wamp/rpc/progress/frontend.py +++ b/examples/twisted/wamp/rpc/progress/frontend.py @@ -44,7 +44,7 @@ def onJoin(self, details): def on_progress(i): print("Progress: {}".format(i)) - res = yield self.call(u'com.myapp.longop', 3, options=CallOptions(on_progress=on_progress)) + res = yield self.call('com.myapp.longop', 3, options=CallOptions(on_progress=on_progress)) print("Final: {}".format(res)) @@ -56,7 +56,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/slowsquare/backend.py b/examples/twisted/wamp/rpc/slowsquare/backend.py index 610807102..1bee2a7f1 100644 --- a/examples/twisted/wamp/rpc/slowsquare/backend.py +++ b/examples/twisted/wamp/rpc/slowsquare/backend.py @@ -44,20 +44,20 @@ def onJoin(self, details): def square(x): return x * x - yield self.register(square, u'com.math.square') + yield self.register(square, 'com.math.square') @inlineCallbacks def slowsquare(x, delay=1): yield sleep(delay) returnValue(x * x) - yield self.register(slowsquare, u'com.math.slowsquare') + yield self.register(slowsquare, 'com.math.slowsquare') print("procedures registered") if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/slowsquare/frontend.py b/examples/twisted/wamp/rpc/slowsquare/frontend.py index e558bee46..3db4cb415 100644 --- a/examples/twisted/wamp/rpc/slowsquare/frontend.py +++ b/examples/twisted/wamp/rpc/slowsquare/frontend.py @@ -46,11 +46,11 @@ def got(res, started, msg): print("{}: {} in {}".format(msg, res, duration)) t1 = time.clock() - d1 = self.call(u'com.math.slowsquare', 3) + d1 = self.call('com.math.slowsquare', 3) d1.addCallback(got, t1, "Slow Square") t2 = time.clock() - d2 = self.call(u'com.math.square', 3) + d2 = self.call('com.math.square', 3) d2.addCallback(got, t2, "Quick Square") def done(_): @@ -65,7 +65,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/timeservice/backend.py b/examples/twisted/wamp/rpc/timeservice/backend.py index c71635b20..cfb45c02e 100644 --- a/examples/twisted/wamp/rpc/timeservice/backend.py +++ b/examples/twisted/wamp/rpc/timeservice/backend.py @@ -46,7 +46,7 @@ def utcnow(): return now.strftime("%Y-%m-%dT%H:%M:%SZ") try: - yield self.register(utcnow, u'com.timeservice.now') + yield self.register(utcnow, 'com.timeservice.now') except Exception as e: print("failed to register procedure: {}".format(e)) else: @@ -54,7 +54,7 @@ def utcnow(): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/rpc/timeservice/frontend.py b/examples/twisted/wamp/rpc/timeservice/frontend.py index 0868e355c..198bfeea5 100644 --- a/examples/twisted/wamp/rpc/timeservice/frontend.py +++ b/examples/twisted/wamp/rpc/timeservice/frontend.py @@ -40,7 +40,7 @@ class Component(ApplicationSession): def onJoin(self, details): print("session attached") try: - now = yield self.call(u'com.timeservice.now') + now = yield self.call('com.timeservice.now') except Exception as e: print("Error: {}".format(e)) else: @@ -54,7 +54,7 @@ def onDisconnect(self): if __name__ == '__main__': - url = environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws") - realm = u"crossbardemo" + url = environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws") + realm = "crossbardemo" runner = ApplicationRunner(url, realm) runner.run(Component) diff --git a/examples/twisted/wamp/work/newapi/test_newapi.py b/examples/twisted/wamp/work/newapi/test_newapi.py index c44189ff0..e850c4734 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi.py +++ b/examples/twisted/wamp/work/newapi/test_newapi.py @@ -25,7 +25,7 @@ def on_create(connection): """ def on_connect(session): session.on_join(on_join) - session.join(u'public') + session.join('public') # we attach our listener code on the connection. whenever there # is a session created which has joined, our callback code is run @@ -50,7 +50,7 @@ def run(on_create): # a connection connects and automatically reconnects WAMP client # transports to a WAMP router. A connection has a listener system # where user code can hook into different events : on_join - connection = Connection(on_create, realm=u'public', + connection = Connection(on_create, realm='public', transports=transports, reactor=reactor) # the following returns a deferred that fires when the connection is diff --git a/examples/twisted/wamp/work/newapi/test_newapi10.py b/examples/twisted/wamp/work/newapi/test_newapi10.py index 5557d686d..1d3cf73a0 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi10.py +++ b/examples/twisted/wamp/work/newapi/test_newapi10.py @@ -8,15 +8,15 @@ def main(reactor, transport): transport1 = yield transport.split() session = yield transport.join() - yield session1.join(transport, u'myrealm1') - yield session2.join(transport, u'myrealm1') + yield session1.join(transport, 'myrealm1') + yield session2.join(transport, 'myrealm1') def main1(reactor, transport): - yield session1.join(transport, u'myrealm1') + yield session1.join(transport, 'myrealm1') def main2(reactor, transport): - yield session2.join(transport, u'myrealm1') + yield session2.join(transport, 'myrealm1') if __name__ == '__main__': @@ -32,11 +32,11 @@ def main2(reactor, transport): } ] - realm = u'myrealm1' + realm = 'myrealm1' extra = { - u'foo': 23, - u'bar': u'baz' + 'foo': 23, + 'bar': 'baz' } client = Client([main1, main2]) diff --git a/examples/twisted/wamp/work/newapi/test_newapi11.py b/examples/twisted/wamp/work/newapi/test_newapi11.py index f4a1b3e01..2d7bf1a3d 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi11.py +++ b/examples/twisted/wamp/work/newapi/test_newapi11.py @@ -1,7 +1,7 @@ @coroutine def main(reactor, session): # the session is joined and ready - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) # as we exit, this signals we are done with the session! the session # can be recycled @@ -16,7 +16,7 @@ def setup(reactor, session): # the session is joined and ready also! def add2(a, b): return a + b - yield session.register(u'com.example.add2', add2) + yield session.register('com.example.add2', add2) print('procedure registered') # as we exit, this signals we are ready! the session must be kept. @@ -35,7 +35,7 @@ def transport_main(reactor, transport): @coroutine def session_main(reactor, session): - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) # returns when the session_main has finished (!), the session @@ -53,7 +53,7 @@ def session_main(reactor, session): @coroutine def session_main(reactor, session): - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) @@ -67,7 +67,7 @@ def session_main(reactor, session): def session_main(reactor, session): def add2(a, b): return a + b - yield session.register(u'com.example.add2', add2) + yield session.register('com.example.add2', add2) print('procedure registered') txaio.return_value(txaio.create_future()) @@ -80,7 +80,7 @@ def add2(a, b): @coroutine def main1(reactor, session, details): - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) yield session.leave() @@ -101,7 +101,7 @@ def main1(reactor, transport, details): session = yield transport.join(details.config.realm) # the session is joined and can be used - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) yield session.leave() @@ -125,7 +125,7 @@ def main1(reactor, client, details): # create a session running over the transport session = yield transport.join(config.realm) - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) yield session.leave() yield transport.close() @@ -144,7 +144,7 @@ def main1(reactor, client, details): def main1(reactor, client, config): transport = yield client.open() session = yield transport.join(config.realm) - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) yield session.leave() yield transport.close() @@ -172,7 +172,7 @@ def main1(reactor, client, config): with yield client.open() as transport: try: with yield transport.join(config.realm) as session: - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) except Exception as e: pass @@ -201,10 +201,10 @@ def main2(reactor, connection): def add2(a, b): return a + b - yield session.register(u'com.example.add2', add2) + yield session.register('com.example.add2', add2) # and call the procedure - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) # now leave the realm, which frees the underlying transport @@ -228,7 +228,7 @@ def add2(a, b): session2 = transport.join(connection.config.realm) # call the procedure registered on the (resumed) session running on transport2 - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('result={}'.format(result)) # if the transport supports multiplexing, multiple session can run @@ -257,6 +257,6 @@ def add2(a, b): } } ] - config = Config(realm=u'myrealm1') + config = Config(realm='myrealm1') connection = Connection(main, transports=transports, config=config) react(connection.start) diff --git a/examples/twisted/wamp/work/newapi/test_newapi12.py b/examples/twisted/wamp/work/newapi/test_newapi12.py index b57b0808f..1a11a19e6 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi12.py +++ b/examples/twisted/wamp/work/newapi/test_newapi12.py @@ -8,15 +8,15 @@ def shutdown(): print('backend component: shutting down ..') session.leave() - yield session.subscribe(shutdown, u'com.example.shutdown') -# yield session.subscribe(u'com.example.shutdown', shutdown) + yield session.subscribe(shutdown, 'com.example.shutdown') +# yield session.subscribe('com.example.shutdown', shutdown) def add2(a, b): print('backend component: add2()') return a + b - yield session.register(add2, u'com.example.add2') -# yield session.register(u'com.example.add2', add2) + yield session.register(add2, 'com.example.add2') +# yield session.register('com.example.add2', add2) print('backend component: ready.') @@ -29,10 +29,10 @@ def component2_main(reactor, session): yield sleep(.2) # "enforce" order: backend must have started before we call it print('frontend component: ready') - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('frontend component: result={}'.format(result)) - session.publish(u'com.example.shutdown') + session.publish('com.example.shutdown') # as we exit, this signals we are done with the session! the session # can be recycled @@ -64,7 +64,7 @@ def component2_main(reactor, session): ] config = { - 'realm': u'realm1', + 'realm': 'realm1', 'extra': { 'foo': 23 } diff --git a/examples/twisted/wamp/work/newapi/test_newapi12b.py b/examples/twisted/wamp/work/newapi/test_newapi12b.py index 2f8b09ef0..bbc764c2c 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi12b.py +++ b/examples/twisted/wamp/work/newapi/test_newapi12b.py @@ -8,15 +8,15 @@ def shutdown(): print('backend component: shutting down ..') session.leave() - yield session.subscribe(shutdown, u'com.example.shutdown') -# yield session.subscribe(u'com.example.shutdown', shutdown) + yield session.subscribe(shutdown, 'com.example.shutdown') +# yield session.subscribe('com.example.shutdown', shutdown) def add2(a, b): print('backend component: add2()') return a + b - yield session.register(add2, u'com.example.add2') -# yield session.register(u'com.example.add2', add2) + yield session.register(add2, 'com.example.add2') +# yield session.register('com.example.add2', add2) print('backend component: ready.') @@ -29,10 +29,10 @@ def component2_main(reactor, session): yield sleep(.2) # "enforce" order: backend must have started before we call it print('frontend component: ready') - result = yield session.call(u'com.example.add2', 2, 3) + result = yield session.call('com.example.add2', 2, 3) print('frontend component: result={}'.format(result)) - session.publish(u'com.example.shutdown') + session.publish('com.example.shutdown') # as we exit, this signals we are done with the session! the session # can be recycled @@ -68,12 +68,12 @@ def component2_main(reactor, session): components = [ Component( transports, - config=Config(realm=u'realm1'), + config=Config(realm='realm1'), setup=component1_setup ), Component( transports, - config=Config(realm=u'realm1', extra={'foo': 23}), + config=Config(realm='realm1', extra={'foo': 23}), main=component2_main ) ] diff --git a/examples/twisted/wamp/work/newapi/test_newapi13.py b/examples/twisted/wamp/work/newapi/test_newapi13.py index 4ecd24732..44246892d 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi13.py +++ b/examples/twisted/wamp/work/newapi/test_newapi13.py @@ -4,13 +4,13 @@ # register/subscribe WAMP actions api = Api() -@api.register(u'com.example.add2') +@api.register('com.example.add2') def add2(a, b): return a + b -@api.subscribe(u'com.example.on-hello', details=True) +@api.subscribe('com.example.on-hello', details=True) def on_hello(msg, details=None): - print(u'Someone said: {}'.format(msg)) + print('Someone said: {}'.format(msg)) details.session.leave() @coroutine @@ -29,8 +29,8 @@ def component2(reactor, session): A second component, which gets called "main-like". When it returns, this will automatically close the session. """ - result = yield session.call(u'com.example.add2', 2, 3) - session.publish(u'com.example.on-hello', u'result={}'.format(result)) + result = yield session.call('com.example.add2', 2, 3) + session.publish('com.example.on-hello', 'result={}'.format(result)) if __name__ == '__main__': diff --git a/examples/twisted/wamp/work/newapi/test_newapi2.py b/examples/twisted/wamp/work/newapi/test_newapi2.py index 107330f8e..885c244a3 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi2.py +++ b/examples/twisted/wamp/work/newapi/test_newapi2.py @@ -13,10 +13,10 @@ def on_join(self, details): def add2(a, b): return a + b - yield self.register(add2, u'com.example.add2') + yield self.register(add2, 'com.example.add2') try: - res = yield self.call(u'com.example.add2', 2, 3) + res = yield self.call('com.example.add2', 2, 3) print("result: {}".format(res)) except Exception as e: print("error: {}".format(e)) @@ -35,7 +35,7 @@ def on_disconnect(self): if __name__ == '__main__': - transports = u'ws://localhost:8080/ws' + transports = 'ws://localhost:8080/ws' connection = Connection(transports=transports) connection.session = MySession diff --git a/examples/twisted/wamp/work/newapi/test_newapi3.py b/examples/twisted/wamp/work/newapi/test_newapi3.py index d2bf289c5..581bd3078 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi3.py +++ b/examples/twisted/wamp/work/newapi/test_newapi3.py @@ -18,10 +18,10 @@ def add2(a, b): print("add2() called", a, b) return a + b - yield session.register(add2, u'com.example.add2') + yield session.register(add2, 'com.example.add2') try: - res = yield session.call(u'com.example.add2', 2, 3) + res = yield session.call('com.example.add2', 2, 3) print("result: {}".format(res)) except Exception as e: print("error: {}".format(e)) diff --git a/examples/twisted/wamp/work/newapi/test_newapi4.py b/examples/twisted/wamp/work/newapi/test_newapi4.py index 834f83566..7d5ae4c0e 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi4.py +++ b/examples/twisted/wamp/work/newapi/test_newapi4.py @@ -13,10 +13,10 @@ def on_join(session, details): def add2(a, b): return a + b - yield session.register(add2, u'com.example.add2') + yield session.register(add2, 'com.example.add2') try: - res = yield session.call(u'com.example.add2', 2, 3) + res = yield session.call('com.example.add2', 2, 3) print("result: {}".format(res)) except Exception as e: print("error: {}".format(e)) diff --git a/examples/twisted/wamp/work/newapi/test_newapi5.py b/examples/twisted/wamp/work/newapi/test_newapi5.py index 024bf7e0b..242cc4330 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi5.py +++ b/examples/twisted/wamp/work/newapi/test_newapi5.py @@ -7,8 +7,8 @@ def main(reactor, connection): transport = yield connection.connect() - session = yield transport.join(u'realm1') - result = yield session.call(u'com.example.add2', 2, 3) + session = yield transport.join('realm1') + result = yield session.call('com.example.add2', 2, 3) yield session.leave() yield transport.disconnect() yield connection.close() diff --git a/examples/twisted/wamp/work/newapi/test_newapi6.py b/examples/twisted/wamp/work/newapi/test_newapi6.py index 6ddb001f3..348ad5367 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi6.py +++ b/examples/twisted/wamp/work/newapi/test_newapi6.py @@ -4,8 +4,8 @@ @coroutine def main(transport): - session = yield transport.join(u'myrealm1') - result = yield session.call(u'com.myapp.add2', 2, 3) + session = yield transport.join('myrealm1') + result = yield session.call('com.myapp.add2', 2, 3) print("Result: {}".format(result)) yield session.leave() yield transport.close() diff --git a/examples/twisted/wamp/work/newapi/test_newapi7.py b/examples/twisted/wamp/work/newapi/test_newapi7.py index 9be8242be..d4b2a85c3 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi7.py +++ b/examples/twisted/wamp/work/newapi/test_newapi7.py @@ -12,14 +12,14 @@ def on_join(session): def on_leave(session, details): print("Session {} has left: {}".format(session.id, details.reason)) -@session.register(u'com.myapp.add2') # registering in on_join +@session.register('com.myapp.add2') # registering in on_join def add2(a, b): return a + b @coroutine def main(transport): - yield session.join(transport, u'myrealm1') - result = yield session.call(u'com.myapp.add2', 2, 3) + yield session.join(transport, 'myrealm1') + result = yield session.call('com.myapp.add2', 2, 3) print("Result: {}".format(result)) yield session.leave() yield transport.close() diff --git a/examples/twisted/wamp/work/newapi/test_newapi8.py b/examples/twisted/wamp/work/newapi/test_newapi8.py index 44220056c..d3c792b77 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi8.py +++ b/examples/twisted/wamp/work/newapi/test_newapi8.py @@ -10,16 +10,16 @@ def main(transport): session = ApplicationSession() # join a first realm and do something - yield session.join(transport, u'myrealm1') - result = yield session.call(u'com.myapp.add2', 2, 3) + yield session.join(transport, 'myrealm1') + result = yield session.call('com.myapp.add2', 2, 3) print("Result: {}".format(result)) # leave the realm. the transport will NOT be closed! yield session.leave() # join a different realm and do something - yield session.join(transport, u'myrealm2') - result = yield session.call(u'com.foobar.mul2', 2, 3) + yield session.join(transport, 'myrealm2') + result = yield session.call('com.foobar.mul2', 2, 3) print("Result: {}".format(result)) # leave the realm. the transport will NOT be closed! diff --git a/examples/twisted/wamp/work/newapi/test_newapi9.py b/examples/twisted/wamp/work/newapi/test_newapi9.py index fa4966152..bf2486a17 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi9.py +++ b/examples/twisted/wamp/work/newapi/test_newapi9.py @@ -14,12 +14,12 @@ def add2(a, b): @coroutine def main(transport): # join a realm and try to resume the session - details = yield session.join(transport, u'myrealm1', resume=True) + details = yield session.join(transport, 'myrealm1', resume=True) if not details.is_resumed: # if the session is fresh, register a procedure .. - yield session.register(u'com.myapp.add2', add2) + yield session.register('com.myapp.add2', add2) # and leave the realm, freezing the session yield session.leave(freeze=True) @@ -28,7 +28,7 @@ def main(transport): # if the session is resumed, our registration will have been # reestablished automatically - result = yield session.call(u'com.myapp.add2', 2, 3) + result = yield session.call('com.myapp.add2', 2, 3) print("Result: {}", result) # leave the realm finally diff --git a/examples/twisted/wamp/work/newapi/test_newapi_cryptosign.py b/examples/twisted/wamp/work/newapi/test_newapi_cryptosign.py index c4f989a28..6c55b3dc0 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi_cryptosign.py +++ b/examples/twisted/wamp/work/newapi/test_newapi_cryptosign.py @@ -1,19 +1,15 @@ -from __future__ import print_function - from autobahn.twisted.component import Component, run -from autobahn.wamp import cryptosign -import binascii privkey_hex = '6e3a302aa67d55ffc2059efeb5cf679470b37a26ae9ac18693b56ea3d0cd331c' # pubkey: 020b13239ca0f10a1c65feaf26e8dfca6e84c81d2509a2b7b75a7e5ee5ce4b66 component = Component( - transports=u'ws://localhost:8080/auth_ws', - realm=u'crossbardemo', + transports='ws://localhost:8080/auth_ws', + realm='crossbardemo', authentication={ - u"cryptosign": { - "authid": u"alice", + "cryptosign": { + "authid": "alice", "privkey": privkey_hex, } } diff --git a/examples/twisted/wamp/work/newapi/test_newapi_multiple_connections.py b/examples/twisted/wamp/work/newapi/test_newapi_multiple_connections.py index 852619bcb..f42b79a02 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi_multiple_connections.py +++ b/examples/twisted/wamp/work/newapi/test_newapi_multiple_connections.py @@ -43,8 +43,8 @@ def on_join(session, details): } ] - component1 = Component(on_join=setup_alice, transports=transports, realm=u'crossbardemo') - component2 = Component(main=setup_bob, transports=transports, realm=u'crossbardemo') + component1 = Component(on_join=setup_alice, transports=transports, realm='crossbardemo') + component2 = Component(main=setup_bob, transports=transports, realm='crossbardemo') #run([component1, component2], log_level='debug') #run([component1, component2], log_level='info') run([component1], log_level='info') diff --git a/examples/twisted/wamp/work/newapi/test_newapi_pubreg_decorator.py b/examples/twisted/wamp/work/newapi/test_newapi_pubreg_decorator.py index 9ea5f6b24..134e4dc5b 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi_pubreg_decorator.py +++ b/examples/twisted/wamp/work/newapi/test_newapi_pubreg_decorator.py @@ -1,5 +1,3 @@ -from __future__ import print_function -import os import txaio from twisted.internet.defer import inlineCallbacks @@ -17,27 +15,27 @@ component = Component( - transports=u'ws://localhost:8080/ws', - realm=u'crossbardemo', + transports='ws://localhost:8080/ws', + realm='crossbardemo', ) # @component.subscribe( -# u"com.example.", -# options=SubscribeOptions(match=u"prefix"), +# "com.example.", +# options=SubscribeOptions(match="prefix"), # ) # def catch_all(*args, **kw): # print("catch_all({}, {})".format(args, kw)) @component.subscribe( - u"com.example.", - options=SubscribeOptions(match=u"prefix", details_arg='details'), + "com.example.", + options=SubscribeOptions(match="prefix", details_arg='details'), ) def an_event(details=None): print("topic '{}'".format(details.topic)) @component.register( - u"com.example.progressive", + "com.example.progressive", options=RegisterOptions(details_arg='details'), ) @inlineCallbacks @@ -73,10 +71,10 @@ def on_progress(some_data): options=CallOptions(on_progress=on_progress) ) - reactor.callLater(1, pub, u'com.example.foo') - reactor.callLater(2, pub, u'com.non_matching') - reactor.callLater(3, pub, u'com.example.some.other.uri') - reactor.callLater(4, call_progress, u'com.example.progressive') + reactor.callLater(1, pub, 'com.example.foo') + reactor.callLater(2, pub, 'com.non_matching') + reactor.callLater(3, pub, 'com.example.some.other.uri') + reactor.callLater(4, call_progress, 'com.example.progressive') reactor.callLater(7, session.leave) @component.on_leave diff --git a/examples/twisted/wamp/work/newapi/test_newapi_short.py b/examples/twisted/wamp/work/newapi/test_newapi_short.py index b130eb000..2eecb1a50 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi_short.py +++ b/examples/twisted/wamp/work/newapi/test_newapi_short.py @@ -5,7 +5,7 @@ @coroutine def on_join(session): try: - res = yield session.call(u'com.example.add2', 2, 3) + res = yield session.call('com.example.add2', 2, 3) print("Result: {}".format(res)) except Exception as e: print("Error: {}".format(e)) diff --git a/examples/twisted/wamp/work/newapi/test_newapi_twisted.py b/examples/twisted/wamp/work/newapi/test_newapi_twisted.py index db02a7386..b977668e2 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi_twisted.py +++ b/examples/twisted/wamp/work/newapi/test_newapi_twisted.py @@ -1,5 +1,5 @@ -from __future__ import print_function import os + import txaio from twisted.internet.defer import inlineCallbacks @@ -14,7 +14,7 @@ from autobahn.twisted.wamp import Session # This uses the new-api with various Twisted native objects. For the -# Unix socket things, you'll have to add a transport to "config.json" +# Unix socket things, yo'll have to add a transport to "config.json" # like this: # { # "type": "websocket", @@ -24,7 +24,7 @@ # } # } # ...then, the socket will appear in the .crossbar directory as -# "unix-websocket". Everything in here presumes you're using the +# "unix-websocket". Everything in here presumes yo're using the # "example/router/.crossbar" with config.json linked to either # "config-no-tls.json" or "config-tls.json" @@ -62,7 +62,7 @@ def on_join(session, details): "endpoint": SSL4ClientEndpoint( reactor, '127.0.0.1', 8083, optionsForClientTLS( - u'localhost', + 'localhost', # XXX why do I need BOTH the intermediate and actual # cert? Did I create the CA/intermediate certificates # incorrectly? @@ -96,7 +96,7 @@ def on_join(session, details): reactor, '127.0.0.1', 8080, - optionsForClientTLS(u'localhost'), + optionsForClientTLS('localhost'), ), } @@ -113,8 +113,8 @@ def on_join(session, details): ] # try main= vs. setup= to see different exit behavior - component = Component(main=setup, transports=transports, realm=u'crossbardemo') - #component = Component(setup=setup, transports=transports, realm=u'crossbardemo') + component = Component(main=setup, transports=transports, realm='crossbardemo') + #component = Component(setup=setup, transports=transports, realm='crossbardemo') # can add this confirm logging of more error-cases #component.session_factory = Foo diff --git a/examples/twisted/wamp/work/newapi/test_newapi_wampcra.py b/examples/twisted/wamp/work/newapi/test_newapi_wampcra.py index d328f6485..d02062e1d 100644 --- a/examples/twisted/wamp/work/newapi/test_newapi_wampcra.py +++ b/examples/twisted/wamp/work/newapi/test_newapi_wampcra.py @@ -1,5 +1,3 @@ -from __future__ import print_function - from autobahn.twisted.component import Component, run from autobahn.wamp import cryptosign import binascii @@ -9,12 +7,12 @@ component = Component( - transports=u'ws://localhost:8080/auth_ws', - realm=u'crossbardemo', + transports='ws://localhost:8080/auth_ws', + realm='crossbardemo', authentication={ - u"wampcra": { - "authid": u"username", - "secret": u"p4ssw0rd", + "wampcra": { + "authid": "username", + "secret": "p4ssw0rd", } } ) diff --git a/examples/twisted/websocket/auth_persona/server.py b/examples/twisted/websocket/auth_persona/server.py index e2593f0b4..c549524df 100644 --- a/examples/twisted/websocket/auth_persona/server.py +++ b/examples/twisted/websocket/auth_persona/server.py @@ -230,7 +230,7 @@ def __init__(self, url): print("Running Autobahn|Python {}".format(autobahn.version)) # our WebSocket server factory - factory = PersonaServerFactory(u"ws://127.0.0.1:8080") + factory = PersonaServerFactory("ws://127.0.0.1:8080") # we serve static files under "/" .. root = File(".") diff --git a/examples/twisted/websocket/broadcast/server.py b/examples/twisted/websocket/broadcast/server.py index 27a56fd6c..c12f3f8a0 100644 --- a/examples/twisted/websocket/broadcast/server.py +++ b/examples/twisted/websocket/broadcast/server.py @@ -108,7 +108,7 @@ def broadcast(self, msg): ServerFactory = BroadcastServerFactory # ServerFactory = BroadcastPreparedServerFactory - factory = ServerFactory(u"ws://127.0.0.1:9000") + factory = ServerFactory("ws://127.0.0.1:9000") factory.protocol = BroadcastServerProtocol listenWS(factory) diff --git a/examples/twisted/websocket/echo/client.py b/examples/twisted/websocket/echo/client.py index 416bd13b3..ecfe3e9ef 100644 --- a/examples/twisted/websocket/echo/client.py +++ b/examples/twisted/websocket/echo/client.py @@ -41,7 +41,7 @@ def onOpen(self): print("WebSocket connection open.") def hello(): - self.sendMessage(u"Hello, world!".encode('utf8')) + self.sendMessage("Hello, world!".encode('utf8')) self.sendMessage(b"\x00\x01\x03\x04", isBinary=True) self.factory.reactor.callLater(1, hello) @@ -67,7 +67,7 @@ def onClose(self, wasClean, code, reason): log.startLogging(sys.stdout) - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = MyClientProtocol reactor.connectTCP("127.0.0.1", 9000, factory) diff --git a/examples/twisted/websocket/echo/client_coroutines.py b/examples/twisted/websocket/echo/client_coroutines.py index 6c4171c25..7eab33da6 100644 --- a/examples/twisted/websocket/echo/client_coroutines.py +++ b/examples/twisted/websocket/echo/client_coroutines.py @@ -47,7 +47,7 @@ def onOpen(self): # start sending messages every second .. while True: - self.sendMessage(u"Hello, world!".encode('utf8')) + self.sendMessage("Hello, world!".encode('utf8')) self.sendMessage(b"\x00\x01\x03\x04", isBinary=True) yield sleep(1) @@ -70,7 +70,7 @@ def onClose(self, wasClean, code, reason): log.startLogging(sys.stdout) - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = MyClientProtocol reactor.connectTCP("127.0.0.1", 9000, factory) diff --git a/examples/twisted/websocket/echo/server.py b/examples/twisted/websocket/echo/server.py index 1dea01021..1acf2bac8 100644 --- a/examples/twisted/websocket/echo/server.py +++ b/examples/twisted/websocket/echo/server.py @@ -58,7 +58,7 @@ def onClose(self, wasClean, code, reason): log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = MyServerProtocol # factory.setProtocolOptions(maxConnections=2) diff --git a/examples/twisted/websocket/echo_compressed/server.py b/examples/twisted/websocket/echo_compressed/server.py index c807426a7..2d26b4f75 100644 --- a/examples/twisted/websocket/echo_compressed/server.py +++ b/examples/twisted/websocket/echo_compressed/server.py @@ -55,7 +55,7 @@ def onMessage(self, payload, isBinary): log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = EchoServerProtocol # Enable WebSocket extension "permessage-deflate". diff --git a/examples/twisted/websocket/echo_compressed/server_advanced.py b/examples/twisted/websocket/echo_compressed/server_advanced.py index c4f9b9b47..cf2bbd060 100644 --- a/examples/twisted/websocket/echo_compressed/server_advanced.py +++ b/examples/twisted/websocket/echo_compressed/server_advanced.py @@ -54,7 +54,7 @@ def onMessage(self, payload, isBinary): log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = EchoServerProtocol # factory.setProtocolOptions(autoFragmentSize = 4) diff --git a/examples/twisted/websocket/echo_endpoints/client.py b/examples/twisted/websocket/echo_endpoints/client.py index 62e2f83ad..53986bde1 100644 --- a/examples/twisted/websocket/echo_endpoints/client.py +++ b/examples/twisted/websocket/echo_endpoints/client.py @@ -75,7 +75,7 @@ class EchoClientFactory(WebSocketClientFactory): parser.add_argument("--websocket", default="tcp:127.0.0.1:9000", help='WebSocket client Twisted endpoint descriptor, e.g. "tcp:127.0.0.1:9000" or "unix:/tmp/mywebsocket".') - parser.add_argument("--wsurl", default=u"ws://127.0.0.1:9000", + parser.add_argument("--wsurl", default="ws://127.0.0.1:9000", help='WebSocket URL (must suit the endpoint), e.g. ws://127.0.0.1:9000.') args = parser.parse_args() diff --git a/examples/twisted/websocket/echo_endpoints/server.py b/examples/twisted/websocket/echo_endpoints/server.py index fcda6202c..d7a9f5962 100644 --- a/examples/twisted/websocket/echo_endpoints/server.py +++ b/examples/twisted/websocket/echo_endpoints/server.py @@ -70,7 +70,7 @@ class EchoServerFactory(WebSocketServerFactory): parser.add_argument("--websocket", default="tcp:9000", help='WebSocket server Twisted endpoint descriptor, e.g. "tcp:9000" or "unix:/tmp/mywebsocket".') - parser.add_argument("--wsurl", default=u"ws://127.0.0.1:9000", + parser.add_argument("--wsurl", default="ws://127.0.0.1:9000", help='WebSocket URL (must suit the endpoint), e.g. ws://127.0.0.1:9000.') parser.add_argument("--web", default="tcp:8080", diff --git a/examples/twisted/websocket/echo_httpheaders/server.py b/examples/twisted/websocket/echo_httpheaders/server.py index 8fa492915..6922e0d06 100644 --- a/examples/twisted/websocket/echo_httpheaders/server.py +++ b/examples/twisted/websocket/echo_httpheaders/server.py @@ -61,7 +61,7 @@ def onMessage(self, payload, isBinary): headers = {'MyCustomServerHeader': 'Foobar'} - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = EchoServerProtocol listenWS(factory) diff --git a/examples/twisted/websocket/echo_multicore/server.py b/examples/twisted/websocket/echo_multicore/server.py index a87d89863..ce874d10b 100644 --- a/examples/twisted/websocket/echo_multicore/server.py +++ b/examples/twisted/websocket/echo_multicore/server.py @@ -255,7 +255,7 @@ def master(options): ## for i in range(options.workers): - args = [executable, "-u", __file__, "--fd", str(port.fileno()), "--cpuid", str(i)] + args = [executable, "-", __file__, "--fd", str(port.fileno()), "--cpuid", str(i)] # pass on cmd line args to worker .. args.extend(sys.argv[1:]) @@ -357,7 +357,7 @@ def stat(): DEFAULT_WORKERS = psutil.cpu_count() parser = argparse.ArgumentParser(description='Autobahn WebSocket Echo Multicore Server') - parser.add_argument('--wsuri', dest='wsuri', type=str, default=u'ws://127.0.0.1:9000', help='The WebSocket URI the server is listening on, e.g. ws://localhost:9000.') + parser.add_argument('--wsuri', dest='wsuri', type=str, default='ws://127.0.0.1:9000', help='The WebSocket URI the server is listening on, e.g. ws://localhost:9000.') parser.add_argument('--port', dest='port', type=int, default=8080, help='Port to listen on for embedded Web server. Set to 0 to disable.') parser.add_argument('--workers', dest='workers', type=int, default=DEFAULT_WORKERS, help='Number of workers to spawn - should fit the number of (physical) CPU cores.') parser.add_argument('--noaffinity', dest='noaffinity', action="store_true", default=False, help='Do not set worker/CPU affinity.') diff --git a/examples/twisted/websocket/echo_multicore/server_reuseport.py b/examples/twisted/websocket/echo_multicore/server_reuseport.py index 16807de07..a425e3c9a 100644 --- a/examples/twisted/websocket/echo_multicore/server_reuseport.py +++ b/examples/twisted/websocket/echo_multicore/server_reuseport.py @@ -90,7 +90,7 @@ def onClose(self, wasClean, code, reason): log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = MyServerProtocol # reactor.listenTCP(9000, factory) diff --git a/examples/twisted/websocket/echo_service/echows/echoservice.py b/examples/twisted/websocket/echo_service/echows/echoservice.py index 5d80ed650..309282dc1 100644 --- a/examples/twisted/websocket/echo_service/echows/echoservice.py +++ b/examples/twisted/websocket/echo_service/echows/echoservice.py @@ -58,7 +58,7 @@ def __init__(self, port=8080): def startService(self): - factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % self.port) + factory = WebSocketServerFactory("ws://127.0.0.1:%d" % self.port) factory.protocol = EchoServerProtocol # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources diff --git a/examples/twisted/websocket/echo_site/server.py b/examples/twisted/websocket/echo_site/server.py index e8abe203b..6a2724f8d 100644 --- a/examples/twisted/websocket/echo_site/server.py +++ b/examples/twisted/websocket/echo_site/server.py @@ -50,7 +50,7 @@ def onMessage(self, payload, isBinary): log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:8080") + factory = WebSocketServerFactory("ws://127.0.0.1:8080") factory.protocol = EchoServerProtocol resource = WebSocketResource(factory) diff --git a/examples/twisted/websocket/echo_site_tls/server.py b/examples/twisted/websocket/echo_site_tls/server.py index df3408d2b..6351d2846 100644 --- a/examples/twisted/websocket/echo_site_tls/server.py +++ b/examples/twisted/websocket/echo_site_tls/server.py @@ -50,7 +50,7 @@ def onMessage(self, payload, isBinary): contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt') - factory = WebSocketServerFactory(u"wss://127.0.0.1:8080") + factory = WebSocketServerFactory("wss://127.0.0.1:8080") factory.protocol = EchoServerProtocol resource = WebSocketResource(factory) diff --git a/examples/twisted/websocket/echo_tls/client.py b/examples/twisted/websocket/echo_tls/client.py index f3213a000..c1b0baf63 100644 --- a/examples/twisted/websocket/echo_tls/client.py +++ b/examples/twisted/websocket/echo_tls/client.py @@ -54,7 +54,7 @@ def onMessage(self, payload, isBinary): log.startLogging(sys.stdout) parser = OptionParser() - parser.add_option("-u", "--url", dest="url", help="The WebSocket URL", default="wss://127.0.0.1:9000") + parser.add_option("-", "--url", dest="url", help="The WebSocket URL", default="wss://127.0.0.1:9000") (options, args) = parser.parse_args() # create a WS server factory with our protocol diff --git a/examples/twisted/websocket/echo_tls/server.py b/examples/twisted/websocket/echo_tls/server.py index 30c9b804e..6af6dd23e 100644 --- a/examples/twisted/websocket/echo_tls/server.py +++ b/examples/twisted/websocket/echo_tls/server.py @@ -52,7 +52,7 @@ def onMessage(self, payload, isBinary): contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt') - factory = WebSocketServerFactory(u"wss://127.0.0.1:9000") + factory = WebSocketServerFactory("wss://127.0.0.1:9000") # by default, allowedOrigins is "*" and will work fine out of the # box, but we can do better and be more-explicit about what we # allow. We are serving the Web content on 8080, but our WebSocket diff --git a/examples/twisted/websocket/echo_variants/server.py b/examples/twisted/websocket/echo_variants/server.py index 60374b175..30a074c43 100644 --- a/examples/twisted/websocket/echo_variants/server.py +++ b/examples/twisted/websocket/echo_variants/server.py @@ -46,7 +46,7 @@ def onMessage(self, payload, isBinary): log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = EchoServerProtocol listenWS(factory) diff --git a/examples/twisted/websocket/echo_wsfallbacks/server.py b/examples/twisted/websocket/echo_wsfallbacks/server.py index e02b04727..cae6bb41f 100644 --- a/examples/twisted/websocket/echo_wsfallbacks/server.py +++ b/examples/twisted/websocket/echo_wsfallbacks/server.py @@ -51,7 +51,7 @@ def onMessage(self, payload, isBinary): wsPort = 9000 # Our WebSocket server - factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % wsPort) + factory = WebSocketServerFactory("ws://127.0.0.1:%d" % wsPort) factory.protocol = EchoServerProtocol listenWS(factory) diff --git a/examples/twisted/websocket/echo_wsgi/server.py b/examples/twisted/websocket/echo_wsgi/server.py index f6c5002ac..d79fd6ece 100644 --- a/examples/twisted/websocket/echo_wsgi/server.py +++ b/examples/twisted/websocket/echo_wsgi/server.py @@ -62,7 +62,7 @@ def page_home(): log.startLogging(sys.stdout) # create a Twisted Web resource for our WebSocket server - wsFactory = WebSocketServerFactory(u"ws://127.0.0.1:8080") + wsFactory = WebSocketServerFactory("ws://127.0.0.1:8080") wsFactory.protocol = EchoServerProtocol wsResource = WebSocketResource(wsFactory) diff --git a/examples/twisted/websocket/multiproto/server1.py b/examples/twisted/websocket/multiproto/server1.py index a1e0a6b7f..a8d003936 100644 --- a/examples/twisted/websocket/multiproto/server1.py +++ b/examples/twisted/websocket/multiproto/server1.py @@ -131,7 +131,7 @@ def onClose(self, wasClean, code, reason): if __name__ == '__main__': - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = ServiceServerProtocol listenWS(factory) diff --git a/examples/twisted/websocket/ping/server.py b/examples/twisted/websocket/ping/server.py index 45b8fe770..5dbe69531 100644 --- a/examples/twisted/websocket/ping/server.py +++ b/examples/twisted/websocket/ping/server.py @@ -76,7 +76,7 @@ def __init__(self, uri): contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt') - factory = PingServerFactory(u"wss://127.0.0.1:9000") + factory = PingServerFactory("wss://127.0.0.1:9000") factory.protocol = PingServerProtocol listenWS(factory, contextFactory) diff --git a/examples/twisted/websocket/pingpong_keepalive/server.py b/examples/twisted/websocket/pingpong_keepalive/server.py index 03f9c0d3b..077534c08 100644 --- a/examples/twisted/websocket/pingpong_keepalive/server.py +++ b/examples/twisted/websocket/pingpong_keepalive/server.py @@ -42,7 +42,7 @@ log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = WebSocketServerProtocol factory.setProtocolOptions(autoPingInterval=1, autoPingTimeout=3, autoPingSize=20) diff --git a/examples/twisted/websocket/reconnecting/client.py b/examples/twisted/websocket/reconnecting/client.py index 1c50e5e96..5753048e7 100644 --- a/examples/twisted/websocket/reconnecting/client.py +++ b/examples/twisted/websocket/reconnecting/client.py @@ -40,7 +40,7 @@ def onOpen(self): print("WebSocket connection open.") def hello(): - self.sendMessage(u"Hello, world!".encode('utf8')) + self.sendMessage("Hello, world!".encode('utf8')) self.sendMessage(b"\x00\x01\x03\x04", isBinary=True) self.factory.reactor.callLater(1, hello) @@ -79,7 +79,7 @@ def clientConnectionLost(self, connector, reason): log.startLogging(sys.stdout) - factory = MyClientFactory(u"ws://127.0.0.1:9000") + factory = MyClientFactory("ws://127.0.0.1:9000") reactor.connectTCP("127.0.0.1", 9000, factory) reactor.run() diff --git a/examples/twisted/websocket/reconnecting/server.py b/examples/twisted/websocket/reconnecting/server.py index c4c8c16ce..efb68214c 100644 --- a/examples/twisted/websocket/reconnecting/server.py +++ b/examples/twisted/websocket/reconnecting/server.py @@ -58,7 +58,7 @@ def onClose(self, wasClean, code, reason): log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = MyServerProtocol reactor.listenTCP(9000, factory) diff --git a/examples/twisted/websocket/slowsquare/client.py b/examples/twisted/websocket/slowsquare/client.py index e6851c3dd..eab9fa5da 100644 --- a/examples/twisted/websocket/slowsquare/client.py +++ b/examples/twisted/websocket/slowsquare/client.py @@ -59,7 +59,7 @@ def onClose(self, wasClean, code, reason): log.startLogging(sys.stdout) - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = SlowSquareClientProtocol reactor.connectTCP("127.0.0.1", 9000, factory) diff --git a/examples/twisted/websocket/slowsquare/server.py b/examples/twisted/websocket/slowsquare/server.py index 871574608..886f59422 100644 --- a/examples/twisted/websocket/slowsquare/server.py +++ b/examples/twisted/websocket/slowsquare/server.py @@ -70,7 +70,7 @@ def onMessage(self, payload, isBinary): log.startLogging(sys.stdout) - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = SlowSquareServerProtocol reactor.listenTCP(9000, factory) diff --git a/examples/twisted/websocket/streaming/frame_based_client.py b/examples/twisted/websocket/streaming/frame_based_client.py index 5e51d937c..ff0508eaa 100644 --- a/examples/twisted/websocket/streaming/frame_based_client.py +++ b/examples/twisted/websocket/streaming/frame_based_client.py @@ -82,7 +82,7 @@ def onClose(self, wasClean, code, reason): if __name__ == '__main__': - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = FrameBasedHashClientProtocol enableCompression = False diff --git a/examples/twisted/websocket/streaming/frame_based_server.py b/examples/twisted/websocket/streaming/frame_based_server.py index a5f8f1670..31696ba17 100644 --- a/examples/twisted/websocket/streaming/frame_based_server.py +++ b/examples/twisted/websocket/streaming/frame_based_server.py @@ -60,7 +60,7 @@ def onMessageEnd(self): if __name__ == '__main__': - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = FrameBasedHashServerProtocol enableCompression = False diff --git a/examples/twisted/websocket/streaming/message_based_client.py b/examples/twisted/websocket/streaming/message_based_client.py index 44a26a35e..4371489d1 100644 --- a/examples/twisted/websocket/streaming/message_based_client.py +++ b/examples/twisted/websocket/streaming/message_based_client.py @@ -59,7 +59,7 @@ def onMessage(self, payload, isBinary): if __name__ == '__main__': - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = MessageBasedHashClientProtocol connectWS(factory) reactor.run() diff --git a/examples/twisted/websocket/streaming/message_based_server.py b/examples/twisted/websocket/streaming/message_based_server.py index 21f29a5cc..92ab4503a 100644 --- a/examples/twisted/websocket/streaming/message_based_server.py +++ b/examples/twisted/websocket/streaming/message_based_server.py @@ -48,7 +48,7 @@ def onMessage(self, payload, isBinary): if __name__ == '__main__': - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = MessageBasedHashServerProtocol listenWS(factory) reactor.run() diff --git a/examples/twisted/websocket/streaming/streaming_client.py b/examples/twisted/websocket/streaming/streaming_client.py index a36197324..30f4fee04 100644 --- a/examples/twisted/websocket/streaming/streaming_client.py +++ b/examples/twisted/websocket/streaming/streaming_client.py @@ -67,7 +67,7 @@ def onMessage(self, payload, isBinary): if __name__ == '__main__': - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = StreamingHashClientProtocol connectWS(factory) reactor.run() diff --git a/examples/twisted/websocket/streaming/streaming_producer_client.py b/examples/twisted/websocket/streaming/streaming_producer_client.py index 395c35b1e..68341dc49 100644 --- a/examples/twisted/websocket/streaming/streaming_producer_client.py +++ b/examples/twisted/websocket/streaming/streaming_producer_client.py @@ -95,7 +95,7 @@ def onMessage(self, payload, isBinary): if __name__ == '__main__': - factory = WebSocketClientFactory(u"ws://127.0.0.1:9000") + factory = WebSocketClientFactory("ws://127.0.0.1:9000") factory.protocol = StreamingProducerHashClientProtocol connectWS(factory) reactor.run() diff --git a/examples/twisted/websocket/streaming/streaming_server.py b/examples/twisted/websocket/streaming/streaming_server.py index fb9100256..183cef18d 100644 --- a/examples/twisted/websocket/streaming/streaming_server.py +++ b/examples/twisted/websocket/streaming/streaming_server.py @@ -89,7 +89,7 @@ def onMessageEnd(self): if __name__ == '__main__': - factory = WebSocketServerFactory(u"ws://127.0.0.1:9000") + factory = WebSocketServerFactory("ws://127.0.0.1:9000") factory.protocol = StreamingHashServerProtocol listenWS(factory) reactor.run() diff --git a/examples/twisted/websocket/wrapping/client.py b/examples/twisted/websocket/wrapping/client.py index 533fa66a6..9c3058a79 100644 --- a/examples/twisted/websocket/wrapping/client.py +++ b/examples/twisted/websocket/wrapping/client.py @@ -51,7 +51,7 @@ def dataReceived(self, data): wrappedFactory = Factory.forProtocol(HelloClientProtocol) factory = WrappingWebSocketClientFactory(wrappedFactory, - u"ws://127.0.0.1:9000", + "ws://127.0.0.1:9000", enableCompression=False, autoFragmentSize=1024) diff --git a/examples/twisted/websocket/wrapping/server.py b/examples/twisted/websocket/wrapping/server.py index c41d5b81d..a3a998dbe 100644 --- a/examples/twisted/websocket/wrapping/server.py +++ b/examples/twisted/websocket/wrapping/server.py @@ -51,7 +51,7 @@ def dataReceived(self, data): wrappedFactory = Factory.forProtocol(HelloServerProtocol) factory = WrappingWebSocketServerFactory(wrappedFactory, - u"ws://127.0.0.1:9000", + "ws://127.0.0.1:9000", enableCompression=False, autoFragmentSize=1024) diff --git a/examples/twisted/websocket/wxpython/client.py b/examples/twisted/websocket/wxpython/client.py index 2eaf8ebb6..197604ecd 100644 --- a/examples/twisted/websocket/wxpython/client.py +++ b/examples/twisted/websocket/wxpython/client.py @@ -155,7 +155,7 @@ def __init__(self, url, app): app._frame.Show() reactor.registerWxApp(app) - app._factory = MyClientFactory(u"ws://127.0.0.1:9000", app) + app._factory = MyClientFactory("ws://127.0.0.1:9000", app) reactor.connectTCP("127.0.0.1", 9000, app._factory) diff --git a/examples/twisted/websocket/wxpython/server.py b/examples/twisted/websocket/wxpython/server.py index b05aadca3..e3248201c 100644 --- a/examples/twisted/websocket/wxpython/server.py +++ b/examples/twisted/websocket/wxpython/server.py @@ -77,7 +77,7 @@ def broadcast(self, payload, isBinary): log.startLogging(sys.stdout) - factory = BroadcastServerFactory(u"ws://127.0.0.1:9000") + factory = BroadcastServerFactory("ws://127.0.0.1:9000") reactor.listenTCP(9000, factory) reactor.run() diff --git a/requirements-rtd.txt b/requirements-rtd.txt index 6c356b4b4..c99a7e97a 100644 --- a/requirements-rtd.txt +++ b/requirements-rtd.txt @@ -1,5 +1,3 @@ # requirements for building the docs on RTD txaio twisted -trollius; python_version <= '2.7' -asyncio; python_version == '3.3' diff --git a/setup.py b/setup.py index 81ddde415..3942c0fe2 100644 --- a/setup.py +++ b/setup.py @@ -24,24 +24,19 @@ # ############################################################################### -from __future__ import absolute_import - import os import sys import platform from setuptools import setup from setuptools.command.test import test as test_command -# remember if we already had six _before_ installation try: - import six # noqa + import six _HAD_SIX = True except ImportError: _HAD_SIX = False CPY = platform.python_implementation() == 'CPython' -PY3 = sys.version_info >= (3,) -PY33 = (3, 3) <= sys.version_info < (3, 4) # read version string with open('autobahn/_version.py') as f: @@ -58,23 +53,6 @@ "Twisted >= 12.1.0" # MIT license ] -# asyncio dependencies -if PY3: - if PY33: - # "Tulip" - extras_require_asyncio = [ - "asyncio>=3.4.3" # Apache 2.0 - ] - else: - # Python 3.4+ has asyncio builtin - extras_require_asyncio = [] -else: - # backport of asyncio for Python 2 - extras_require_asyncio = [ - "trollius>=2.0", # Apache 2.0 - "futures>=3.0.4" # BSD license - ] - # C-based WebSocket acceleration (only use on CPython, not PyPy!) if CPY and sys.platform != 'win32': # wsaccel does not provide wheels: https://github.com/methane/wsaccel/issues/12 @@ -163,16 +141,9 @@ ] # everything -if PY3: - extras_require_all = extras_require_twisted + extras_require_asyncio + \ - extras_require_accelerate + extras_require_compress + \ - extras_require_serialization + extras_require_encryption + \ - extras_require_scram + extras_require_nvx + extras_require_xbr -else: - extras_require_all = extras_require_twisted + extras_require_asyncio + \ - extras_require_accelerate + extras_require_compress + \ - extras_require_serialization + extras_require_encryption + \ - extras_require_scram + extras_require_nvx +extras_require_all = extras_require_twisted + extras_require_accelerate + extras_require_compress + \ + extras_require_serialization + extras_require_encryption + extras_require_scram + \ + extras_require_nvx + extras_require_xbr # development dependencies extras_require_dev = [ @@ -199,13 +170,12 @@ 'wheel', # MIT license ] -if PY3: - extras_require_dev.extend([ - # pytest-asyncio 0.6 has dropped support for Py <3.5 - # https://github.com/pytest-dev/pytest-asyncio/issues/57 - 'pytest_asyncio<0.6', # Apache 2.0 - 'pytest-aiohttp', # Apache 2.0 - ]) +extras_require_dev.extend([ + # pytest-asyncio 0.6 has dropped support for Py <3.5 + # https://github.com/pytest-dev/pytest-asyncio/issues/57 + 'pytest_asyncio<0.6', # Apache 2.0 + 'pytest-aiohttp', # Apache 2.0 +]) # for testing by users with "python setup.py test" (not Tox, which we use) test_requirements = [ @@ -251,7 +221,7 @@ def run_tests(self): ], extras_require={ 'all': extras_require_all, - 'asyncio': extras_require_asyncio, + 'asyncio': [], # backwards compatibility 'twisted': extras_require_twisted, 'accelerate': extras_require_accelerate, 'compress': extras_require_compress, @@ -308,13 +278,11 @@ def run_tests(self): "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: Implementation :: Jython", diff --git a/twisted/plugins/autobahn_endpoints.py b/twisted/plugins/autobahn_endpoints.py index 2538d292f..7e1bb2ad7 100644 --- a/twisted/plugins/autobahn_endpoints.py +++ b/twisted/plugins/autobahn_endpoints.py @@ -24,8 +24,6 @@ # ############################################################################### -from __future__ import absolute_import - from zope.interface import implementer from twisted.plugin import IPlugin diff --git a/wstest/testee_client_aio.py b/wstest/testee_client_aio.py index d8f638bd4..56ac444c5 100644 --- a/wstest/testee_client_aio.py +++ b/wstest/testee_client_aio.py @@ -24,16 +24,12 @@ # ############################################################################### +import asyncio import argparse import txaio txaio.use_asyncio() -try: - import asyncio -except ImportError: - import trollius as asyncio - import autobahn from autobahn.websocket.util import parse_url @@ -92,8 +88,8 @@ def accept(response): if __name__ == '__main__': parser = argparse.ArgumentParser(description='Autobahn Testee Client (asyncio)') - parser.add_argument('--url', dest='url', type=str, default=u'ws://127.0.0.1:9001', help='The WebSocket fuzzing server URL.') - parser.add_argument('--loglevel', dest='loglevel', type=str, default=u'info', help='Log level, eg "info" or "debug".') + parser.add_argument('--url', dest='url', type=str, default='ws://127.0.0.1:9001', help='The WebSocket fuzzing server URL.') + parser.add_argument('--loglevel', dest='loglevel', type=str, default='info', help='Log level, eg "info" or "debug".') options = parser.parse_args() @@ -105,7 +101,7 @@ def accept(response): loop = asyncio.get_event_loop() - factory.resource = u'/getCaseCount' + factory.resource = '/getCaseCount' factory.endCaseId = None factory.currentCaseId = 0 factory.updateReports = True @@ -119,9 +115,9 @@ def accept(response): factory.currentCaseId += 1 if factory.currentCaseId <= factory.endCaseId: - factory.resource = u"/runCase?case={}&agent={}".format(factory.currentCaseId, factory.agent) + factory.resource = "/runCase?case={}&agent={}".format(factory.currentCaseId, factory.agent) elif factory.updateReports: - factory.resource = u"/updateReports?agent={}".format(factory.agent) + factory.resource = "/updateReports?agent={}".format(factory.agent) factory.updateReports = False else: break diff --git a/wstest/testee_client_tx.py b/wstest/testee_client_tx.py index fa28b1353..fbcb4fc0c 100644 --- a/wstest/testee_client_tx.py +++ b/wstest/testee_client_tx.py @@ -106,8 +106,8 @@ def clientConnectionFailed(self, connector, reason): if __name__ == '__main__': parser = argparse.ArgumentParser(description='Autobahn Testee Client (Twisted)') - parser.add_argument('--url', dest='url', type=str, default=u'ws://127.0.0.1:9001', help='The WebSocket fuzzing server URL.') - parser.add_argument('--loglevel', dest='loglevel', type=str, default=u'info', help='Log level, eg "info" or "debug".') + parser.add_argument('--url', dest='url', type=str, default='ws://127.0.0.1:9001', help='The WebSocket fuzzing server URL.') + parser.add_argument('--loglevel', dest='loglevel', type=str, default='info', help='Log level, eg "info" or "debug".') options = parser.parse_args() diff --git a/wstest/testee_server_aio.py b/wstest/testee_server_aio.py index d5b7fd858..53ce28ea2 100644 --- a/wstest/testee_server_aio.py +++ b/wstest/testee_server_aio.py @@ -25,15 +25,11 @@ ############################################################################### import argparse +import asyncio import txaio txaio.use_asyncio() -try: - import asyncio -except ImportError: - import trollius as asyncio - import autobahn from autobahn.websocket.util import parse_url @@ -112,8 +108,8 @@ def accept(offers): if __name__ == '__main__': parser = argparse.ArgumentParser(description='Autobahn Testee Server (Twisted)') - parser.add_argument('--url', dest='url', type=str, default=u'ws://127.0.0.1:9001', help='The WebSocket fuzzing server URL.') - parser.add_argument('--loglevel', dest='loglevel', type=str, default=u'info', help='Log level, eg "info" or "debug".') + parser.add_argument('--url', dest='url', type=str, default='ws://127.0.0.1:9001', help='The WebSocket fuzzing server URL.') + parser.add_argument('--loglevel', dest='loglevel', type=str, default='info', help='Log level, eg "info" or "debug".') options = parser.parse_args() diff --git a/wstest/testee_server_tx.py b/wstest/testee_server_tx.py index 69c702c43..986903534 100644 --- a/wstest/testee_server_tx.py +++ b/wstest/testee_server_tx.py @@ -112,8 +112,8 @@ def accept(offers): if __name__ == '__main__': parser = argparse.ArgumentParser(description='Autobahn Testee Server (Twisted)') - parser.add_argument('--url', dest='url', type=str, default=u'ws://127.0.0.1:9001', help='The WebSocket fuzzing server URL.') - parser.add_argument('--loglevel', dest='loglevel', type=str, default=u'info', help='Log level, eg "info" or "debug".') + parser.add_argument('--url', dest='url', type=str, default='ws://127.0.0.1:9001', help='The WebSocket fuzzing server URL.') + parser.add_argument('--loglevel', dest='loglevel', type=str, default='info', help='Log level, eg "info" or "debug".') options = parser.parse_args()