From a7be2b25c9574075cfe717382dfe5ced5280f77f Mon Sep 17 00:00:00 2001 From: Client Date: Thu, 21 Jan 2021 20:41:57 +0000 Subject: [PATCH] PubNub SDK v5.0.0 release. --- .pubnub.yml | 8 +- .travis.yml | 28 +- CHANGELOG.md | 6 + DEVELOPER.md | 3 - README.md | 3 +- examples/native_threads/custom_crypto.py | 31 - examples/tornado/__init__.py | 0 examples/tornado/http/Procfile | 1 - examples/tornado/http/__init__.py | 0 examples/tornado/http/app.py | 260 ------- examples/tornado/http/requirements.txt | 2 - examples/twisted/__init__.py | 0 examples/twisted/basic_usage.py | 61 -- examples/twisted/subscribe.py | 38 - pubnub/crypto.py | 80 +- pubnub/crypto_legacy.py | 82 --- pubnub/dtos.py | 5 +- .../add_channel_to_channel_group.py | 5 +- .../list_channels_in_channel_group.py | 5 +- .../remove_channel_from_channel_group.py | 5 +- .../channel_groups/remove_channel_group.py | 5 +- pubnub/endpoints/fetch_messages.py | 8 +- .../file_operations/download_file_asyncio.py | 10 +- .../file_operations/publish_file_message.py | 14 +- pubnub/endpoints/file_operations/send_file.py | 3 +- .../file_operations/send_file_asyncio.py | 14 +- pubnub/endpoints/history.py | 8 +- .../message_actions/get_message_actions.py | 8 +- pubnub/endpoints/mixins.py | 6 +- pubnub/endpoints/push/add_channels_to_push.py | 6 +- pubnub/endpoints/push/list_push_provisions.py | 6 +- .../push/remove_channels_from_push.py | 6 +- pubnub/endpoints/push/remove_device.py | 6 +- pubnub/models/consumer/access_manager.py | 25 +- pubnub/models/consumer/presence.py | 11 +- pubnub/models/consumer/pubsub.py | 20 +- pubnub/models/server/subscribe.py | 10 +- pubnub/pubnub.py | 6 +- pubnub/pubnub_asyncio.py | 124 ++-- pubnub/pubnub_core.py | 2 +- pubnub/pubnub_tornado.py | 685 ------------------ pubnub/pubnub_twisted.py | 412 ----------- pubnub/request_handlers/requests_handler.py | 6 +- pubnub/request_handlers/urllib2_handler.py | 259 ------- pubnub/structures.py | 8 +- pubnub/utils.py | 21 +- requirements-dev.txt | 13 +- requirements-pypy-dev.txt | 4 - requirements27-dev.txt | 6 - requirements34-dev.txt | 7 - requirements35-dev.txt | 6 - requirements36-dev.txt | 6 - requirements37-dev.txt | 6 - scripts/install.sh | 9 - scripts/run-tests.py | 31 +- setup.py | 12 +- .../push/test_remove_channels_from_push.py | 8 +- tests/functional/test_heartbeat.py | 15 +- tests/helper.py | 15 +- .../asyncio/test_channel_groups.py | 56 +- .../integrational/asyncio/test_file_upload.py | 43 +- tests/integrational/asyncio/test_fire.py | 10 +- tests/integrational/asyncio/test_heartbeat.py | 16 +- tests/integrational/asyncio/test_here_now.py | 72 +- .../asyncio/test_history_delete.py | 12 +- .../integrational/asyncio/test_invocations.py | 60 +- .../asyncio/test_message_count.py | 28 +- tests/integrational/asyncio/test_pam.py | 156 ++-- tests/integrational/asyncio/test_publish.py | 121 ++-- tests/integrational/asyncio/test_signal.py | 12 +- tests/integrational/asyncio/test_ssl.py | 10 +- tests/integrational/asyncio/test_state.py | 30 +- tests/integrational/asyncio/test_subscribe.py | 117 ++- tests/integrational/asyncio/test_time.py | 4 +- tests/integrational/asyncio/test_where_now.py | 30 +- .../send_and_download_encrypted_file.yaml | 343 ++++----- .../asyncio/subscription/unsubscribe_all.yaml | 228 ++++-- .../fixtures/twisted/groups/add_channels.yaml | 16 - .../twisted/groups/add_single_channel.yaml | 16 - .../twisted/groups/list_channels.yaml | 16 - .../twisted/groups/remove_channels.yaml | 16 - .../twisted/groups/remove_single_channel.yaml | 16 - .../fixtures/twisted/here_now/global.yaml | 18 - .../fixtures/twisted/here_now/multiple.yaml | 17 - .../fixtures/twisted/here_now/single.yaml | 16 - .../twisted/publish/do_not_store.yaml | 15 - .../fixtures/twisted/publish/forbidden.yaml | 18 - .../fixtures/twisted/publish/invalid_key.yaml | 15 - .../fixtures/twisted/publish/meta_object.yaml | 15 - .../publish/mixed_encrypted_via_get.yaml | 54 -- .../twisted/publish/mixed_via_get.yaml | 54 -- .../twisted/publish/object_via_get.yaml | 15 - .../twisted/state/multiple_channels.yaml | 16 - .../twisted/state/single_channel.yaml | 16 - .../fixtures/twisted/where_now/multiple.yaml | 16 - .../fixtures/twisted/where_now/single.yaml | 16 - .../native_sync/test_file_upload.py | 18 +- tests/integrational/python_v35/__init__.py | 0 .../test_asyncio_async_await_syntax.py | 50 -- .../test_tornado_async_await_syntax.py | 48 -- tests/integrational/tornado/__init__.py | 0 .../tornado/test_channel_groups.py | 131 ---- tests/integrational/tornado/test_fire.py | 28 - tests/integrational/tornado/test_heartbeat.py | 86 --- tests/integrational/tornado/test_here_now.py | 109 --- .../tornado/test_history_delete.py | 32 - .../integrational/tornado/test_invocations.py | 98 --- .../tornado/test_message_count.py | 53 -- tests/integrational/tornado/test_publish.py | 251 ------- tests/integrational/tornado/test_signal.py | 32 - tests/integrational/tornado/test_ssl.py | 42 -- tests/integrational/tornado/test_state.py | 105 --- tests/integrational/tornado/test_subscribe.py | 303 -------- tests/integrational/tornado/test_where_now.py | 70 -- tests/integrational/tornado/tornado_helper.py | 39 - .../tornado/vcr_tornado_decorator.py | 42 -- tests/integrational/twisted/__init__.py | 0 tests/integrational/twisted/test_cg.py | 101 --- tests/integrational/twisted/test_here_now.py | 84 --- tests/integrational/twisted/test_publish.py | 183 ----- tests/integrational/twisted/test_state.py | 55 -- tests/integrational/twisted/test_where_now.py | 49 -- tests/integrational/vcr_asyncio_sleeper.py | 31 +- tests/integrational/vcr_helper.py | 31 +- tests/manual/asyncio/test_reconnections.py | 21 +- tests/manual/tornado/__init__.py | 0 tests/manual/tornado/subscribe_stub.py | 66 -- tests/manual/tornado/test_reconnections.py | 73 -- tests/unit/test_crypto.py | 15 +- 129 files changed, 976 insertions(+), 5449 deletions(-) delete mode 100644 examples/native_threads/custom_crypto.py delete mode 100644 examples/tornado/__init__.py delete mode 100644 examples/tornado/http/Procfile delete mode 100644 examples/tornado/http/__init__.py delete mode 100644 examples/tornado/http/app.py delete mode 100644 examples/tornado/http/requirements.txt delete mode 100644 examples/twisted/__init__.py delete mode 100644 examples/twisted/basic_usage.py delete mode 100644 examples/twisted/subscribe.py delete mode 100644 pubnub/crypto_legacy.py delete mode 100644 pubnub/pubnub_tornado.py delete mode 100644 pubnub/pubnub_twisted.py delete mode 100644 pubnub/request_handlers/urllib2_handler.py delete mode 100644 requirements-pypy-dev.txt delete mode 100644 requirements27-dev.txt delete mode 100644 requirements34-dev.txt delete mode 100644 requirements35-dev.txt delete mode 100644 requirements36-dev.txt delete mode 100644 requirements37-dev.txt delete mode 100644 tests/integrational/fixtures/twisted/groups/add_channels.yaml delete mode 100644 tests/integrational/fixtures/twisted/groups/add_single_channel.yaml delete mode 100644 tests/integrational/fixtures/twisted/groups/list_channels.yaml delete mode 100644 tests/integrational/fixtures/twisted/groups/remove_channels.yaml delete mode 100644 tests/integrational/fixtures/twisted/groups/remove_single_channel.yaml delete mode 100644 tests/integrational/fixtures/twisted/here_now/global.yaml delete mode 100644 tests/integrational/fixtures/twisted/here_now/multiple.yaml delete mode 100644 tests/integrational/fixtures/twisted/here_now/single.yaml delete mode 100644 tests/integrational/fixtures/twisted/publish/do_not_store.yaml delete mode 100644 tests/integrational/fixtures/twisted/publish/forbidden.yaml delete mode 100644 tests/integrational/fixtures/twisted/publish/invalid_key.yaml delete mode 100644 tests/integrational/fixtures/twisted/publish/meta_object.yaml delete mode 100644 tests/integrational/fixtures/twisted/publish/mixed_encrypted_via_get.yaml delete mode 100644 tests/integrational/fixtures/twisted/publish/mixed_via_get.yaml delete mode 100644 tests/integrational/fixtures/twisted/publish/object_via_get.yaml delete mode 100644 tests/integrational/fixtures/twisted/state/multiple_channels.yaml delete mode 100644 tests/integrational/fixtures/twisted/state/single_channel.yaml delete mode 100644 tests/integrational/fixtures/twisted/where_now/multiple.yaml delete mode 100644 tests/integrational/fixtures/twisted/where_now/single.yaml delete mode 100644 tests/integrational/python_v35/__init__.py delete mode 100644 tests/integrational/python_v35/test_asyncio_async_await_syntax.py delete mode 100644 tests/integrational/python_v35/test_tornado_async_await_syntax.py delete mode 100644 tests/integrational/tornado/__init__.py delete mode 100644 tests/integrational/tornado/test_channel_groups.py delete mode 100644 tests/integrational/tornado/test_fire.py delete mode 100644 tests/integrational/tornado/test_heartbeat.py delete mode 100644 tests/integrational/tornado/test_here_now.py delete mode 100644 tests/integrational/tornado/test_history_delete.py delete mode 100644 tests/integrational/tornado/test_invocations.py delete mode 100644 tests/integrational/tornado/test_message_count.py delete mode 100644 tests/integrational/tornado/test_publish.py delete mode 100644 tests/integrational/tornado/test_signal.py delete mode 100644 tests/integrational/tornado/test_ssl.py delete mode 100644 tests/integrational/tornado/test_state.py delete mode 100644 tests/integrational/tornado/test_subscribe.py delete mode 100644 tests/integrational/tornado/test_where_now.py delete mode 100644 tests/integrational/tornado/tornado_helper.py delete mode 100644 tests/integrational/tornado/vcr_tornado_decorator.py delete mode 100644 tests/integrational/twisted/__init__.py delete mode 100644 tests/integrational/twisted/test_cg.py delete mode 100644 tests/integrational/twisted/test_here_now.py delete mode 100644 tests/integrational/twisted/test_publish.py delete mode 100644 tests/integrational/twisted/test_state.py delete mode 100644 tests/integrational/twisted/test_where_now.py delete mode 100644 tests/manual/tornado/__init__.py delete mode 100644 tests/manual/tornado/subscribe_stub.py delete mode 100644 tests/manual/tornado/test_reconnections.py diff --git a/.pubnub.yml b/.pubnub.yml index 7a48e422..8d319fe8 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,8 +1,14 @@ name: python -version: 4.8.1 +version: 5.0.0 schema: 1 scm: github.com/pubnub/python changelog: + - version: v5.0.0 + date: Jan 21, 2021 + changes: + - + text: "Apart from bringing the whole SDK up to date, support for Tornado and Twisted was removed and dependiecies were simplified." + type: improvement - version: v4.8.1 date: Jan 18, 2021 changes: diff --git a/.travis.yml b/.travis.yml index d987512a..b50f7f5c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,31 +11,19 @@ stages: if: | type != pull_request \ AND tag IS blank - - name: "code coverage" - if: | - type == pull_request jobs: include: - stage: "test" - name: 'Python 2.7' - python: '2.7' - script: python scripts/run-tests.py - - name: 'Python 3.4' - python: '3.4' - script: python scripts/run-tests.py - - name: 'Python 3.5' - python: '3.5' - script: python scripts/run-tests.py - name: 'Python 3.6' - python: '3.6' + python: '3.6.12' + script: python scripts/run-tests.py + - name: 'Python 3.7' + python: '3.7.9' script: python scripts/run-tests.py - - name: 'Python PyPi' - python: 'pypy' + - name: 'Python 3.8' + python: '3.8.6' script: python scripts/run-tests.py - - stage: "code coverage" - name: 'Test & Code coverage' - python: '3.6' + - name: 'Python 3.9' + python: '3.9.1' script: python scripts/run-tests.py - after_success: - - python-codacy-coverage -r coverage.xml diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f721cde..2de69a57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## [v5.0.0](https://github.com/pubnub/python/releases/tag/v5.0.0) + +[Full Changelog](https://github.com/pubnub/python/compare/v4.8.1...v5.0.0) + +- ⭐️️ Apart from bringing the whole SDK up to date, support for Tornado and Twisted was removed and dependiecies were simplified. + ## [v4.8.1](https://github.com/pubnub/python/releases/tag/v4.8.1) [Full Changelog](https://github.com/pubnub/python/compare/v4.8.0...v4.8.1) diff --git a/DEVELOPER.md b/DEVELOPER.md index 3fa58e18..536a7b87 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -45,9 +45,6 @@ Twisted is supported by Python 2.7 only. * Test runner: py.test * Source code checker: flake -## Crypto library -We have 2 crypto libraries. By default we use PubNubCryptodome. But for some legacy environment such as Google Cloud PubNubCryptoLegacy should be manually configured, see example here https://github.com/pubnub/python/blob/master/examples/native_threads/custom_crypto.py - ## Daemon mode with Native SDK Daemon mode for all requests are disabled by default. This means that all asynchronous requests including will block the main thread until all the children be closed. If SDK user want to use Java-like behaviour when it's up to him to decide should he wait for response completion or continue program execution, he has to explicitly set daemon mode to true: diff --git a/README.md b/README.md index ed26410c..692a0a38 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,6 @@ -# PubNub Python SDK (V4) +# PubNub Python SDK [![Build Status](https://travis-ci.org/pubnub/python.svg?branch=master)](https://travis-ci.org/pubnub/python) -[![codecov](https://codecov.io/gh/pubnub/python/branch/master/graph/badge.svg)](https://codecov.io/gh/pubnub/python) [![PyPI](https://img.shields.io/pypi/v/pubnub.svg)](https://pypi.python.org/pypi/pubnub/) [![PyPI](https://img.shields.io/pypi/pyversions/pubnub.svg)](https://pypi.python.org/pypi/pubnub/) [![Docs](https://img.shields.io/badge/docs-online-blue.svg)](https://www.pubnub.com/docs/python/pubnub-python-sdk-v4) diff --git a/examples/native_threads/custom_crypto.py b/examples/native_threads/custom_crypto.py deleted file mode 100644 index c29b180f..00000000 --- a/examples/native_threads/custom_crypto.py +++ /dev/null @@ -1,31 +0,0 @@ -# PubNub custom crypto library usage example -import logging -import os -import sys - -d = os.path.dirname -PUBNUB_ROOT = d(d(os.path.dirname(os.path.abspath(__file__)))) -sys.path.append(PUBNUB_ROOT) - -import pubnub - -pubnub.set_stream_logger('pubnub', logging.DEBUG, stream=sys.stdout) - -from examples import pnconf -from pubnub.pubnub import PubNub -from pubnub.crypto_legacy import PubNubCryptoLegacy - -crypto = PubNubCryptoLegacy() - -pnconf.enable_subscribe = False -pnconf.cipher_key = 'blah' -pnconf.crypto_instance = crypto -pubnub = PubNub(pnconf) - - -envelope = pubnub.publish() \ - .channel("blah") \ - .message("hey") \ - .sync() - -print(envelope.result) diff --git a/examples/tornado/__init__.py b/examples/tornado/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/tornado/http/Procfile b/examples/tornado/http/Procfile deleted file mode 100644 index 2e35818f..00000000 --- a/examples/tornado/http/Procfile +++ /dev/null @@ -1 +0,0 @@ -web: python app.py diff --git a/examples/tornado/http/__init__.py b/examples/tornado/http/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/tornado/http/app.py b/examples/tornado/http/app.py deleted file mode 100644 index 6e8ce398..00000000 --- a/examples/tornado/http/app.py +++ /dev/null @@ -1,260 +0,0 @@ -import json -import tornado.ioloop -import tornado.web -import tornado.gen -import sys -import os - -from pubnub import utils -from pubnub.enums import PNStatusCategory, PNOperationType - -d = os.path.dirname -PUBNUB_ROOT = d(d(d(os.path.dirname(os.path.abspath(__file__))))) -APP_ROOT = d(os.path.abspath(__file__)) -sys.path.append(PUBNUB_ROOT) - - -from pubnub.pubnub_tornado import SubscribeListener, TornadoEnvelope -from pubnub.exceptions import PubNubException -from pubnub.pnconfiguration import PNConfiguration -from pubnub.pubnub_tornado import PubNubTornado, PubNubTornadoException -from pubnub.pubnub_tornado import SubscribeCallback -from pubnub.models.consumer.pubsub import PNPublishResult - -pnconf = PNConfiguration() -pnconf.subscribe_key = "sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe" -pnconf.publish_key = "pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52" -pnconf.uuid = "pubnub-demo-api-python-backend" -DEFAULT_CHANNEL = "pubnub_demo_api_python_channel" -EVENTS_CHANNEL = "pubnub_demo_api_python_events" -APP_KEY = utils.uuid() - -pubnub = PubNubTornado(pnconf) - - -class SyncPublishHandler(tornado.web.RequestHandler): - @tornado.gen.coroutine - def get(self): - return self.send_error(501, message={ - "error": "Sync publish not implemented" - }) - - -class AsyncPublishHandler(tornado.web.RequestHandler): - @tornado.gen.coroutine - def get(self): - channel = self.get_argument('channel') - if channel is None: - return self.send_error(500, message={ - "error": "Channel missing" - }) - - try: - envelope = yield pubnub.publish().channel(channel).message("hello from yield-based publish").future() - self.write(json.dumps({ - "original_response": str(envelope.status.original_response) - })) - except PubNubTornadoException as e: - self.send_error(500, message={ - "message": str(e) - }) - - -class AsyncPublishHandler2(tornado.web.RequestHandler): - def data_received(self, chunk): - pass - - @tornado.web.asynchronous - def get(self): - channel = self.get_argument('channel') - if channel is None: - return self.send_error(500, message={ - "error": "Channel missing" - }) - - pubnub.publish().channel(channel).message("hello from callback-based publish")\ - .future().add_done_callback(self.callback) - - def callback(self, future): - if future.exception() is not None: - self.send_error(500, message={ - "message": str(str(future.exception())) - }) - else: - envelope = future.result() - self.write(json.dumps({ - "original_response": str(envelope.status.original_response) - })) - - self.finish() - - -class AppKeyHandler(tornado.web.RequestHandler): - def data_received(self, chunk): - pass - - @tornado.gen.coroutine - def get(self): - self.set_header('Content-Type', 'application/json') - - self.write(json.dumps({ - "app_key": APP_KEY - })) - - -class ListenHandler(tornado.web.RequestHandler): - """ - Long-polling request - """ - def data_received(self, chunk): - pass - - @tornado.gen.coroutine - def get(self): - self.set_header('Content-Type', 'application/json') - - channel = self.get_argument('channel') - if channel is None: - return self.send_error(500, message={ - "error": "Channel missing" - }) - - listener = SubscribeListener() - pubnub.add_listener(listener) - - try: - res = yield listener.wait_for_message_on(channel) - self.write(json.dumps({"message": res.message})) - except PubNubException as e: - self.send_error(500, message={ - "message": str(e) - }) - finally: - pubnub.remove_listener(listener) - - -class ListChannelHandler(tornado.web.RequestHandler): - def data_received(self, chunk): - pass - - @tornado.gen.coroutine - def get(self): - self.set_header('Content-Type', 'application/json') - - self.write(json.dumps({ - "subscribed_channels": pubnub.get_subscribed_channels() - })) - - -class AddChannelHandler(tornado.web.RequestHandler): - def data_received(self, chunk): - pass - - @tornado.gen.coroutine - def get(self): - self.set_header('Content-Type', 'application/json') - - channel = self.get_argument('channel') - if channel is None: - return self.send_error(500, message={ - "error": "Channel missing" - }) - - try: - pubnub.subscribe().channels(channel).execute() - self.write(json.dumps({ - "subscribed_channels": pubnub.get_subscribed_channels() - })) - except PubNubException as e: - self.send_error(500, message={ - "message": str(e) - }) - - -class RemoveChannelHandler(tornado.web.RequestHandler): - def data_received(self, chunk): - pass - - @tornado.gen.coroutine - def get(self): - self.set_header('Content-Type', 'application/json') - - channel = self.get_argument('channel') - if channel is None: - return self.send_error(500, message={ - "error": "Channel missing" - }) - - try: - pubnub.unsubscribe().channels(channel).execute() - self.write(json.dumps({ - "subscribed_channels": pubnub.get_subscribed_channels() - })) - except PubNubException as e: - self.send_error(500, message={ - "message": str(e) - }) - - -def init_events_transmitter(): - """ - Method transmits status events to the specific channel - :return: - """ - class StatusListener(SubscribeCallback): - def status(self, pubnub, status): - def callback(future): - envelope = future.result() - assert isinstance(envelope, TornadoEnvelope) - - result = envelope.result - assert isinstance(result, PNPublishResult) - - print(result) - - event = "unknown" - - if status.operation == PNOperationType.PNSubscribeOperation \ - and status.category == PNStatusCategory.PNConnectedCategory: - event = "Connect" - elif status.operation == PNOperationType.PNUnsubscribeOperation \ - and status.category == PNStatusCategory.PNAcknowledgmentCategory: - event = "Unsubscribe" - - tornado.ioloop.IOLoop.current().add_future( - pubnub.publish().channel('status-' + APP_KEY).message({ - "event": event - }).future(), - callback - ) - - def presence(self, pubnub, presence): - pass - - def message(self, pubnub, message): - pass - - listener = StatusListener() - pubnub.add_listener(listener) - - -def make_app(): - return tornado.web.Application([ - (r"/listen", ListenHandler), - (r"/app_key", AppKeyHandler), - (r"/publish/sync", SyncPublishHandler), - (r"/publish/async", AsyncPublishHandler), - (r"/publish/async2", AsyncPublishHandler2), - (r"/subscription/list", ListChannelHandler), - (r"/subscription/add", AddChannelHandler), - (r"/subscription/remove", RemoveChannelHandler), - ], - static_path=os.path.join(APP_ROOT, "static"), - template_path=os.path.join(APP_ROOT, "templates"),) - - -if __name__ == "__main__": - init_events_transmitter() - app = make_app() - app.listen(8888) - tornado.ioloop.IOLoop.current().start() diff --git a/examples/tornado/http/requirements.txt b/examples/tornado/http/requirements.txt deleted file mode 100644 index de466fb5..00000000 --- a/examples/tornado/http/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -tornado -pubnub diff --git a/examples/twisted/__init__.py b/examples/twisted/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/examples/twisted/basic_usage.py b/examples/twisted/basic_usage.py deleted file mode 100644 index 3b9fcd2d..00000000 --- a/examples/twisted/basic_usage.py +++ /dev/null @@ -1,61 +0,0 @@ -from pubnub.enums import PNStatusCategory -from pubnub.pubnub_twisted import PubNubTwisted as PubNub -from pubnub.pnconfiguration import PNConfiguration -from twisted.internet import reactor -from pubnub.callbacks import SubscribeCallback - - -def main(): - pnconf = PNConfiguration() - pnconf.subscribe_key = 'demo' - pnconf.publish_key = 'demo' - - pubnub = PubNub(pnconf) - - def my_publish_callback(result, status): - # Check whether request successfully completed or not - if not status.is_error(): - envelope = result # noqa - pass # Message successfully published to specified channel. - else: - pass # Handle message publish error. Check 'category' property to find out possible issue - # because of which request did fail. - # Request can be resent using: [status retry]; - - class MySubscribeCallback(SubscribeCallback): - def presence(self, pubnub, presence): - pass # handle incoming presence data - - def status(self, pubnub, status): - if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: - pass # This event happens when radio / connectivity is lost - - elif status.category == PNStatusCategory.PNConnectedCategory: - # Connect event. You can do stuff like publish, and know you'll get it. - # Or just use the connected event to confirm you are subscribed for - # UI / internal notifications, etc - pubnub.publish().channel("awesome_channel").message("Hello!").pn_async(my_publish_callback), - - elif status.category == PNStatusCategory.PNReconnectedCategory: - pass - # Happens as part of our regular operation. This event happens when - # radio / connectivity is lost, then regained. - elif status.category == PNStatusCategory.PNDecryptionErrorCategory: - pass - # Handle message decryption error. Probably client configured to - # encrypt messages and on live data feed it received plain text. - - def message(self, pubnub, message): - # Handle new message stored in message.message - pass - - pubnub.add_listener(MySubscribeCallback()) - pubnub.subscribe().channels('awesome_channel').execute() - - reactor.callLater(30, pubnub.stop) # stop reactor loop after 30 seconds - - pubnub.start() - - -if __name__ == '__main__': - main() diff --git a/examples/twisted/subscribe.py b/examples/twisted/subscribe.py deleted file mode 100644 index 0ad81f43..00000000 --- a/examples/twisted/subscribe.py +++ /dev/null @@ -1,38 +0,0 @@ -# PubNub HereNow usage example -import sys - -import time - - -sys.path.append("../../") - -from pubnub.callbacks import SubscribeCallback -from pubnub.pnconfiguration import PNConfiguration -from pubnub.pubnub_twisted import PubNubTwisted - -pnconf = PNConfiguration() -pnconf.publish_key = "demo" -pnconf.subscribe_key = "demo" -pnconf.enable_subscribe = True - -pubnub = PubNubTwisted(pnconf) - - -class MyListener(SubscribeCallback): - def status(self, pubnub, status): - print("status changed: %s" % status) - - def message(self, pubnub, message): - print("new message: %s" % message) - - def presence(self, pubnub, presence): - pass - - -my_listener = MyListener() - - -pubnub.add_listener(my_listener) - -pubnub.subscribe().channels('my_channel').execute() -time.sleep(60) diff --git a/pubnub/crypto.py b/pubnub/crypto.py index 2525add1..f985a46e 100644 --- a/pubnub/crypto.py +++ b/pubnub/crypto.py @@ -1,30 +1,14 @@ import hashlib import json -import sys import random +from base64 import decodebytes, encodebytes from .crypto_core import PubNubCrypto from Cryptodome.Cipher import AES from Cryptodome.Util.Padding import pad, unpad -Initial16bytes = '0123456789012345' - -if sys.version_info > (3, 0): - v = 3 -else: - v = 2 -try: - from base64 import decodebytes, encodebytes -except ImportError: - from base64 import decodestring, encodestring - -try: - from hashlib import sha256 - digestmod = sha256 -except ImportError: - import Cryptodome.Hash.SHA256 as digestmod - sha256 = digestmod.new +Initial16bytes = '0123456789012345' class PubNubCryptodome(PubNubCrypto): @@ -35,33 +19,19 @@ def encrypt(self, key, msg, use_random_iv=False): secret = self.get_secret(key) initialization_vector = self.get_initialization_vector(use_random_iv) - if v == 3: - cipher = AES.new(bytes(secret[0:32], 'utf-8'), AES.MODE_CBC, bytes(initialization_vector, 'utf-8')) - encrypted_message = cipher.encrypt(self.pad(msg.encode('utf-8'))) - msg_with_iv = self.append_random_iv(encrypted_message, use_random_iv, bytes(initialization_vector, "utf-8")) + cipher = AES.new(bytes(secret[0:32], 'utf-8'), AES.MODE_CBC, bytes(initialization_vector, 'utf-8')) + encrypted_message = cipher.encrypt(self.pad(msg.encode('utf-8'))) + msg_with_iv = self.append_random_iv(encrypted_message, use_random_iv, bytes(initialization_vector, "utf-8")) - return encodebytes(msg_with_iv).decode('utf-8').replace("\n", "") - - else: - cipher = AES.new(secret[0:32], AES.MODE_CBC, initialization_vector) - encrypted_message = cipher.encrypt(self.pad(msg)) - msg_with_iv = self.append_random_iv(encrypted_message, use_random_iv, initialization_vector) - return encodestring(msg_with_iv).replace("\n", "") + return encodebytes(msg_with_iv).decode('utf-8').replace("\n", "") def decrypt(self, key, msg, use_random_iv=False): secret = self.get_secret(key) - if v == 3: - decoded_message = decodebytes(msg.encode("utf-8")) - initialization_vector, extracted_message = self.extract_random_iv(decoded_message, use_random_iv) - cipher = AES.new(bytes(secret[0:32], "utf-8"), AES.MODE_CBC, initialization_vector) - plain = self.depad((cipher.decrypt(extracted_message)).decode('utf-8')) - - else: - decoded_message = decodestring(msg) - initialization_vector, extracted_message = self.extract_random_iv(decoded_message, use_random_iv) - cipher = AES.new(secret[0:32], AES.MODE_CBC, initialization_vector) - plain = self.depad(cipher.decrypt(extracted_message)) + decoded_message = decodebytes(msg.encode("utf-8")) + initialization_vector, extracted_message = self.extract_random_iv(decoded_message, use_random_iv) + cipher = AES.new(bytes(secret[0:32], "utf-8"), AES.MODE_CBC, initialization_vector) + plain = self.depad((cipher.decrypt(extracted_message)).decode('utf-8')) try: return json.loads(plain) @@ -78,10 +48,7 @@ def extract_random_iv(self, message, use_random_iv): if self.pubnub_configuration.use_random_initialization_vector or use_random_iv: return message[0:16], message[16:] else: - if v == 3: - return bytes(Initial16bytes, "utf-8"), message - else: - return Initial16bytes, message + return bytes(Initial16bytes, "utf-8"), message def get_initialization_vector(self, use_random_iv): if self.pubnub_configuration.use_random_initialization_vector or use_random_iv: @@ -91,32 +58,21 @@ def get_initialization_vector(self, use_random_iv): def pad(self, msg, block_size=16): padding = block_size - (len(msg) % block_size) - - if v == 3: - return msg + (chr(padding) * padding).encode('utf-8') - else: - return msg + chr(padding) * padding + return msg + (chr(padding) * padding).encode('utf-8') def depad(self, msg): return msg[0:-ord(msg[-1])] def get_secret(self, key): - if v == 3: - return hashlib.sha256(key.encode("utf-8")).hexdigest() - else: - return hashlib.sha256(key).hexdigest() + return hashlib.sha256(key.encode("utf-8")).hexdigest() class PubNubFileCrypto(PubNubCryptodome): def encrypt(self, key, file): secret = self.get_secret(key) initialization_vector = self.get_initialization_vector(use_random_iv=True) - - if v == 3: - cipher = AES.new(bytes(secret[0:32], "utf-8"), AES.MODE_CBC, bytes(initialization_vector, 'utf-8')) - initialization_vector = bytes(initialization_vector, 'utf-8') - else: - cipher = AES.new(secret[0:32], AES.MODE_CBC, initialization_vector) + cipher = AES.new(bytes(secret[0:32], "utf-8"), AES.MODE_CBC, bytes(initialization_vector, 'utf-8')) + initialization_vector = bytes(initialization_vector, 'utf-8') return self.append_random_iv( cipher.encrypt(pad(file, 16)), @@ -127,10 +83,6 @@ def encrypt(self, key, file): def decrypt(self, key, file): secret = self.get_secret(key) initialization_vector, extracted_file = self.extract_random_iv(file, use_random_iv=True) - - if v == 3: - cipher = AES.new(bytes(secret[0:32], "utf-8"), AES.MODE_CBC, initialization_vector) - else: - cipher = AES.new(secret[0:32], AES.MODE_CBC, initialization_vector) + cipher = AES.new(bytes(secret[0:32], "utf-8"), AES.MODE_CBC, initialization_vector) return unpad(cipher.decrypt(extracted_file), 16) diff --git a/pubnub/crypto_legacy.py b/pubnub/crypto_legacy.py deleted file mode 100644 index 37091677..00000000 --- a/pubnub/crypto_legacy.py +++ /dev/null @@ -1,82 +0,0 @@ -import hashlib -import json -import sys - -from .crypto_core import PubNubCrypto -from Crypto.Cipher import AES - -Initial16bytes = '0123456789012345' - -if sys.version_info > (3, 0): - v = 3 -else: - v = 2 - -try: - from base64 import decodebytes, encodebytes -except ImportError: - from base64 import decodestring, encodestring - -try: - from hashlib import sha256 - digestmod = sha256 -except ImportError: - import Crypto.Hash.SHA256 as digestmod - sha256 = digestmod.new - - -class PubNubCryptoLegacy(PubNubCrypto): - """ - Provides a crypto utils using a legacy pycrypto library. - Useful for GAE standard environment, which doesn't support Cryptodome yet. - - To use it you should explicitly assign it while configuring PNConfiguration() object: - - from pubnub.crypto_legacy import PubNubCryptoLegacy - - config = PNConfiguration() - config.crypto_instance = PubNubCryptoLegacy() - pubnub = PubNub(config) - """ - - def encrypt(self, key, msg): - secret = self.get_secret(key) - - if v == 3: - cipher = AES.new(bytes(secret[0:32], 'utf-8'), AES.MODE_CBC, bytes(Initial16bytes, 'utf-8')) - return encodebytes(cipher.encrypt(self.pad(msg.encode('utf-8')))).decode('utf-8').replace("\n", "") - else: - cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) - return encodestring(cipher.encrypt(self.pad(msg))).replace("\n", "") - - def decrypt(self, key, msg): - secret = self.get_secret(key) - - if v == 3: - cipher = AES.new(bytes(secret[0:32], 'utf-8'), AES.MODE_CBC, bytes(Initial16bytes, 'utf-8')) - plain = self.depad((cipher.decrypt(decodebytes(msg.encode('utf-8')))).decode('utf-8')) - else: - cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes) - plain = self.depad(cipher.decrypt(decodestring(msg))) - - try: - return json.loads(plain) - except Exception: - return plain - - def pad(self, msg, block_size=16): - padding = block_size - (len(msg) % block_size) - - if v == 3: - return msg + (chr(padding) * padding).encode('utf-8') - else: - return msg + chr(padding) * padding - - def depad(self, msg): - return msg[0:-ord(msg[-1])] - - def get_secret(self, key): - if v == 3: - return hashlib.sha256(key.encode("utf-8")).hexdigest() - else: - return hashlib.sha256(key).hexdigest() diff --git a/pubnub/dtos.py b/pubnub/dtos.py index 18c418d5..ae0220b0 100644 --- a/pubnub/dtos.py +++ b/pubnub/dtos.py @@ -1,12 +1,9 @@ -import six - - class SubscribeOperation(object): def __init__(self, channels=None, channel_groups=None, presence_enabled=None, timetoken=None): assert isinstance(channels, (list, tuple)) assert isinstance(channel_groups, (list, tuple)) assert isinstance(presence_enabled, bool) - assert isinstance(timetoken, six.integer_types) + assert isinstance(timetoken, int) self.channels = channels self.channel_groups = channel_groups diff --git a/pubnub/endpoints/channel_groups/add_channel_to_channel_group.py b/pubnub/endpoints/channel_groups/add_channel_to_channel_group.py index 37c60831..191761de 100644 --- a/pubnub/endpoints/channel_groups/add_channel_to_channel_group.py +++ b/pubnub/endpoints/channel_groups/add_channel_to_channel_group.py @@ -1,5 +1,3 @@ -import six - from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_CHANNELS_MISSING, PNERR_GROUP_MISSING @@ -46,8 +44,7 @@ def validate_params(self): if len(self._channels) == 0: raise PubNubException(pn_error=PNERR_CHANNELS_MISSING) - if not isinstance(self._channel_group, six.string_types)\ - or len(self._channel_group) == 0: + if not isinstance(self._channel_group, str) or len(self._channel_group) == 0: raise PubNubException(pn_error=PNERR_GROUP_MISSING) def is_auth_required(self): diff --git a/pubnub/endpoints/channel_groups/list_channels_in_channel_group.py b/pubnub/endpoints/channel_groups/list_channels_in_channel_group.py index fea060e7..ff5d0103 100644 --- a/pubnub/endpoints/channel_groups/list_channels_in_channel_group.py +++ b/pubnub/endpoints/channel_groups/list_channels_in_channel_group.py @@ -1,5 +1,3 @@ -import six - from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_GROUP_MISSING @@ -34,8 +32,7 @@ def http_method(self): def validate_params(self): self.validate_subscribe_key() - if not isinstance(self._channel_group, six.string_types)\ - or len(self._channel_group) == 0: + if not isinstance(self._channel_group, str) or len(self._channel_group) == 0: raise PubNubException(pn_error=PNERR_GROUP_MISSING) def create_response(self, envelope): diff --git a/pubnub/endpoints/channel_groups/remove_channel_from_channel_group.py b/pubnub/endpoints/channel_groups/remove_channel_from_channel_group.py index 85f878a3..3c5dfb52 100644 --- a/pubnub/endpoints/channel_groups/remove_channel_from_channel_group.py +++ b/pubnub/endpoints/channel_groups/remove_channel_from_channel_group.py @@ -1,5 +1,3 @@ -import six - from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_CHANNELS_MISSING, PNERR_GROUP_MISSING @@ -46,8 +44,7 @@ def validate_params(self): if len(self._channels) == 0: raise PubNubException(pn_error=PNERR_CHANNELS_MISSING) - if not isinstance(self._channel_group, six.string_types)\ - or len(self._channel_group) == 0: + if not isinstance(self._channel_group, str) or len(self._channel_group) == 0: raise PubNubException(pn_error=PNERR_GROUP_MISSING) def is_auth_required(self): diff --git a/pubnub/endpoints/channel_groups/remove_channel_group.py b/pubnub/endpoints/channel_groups/remove_channel_group.py index 903dbe67..054eff48 100644 --- a/pubnub/endpoints/channel_groups/remove_channel_group.py +++ b/pubnub/endpoints/channel_groups/remove_channel_group.py @@ -1,5 +1,3 @@ -import six - from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_GROUP_MISSING @@ -34,8 +32,7 @@ def http_method(self): def validate_params(self): self.validate_subscribe_key() - if not isinstance(self._channel_group, six.string_types)\ - or len(self._channel_group) == 0: + if not isinstance(self._channel_group, str) or len(self._channel_group) == 0: raise PubNubException(pn_error=PNERR_GROUP_MISSING) def is_auth_required(self): diff --git a/pubnub/endpoints/fetch_messages.py b/pubnub/endpoints/fetch_messages.py index e6d05351..1365c431 100644 --- a/pubnub/endpoints/fetch_messages.py +++ b/pubnub/endpoints/fetch_messages.py @@ -1,7 +1,5 @@ import logging -import six - from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.enums import HttpMethod, PNOperationType @@ -39,7 +37,7 @@ def channels(self, channels): return self def count(self, count): - assert isinstance(count, six.integer_types) + assert isinstance(count, int) self._count = count return self @@ -47,12 +45,12 @@ def maximum_per_channel(self, maximum_per_channel): return self.count(maximum_per_channel) def start(self, start): - assert isinstance(start, six.integer_types) + assert isinstance(start, int) self._start = start return self def end(self, end): - assert isinstance(end, six.integer_types) + assert isinstance(end, int) self._end = end return self diff --git a/pubnub/endpoints/file_operations/download_file_asyncio.py b/pubnub/endpoints/file_operations/download_file_asyncio.py index 4a142bf7..9364d30a 100644 --- a/pubnub/endpoints/file_operations/download_file_asyncio.py +++ b/pubnub/endpoints/file_operations/download_file_asyncio.py @@ -9,16 +9,16 @@ def create_response(self, envelope, data=None): data = self.decrypt_payload(data) return PNDownloadFileResult(data) - def future(self): - self._download_data = yield from GetFileDownloadUrl(self._pubnub)\ + async def future(self): + self._download_data = await GetFileDownloadUrl(self._pubnub)\ .channel(self._channel)\ .file_name(self._file_name)\ .file_id(self._file_id)\ .future() - downloaded_file = yield from super(DownloadFileAsyncio, self).future() + downloaded_file = await super(DownloadFileAsyncio, self).future() return downloaded_file - def result(self): - response_envelope = yield from self.future() + async def result(self): + response_envelope = await self.future() return response_envelope.result diff --git a/pubnub/endpoints/file_operations/publish_file_message.py b/pubnub/endpoints/file_operations/publish_file_message.py index dc1483a9..55fa8d3c 100644 --- a/pubnub/endpoints/file_operations/publish_file_message.py +++ b/pubnub/endpoints/file_operations/publish_file_message.py @@ -1,4 +1,3 @@ -from collections import OrderedDict from pubnub.endpoints.file_operations.file_based_endpoint import FileOperationEndpoint from pubnub.enums import HttpMethod, PNOperationType from pubnub import utils @@ -60,12 +59,13 @@ def _encrypt_message(self, message): return message def _build_message(self): - message = OrderedDict() # TODO: remove OrderedDict while removing EOL versions of Python (v5 release, SDK-181) - message["message"] = self._message - message["file"] = OrderedDict() - message["file"]["id"] = self._file_id - message["file"]["name"] = self._file_name - + message = { + "message": self._message, + "file": { + "id": self._file_id, + "name": self._file_name + } + } return self._encrypt_message(message) def build_path(self): diff --git a/pubnub/endpoints/file_operations/send_file.py b/pubnub/endpoints/file_operations/send_file.py index 90ab513f..f4e8f7c6 100644 --- a/pubnub/endpoints/file_operations/send_file.py +++ b/pubnub/endpoints/file_operations/send_file.py @@ -1,4 +1,3 @@ -from collections import OrderedDict from pubnub.endpoints.file_operations.file_based_endpoint import FileOperationEndpoint from pubnub.crypto import PubNubFileCrypto @@ -51,7 +50,7 @@ def encrypt_payload(self): def build_file_upload_request(self): file = self.encrypt_payload() - multipart_body = OrderedDict() # TODO: remove OrderedDict while removing EOL versions of Python (v5 release) + multipart_body = {} for form_field in self._file_upload_envelope.result.data["form_fields"]: multipart_body[form_field["key"]] = (None, form_field["value"]) diff --git a/pubnub/endpoints/file_operations/send_file_asyncio.py b/pubnub/endpoints/file_operations/send_file_asyncio.py index a930927b..5934cf21 100644 --- a/pubnub/endpoints/file_operations/send_file_asyncio.py +++ b/pubnub/endpoints/file_operations/send_file_asyncio.py @@ -1,4 +1,3 @@ -import asyncio import aiohttp from pubnub.endpoints.file_operations.send_file import SendFileNative @@ -21,15 +20,14 @@ def options(self): request_options.data = request_options.files return request_options - @asyncio.coroutine - def future(self): - self._file_upload_envelope = yield from FetchFileUploadS3Data(self._pubnub).\ + async def future(self): + self._file_upload_envelope = await FetchFileUploadS3Data(self._pubnub).\ channel(self._channel).\ file_name(self._file_name).future() - response_envelope = yield from super(SendFileNative, self).future() + response_envelope = await super(SendFileNative, self).future() - publish_file_response = yield from PublishFileMessage(self._pubnub).\ + publish_file_response = await PublishFileMessage(self._pubnub).\ channel(self._channel).\ meta(self._meta).\ message(self._message).\ @@ -42,6 +40,6 @@ def future(self): response_envelope.result.timestamp = publish_file_response.result.timestamp return response_envelope - def result(self): - response_envelope = yield from self.future() + async def result(self): + response_envelope = await self.future() return response_envelope.result diff --git a/pubnub/endpoints/history.py b/pubnub/endpoints/history.py index 26b2c32e..c52eae44 100644 --- a/pubnub/endpoints/history.py +++ b/pubnub/endpoints/history.py @@ -1,5 +1,3 @@ -import six - from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.enums import HttpMethod, PNOperationType @@ -25,12 +23,12 @@ def channel(self, channel): return self def start(self, start): - assert isinstance(start, six.integer_types) + assert isinstance(start, int) self._start = start return self def end(self, end): - assert isinstance(end, six.integer_types) + assert isinstance(end, int) self._end = end return self @@ -40,7 +38,7 @@ def reverse(self, reverse): return self def count(self, count): - assert isinstance(count, six.integer_types) + assert isinstance(count, int) self._count = count return self diff --git a/pubnub/endpoints/message_actions/get_message_actions.py b/pubnub/endpoints/message_actions/get_message_actions.py index da20e75b..b54666ea 100644 --- a/pubnub/endpoints/message_actions/get_message_actions.py +++ b/pubnub/endpoints/message_actions/get_message_actions.py @@ -1,5 +1,3 @@ -import six - from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.models.consumer.message_actions import PNGetMessageActionsResult, PNMessageAction @@ -22,17 +20,17 @@ def channel(self, channel): return self def start(self, start): - assert isinstance(start, six.string_types) + assert isinstance(start, str) self._start = start return self def end(self, end): - assert isinstance(end, six.string_types) + assert isinstance(end, str) self._end = end return self def limit(self, limit): - assert isinstance(limit, six.integer_types) + assert isinstance(limit, str) self._limit = limit return self diff --git a/pubnub/endpoints/mixins.py b/pubnub/endpoints/mixins.py index 9d4a22d4..a92014e7 100644 --- a/pubnub/endpoints/mixins.py +++ b/pubnub/endpoints/mixins.py @@ -1,12 +1,10 @@ -import six - from pubnub.errors import PNERR_UUID_MISSING from pubnub.exceptions import PubNubException class UUIDValidatorMixin: def validate_uuid(self): - if self._uuid is None or not isinstance(self._uuid, six.string_types): + if self._uuid is None or not isinstance(self._uuid, str): raise PubNubException(pn_error=PNERR_UUID_MISSING) @@ -17,7 +15,7 @@ def replicate(self, replicate): def ptto(self, timetoken): if timetoken: - assert isinstance(timetoken, six.integer_types) + assert isinstance(timetoken, int) self._ptto = timetoken return self diff --git a/pubnub/endpoints/push/add_channels_to_push.py b/pubnub/endpoints/push/add_channels_to_push.py index 9d3f7569..9318b492 100644 --- a/pubnub/endpoints/push/add_channels_to_push.py +++ b/pubnub/endpoints/push/add_channels_to_push.py @@ -1,5 +1,3 @@ -import six - from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_CHANNEL_MISSING, PNERR_PUSH_DEVICE_MISSING, PNERROR_PUSH_TYPE_MISSING, \ PNERR_PUSH_TOPIC_MISSING @@ -76,14 +74,14 @@ def validate_params(self): if not isinstance(self._channels, list) or len(self._channels) == 0: raise PubNubException(pn_error=PNERR_CHANNEL_MISSING) - if not isinstance(self._device_id, six.string_types) or len(self._device_id) == 0: + if not isinstance(self._device_id, str) or len(self._device_id) == 0: raise PubNubException(pn_error=PNERR_PUSH_DEVICE_MISSING) if self._push_type is None: raise PubNubException(pn_error=PNERROR_PUSH_TYPE_MISSING) if self._push_type == PNPushType.APNS2: - if not isinstance(self._topic, six.string_types) or len(self._topic) == 0: + if not isinstance(self._topic, str) or len(self._topic) == 0: raise PubNubException(pn_error=PNERR_PUSH_TOPIC_MISSING) def create_response(self, envelope): diff --git a/pubnub/endpoints/push/list_push_provisions.py b/pubnub/endpoints/push/list_push_provisions.py index 3b8ae01f..c9cec7dd 100644 --- a/pubnub/endpoints/push/list_push_provisions.py +++ b/pubnub/endpoints/push/list_push_provisions.py @@ -1,5 +1,3 @@ -import six - from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_PUSH_DEVICE_MISSING, PNERROR_PUSH_TYPE_MISSING, PNERR_PUSH_TOPIC_MISSING from pubnub.exceptions import PubNubException @@ -65,14 +63,14 @@ def http_method(self): def validate_params(self): self.validate_subscribe_key() - if not isinstance(self._device_id, six.string_types) or len(self._device_id) == 0: + if not isinstance(self._device_id, str) or len(self._device_id) == 0: raise PubNubException(pn_error=PNERR_PUSH_DEVICE_MISSING) if self._push_type is None: raise PubNubException(pn_error=PNERROR_PUSH_TYPE_MISSING) if self._push_type == PNPushType.APNS2: - if not isinstance(self._topic, six.string_types) or len(self._topic) == 0: + if not isinstance(self._topic, str) or len(self._topic) == 0: raise PubNubException(pn_error=PNERR_PUSH_TOPIC_MISSING) def create_response(self, channels): diff --git a/pubnub/endpoints/push/remove_channels_from_push.py b/pubnub/endpoints/push/remove_channels_from_push.py index 622ef832..31432564 100644 --- a/pubnub/endpoints/push/remove_channels_from_push.py +++ b/pubnub/endpoints/push/remove_channels_from_push.py @@ -1,5 +1,3 @@ -import six - from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_CHANNEL_MISSING, PNERR_PUSH_DEVICE_MISSING, PNERROR_PUSH_TYPE_MISSING, \ PNERR_PUSH_TOPIC_MISSING @@ -74,14 +72,14 @@ def validate_params(self): if not isinstance(self._channels, list) or len(self._channels) == 0: raise PubNubException(pn_error=PNERR_CHANNEL_MISSING) - if not isinstance(self._device_id, six.string_types) or len(self._device_id) == 0: + if not isinstance(self._device_id, str) or len(self._device_id) == 0: raise PubNubException(pn_error=PNERR_PUSH_DEVICE_MISSING) if self._push_type is None: raise PubNubException(pn_error=PNERROR_PUSH_TYPE_MISSING) if self._push_type == PNPushType.APNS2: - if not isinstance(self._topic, six.string_types) or len(self._topic) == 0: + if not isinstance(self._topic, str) or len(self._topic) == 0: raise PubNubException(pn_error=PNERR_PUSH_TOPIC_MISSING) def create_response(self, envelope): diff --git a/pubnub/endpoints/push/remove_device.py b/pubnub/endpoints/push/remove_device.py index b021e4ce..06c69717 100644 --- a/pubnub/endpoints/push/remove_device.py +++ b/pubnub/endpoints/push/remove_device.py @@ -1,5 +1,3 @@ -import six - from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_PUSH_DEVICE_MISSING, PNERROR_PUSH_TYPE_MISSING, PNERR_PUSH_TOPIC_MISSING from pubnub.exceptions import PubNubException @@ -65,14 +63,14 @@ def http_method(self): def validate_params(self): self.validate_subscribe_key() - if not isinstance(self._device_id, six.string_types) or len(self._device_id) == 0: + if not isinstance(self._device_id, str) or len(self._device_id) == 0: raise PubNubException(pn_error=PNERR_PUSH_DEVICE_MISSING) if self._push_type is None: raise PubNubException(pn_error=PNERROR_PUSH_TYPE_MISSING) if self._push_type == PNPushType.APNS2: - if not isinstance(self._topic, six.string_types) or len(self._topic) == 0: + if not isinstance(self._topic, str) or len(self._topic) == 0: raise PubNubException(pn_error=PNERR_PUSH_TOPIC_MISSING) def create_response(self, envelope): diff --git a/pubnub/models/consumer/access_manager.py b/pubnub/models/consumer/access_manager.py index 6190fc5d..e2f3c12c 100644 --- a/pubnub/models/consumer/access_manager.py +++ b/pubnub/models/consumer/access_manager.py @@ -1,10 +1,9 @@ -import six """ Possible responses of PAM request """ -class _PAMResult(object): +class _PAMResult: def __init__(self, level, subscribe_key, channels, groups, uuids, ttl=None, r=None, w=None, m=None, d=None): self.level = level self.subscribe_key = subscribe_key @@ -29,7 +28,7 @@ def from_json(cls, json_input): if 'channel' in json_input: channel_name = json_input['channel'] constructed_auth_keys = {} - for auth_key_name, value in six.iteritems(json_input['auths']): + for auth_key_name, value in json_input['auths'].items(): constructed_auth_keys[auth_key_name] = PNAccessManagerKeyData.from_json(value) constructed_channels[channel_name] = PNAccessManagerChannelData( @@ -39,10 +38,10 @@ def from_json(cls, json_input): ) if 'channel-group' in json_input: - if isinstance(json_input['channel-group'], six.string_types): + if isinstance(json_input['channel-group'], str): group_name = json_input['channel-group'] constructed_auth_keys = {} - for auth_key_name, value in six.iteritems(json_input['auths']): + for auth_key_name, value in json_input['auths'].items(): constructed_auth_keys[auth_key_name] = PNAccessManagerKeyData.from_json(value) constructed_groups[group_name] = PNAccessManagerChannelGroupData( name=group_name, @@ -51,10 +50,10 @@ def from_json(cls, json_input): ) if 'channel-groups' in json_input: - if isinstance(json_input['channel-groups'], six.string_types): + if isinstance(json_input['channel-groups'], str): group_name = json_input['channel-groups'] constructed_auth_keys = {} - for auth_key_name, value in six.iteritems(json_input['auths']): + for auth_key_name, value in json_input['auths'].items(): constructed_auth_keys[auth_key_name] = PNAccessManagerKeyData.from_json(value) constructed_groups[group_name] = PNAccessManagerChannelGroupData( name=group_name, @@ -62,17 +61,15 @@ def from_json(cls, json_input): ttl=ttl ) if isinstance(json_input['channel-groups'], dict): - for group_name, value in six.iteritems(json_input['channel-groups']): - constructed_groups[group_name] = \ - PNAccessManagerChannelGroupData.from_json(group_name, value) + for group_name, value in json_input['channel-groups'].items(): + constructed_groups[group_name] = PNAccessManagerChannelGroupData.from_json(group_name, value) if 'channels' in json_input: - for channel_name, value in six.iteritems(json_input['channels']): - constructed_channels[channel_name] = \ - PNAccessManagerChannelData.from_json(channel_name, value) + for channel_name, value in json_input['channels'].items(): + constructed_channels[channel_name] = PNAccessManagerChannelData.from_json(channel_name, value) if 'uuids' in json_input: - for uuid, value in six.iteritems(json_input['uuids']): + for uuid, value in json_input['uuids'].items(): constructed_uuids[uuid] = PNAccessManagerUuidsData.from_json(uuid, value) return cls( diff --git a/pubnub/models/consumer/presence.py b/pubnub/models/consumer/presence.py index 5abb0d61..2461cbd6 100644 --- a/pubnub/models/consumer/presence.py +++ b/pubnub/models/consumer/presence.py @@ -1,10 +1,7 @@ -import six - - -class PNHereNowResult(object): +class PNHereNowResult: def __init__(self, total_channels, total_occupancy, channels): - assert isinstance(total_channels, six.integer_types) - assert isinstance(total_occupancy, six.integer_types) + assert isinstance(total_channels, int) + assert isinstance(total_occupancy, int) self.total_channels = total_channels self.total_occupancy = total_occupancy @@ -50,7 +47,7 @@ def from_json(cls, envelope, channel_names): elif 'uuids' in envelope and isinstance(envelope['uuids'], list): occupants = [] for user in envelope['uuids']: - if isinstance(user, six.string_types): + if isinstance(user, str): occupants.append(PNHereNowOccupantsData(user, None)) else: state = user['state'] if 'state' in user else None diff --git a/pubnub/models/consumer/pubsub.py b/pubnub/models/consumer/pubsub.py index 8c8e3eac..87cdfcca 100644 --- a/pubnub/models/consumer/pubsub.py +++ b/pubnub/models/consumer/pubsub.py @@ -1,5 +1,3 @@ -import six - from pubnub.models.consumer.message_actions import PNMessageAction @@ -8,15 +6,15 @@ def __init__(self, message, subscription, channel, timetoken, user_metadata=None assert message is not None if subscription is not None: - assert isinstance(subscription, six.string_types) + assert isinstance(subscription, str) if channel is not None: - assert isinstance(channel, six.string_types) + assert isinstance(channel, str) if publisher is not None: - assert isinstance(publisher, six.string_types) + assert isinstance(publisher, str) - assert isinstance(timetoken, six.integer_types) + assert isinstance(timetoken, int) if user_metadata is not None: assert isinstance(user_metadata, object) @@ -54,11 +52,11 @@ class PNPresenceEventResult(object): def __init__(self, event, uuid, timestamp, occupancy, subscription, channel, timetoken, state, join, leave, timeout, user_metadata=None): - assert isinstance(event, six.string_types) - assert isinstance(timestamp, six.integer_types) - assert isinstance(occupancy, six.integer_types) - assert isinstance(channel, six.string_types) - assert isinstance(timetoken, six.integer_types) + assert isinstance(event, str) + assert isinstance(timestamp, int) + assert isinstance(occupancy, int) + assert isinstance(channel, str) + assert isinstance(timetoken, int) if user_metadata is not None: assert isinstance(user_metadata, object) diff --git a/pubnub/models/server/subscribe.py b/pubnub/models/server/subscribe.py index 9e85a280..87793a83 100644 --- a/pubnub/models/server/subscribe.py +++ b/pubnub/models/server/subscribe.py @@ -1,6 +1,3 @@ -import six - - class SubscribeEnvelope: def __init__(self, messages=None, metadata=None): assert isinstance(messages, (list, None)) @@ -71,9 +68,9 @@ def from_json(cls, json_input): class PresenceEnvelope: def __init__(self, action, uuid, occupancy, timestamp, data=None): - assert isinstance(action, six.string_types) - assert isinstance(occupancy, six.integer_types) - assert isinstance(timestamp, six.integer_types) + assert isinstance(action, str) + assert isinstance(occupancy, int) + assert isinstance(timestamp, int) if data is not None: assert isinstance(data, dict) @@ -92,7 +89,6 @@ def extract_value(cls, json, key): @classmethod def from_json_payload(cls, json): - return PresenceEnvelope( action=cls.extract_value(json, 'action'), uuid=cls.extract_value(json, 'uuid'), diff --git a/pubnub/pubnub.py b/pubnub/pubnub.py index 18d3793e..a98865c7 100644 --- a/pubnub/pubnub.py +++ b/pubnub/pubnub.py @@ -3,7 +3,7 @@ import threading from threading import Event -from six.moves.queue import Queue, Empty +from queue import Queue, Empty from . import utils from .request_handlers.base import BaseRequestHandler @@ -316,7 +316,7 @@ def _stop_subscribe_loop(self): sc.cancel() -class NativePeriodicCallback(object): +class NativePeriodicCallback: def __init__(self, callback, callback_time): self._callback = callback self._callback_time = callback_time @@ -434,7 +434,7 @@ def wait_for_presence_on(self, *channel_names): continue -class NonSubscribeListener(object): +class NonSubscribeListener: def __init__(self): self.result = None self.status = None diff --git a/pubnub/pubnub_asyncio.py b/pubnub/pubnub_asyncio.py index 3b39f9e4..ad010f04 100644 --- a/pubnub/pubnub_asyncio.py +++ b/pubnub/pubnub_asyncio.py @@ -3,10 +3,11 @@ import asyncio import aiohttp import math -import six import time +import urllib from asyncio import Event, Queue, Semaphore +from yarl import URL from pubnub.models.consumer.common import PNStatus from .endpoints.presence.heartbeat import Heartbeat @@ -19,15 +20,12 @@ from .structures import ResponseInfo, RequestOptions from .enums import PNStatusCategory, PNHeartbeatNotificationOptions, PNOperationType, PNReconnectionPolicy from .callbacks import SubscribeCallback, ReconnectionCallback -from .errors import PNERR_SERVER_ERROR, PNERR_CLIENT_ERROR, PNERR_JSON_DECODING_FAILED, PNERR_REQUEST_CANCELLED, \ +from .errors import PNERR_SERVER_ERROR, PNERR_CLIENT_ERROR, PNERR_JSON_DECODING_FAILED, PNERR_REQUEST_CANCELLED,\ PNERR_CLIENT_TIMEOUT from .exceptions import PubNubException logger = logging.getLogger("pubnub") -# Major version of aiohttp library -AIOHTTP_V = int(aiohttp.__version__[0]) - class PubNubAsyncio(PubNubCore): """ @@ -41,10 +39,7 @@ def __init__(self, config, custom_event_loop=None): self._connector = None self._session = None - if AIOHTTP_V in (0, 1): - self.set_connector(aiohttp.TCPConnector(conn_timeout=config.connect_timeout, verify_ssl=True)) - else: - self.set_connector(aiohttp.TCPConnector(verify_ssl=True)) + self.set_connector(aiohttp.TCPConnector(verify_ssl=True)) if self.config.enable_subscribe: self._subscription_manager = AsyncioSubscriptionManager(self) @@ -60,11 +55,11 @@ def set_connector(self, cn): self._connector = cn - if AIOHTTP_V in (0, 1): - self._session = aiohttp.ClientSession(loop=self.event_loop, connector=self._connector) - else: - self._session = aiohttp.ClientSession(loop=self.event_loop, conn_timeout=self.config.connect_timeout, - connector=self._connector) + self._session = aiohttp.ClientSession( + loop=self.event_loop, + conn_timeout=self.config.connect_timeout, + connector=self._connector + ) def stop(self): self._session.close() @@ -80,15 +75,13 @@ def request_sync(self, *args): def request_deferred(self, *args): raise NotImplementedError - @asyncio.coroutine - def request_result(self, options_func, cancellation_event): - envelope = yield from self._request_helper(options_func, cancellation_event) + async def request_result(self, options_func, cancellation_event): + envelope = await self._request_helper(options_func, cancellation_event) return envelope.result - @asyncio.coroutine - def request_future(self, options_func, cancellation_event): + async def request_future(self, options_func, cancellation_event): try: - res = yield from self._request_helper(options_func, cancellation_event) + res = await self._request_helper(options_func, cancellation_event) return res except PubNubException as e: return PubNubAsyncioException( @@ -124,8 +117,7 @@ def request_future(self, options_func, cancellation_event): e) ) - @asyncio.coroutine - def _request_helper(self, options_func, cancellation_event): + async def _request_helper(self, options_func, cancellation_event): """ Query string should be provided as a manually serialized and encoded string. @@ -146,7 +138,7 @@ def _request_helper(self, options_func, cancellation_event): params_to_merge_in = {} if options.operation_type == PNOperationType.PNPublishOperation: - params_to_merge_in['seqn'] = yield from self._publish_sequence_manager.get_next_sequence() + params_to_merge_in['seqn'] = await self._publish_sequence_manager.get_next_sequence() options.merge_params_in(params_to_merge_in) @@ -155,20 +147,19 @@ def _request_helper(self, options_func, cancellation_event): else: url = utils.build_url(scheme="", origin="", path=options.path, params=options.query_string) + url = URL(url, encoded=True) + logger.debug("%s %s %s" % (options.method_string, url, options.data)) if options.request_headers: self.headers.update(options.request_headers) - if AIOHTTP_V in (1, 2): - from yarl import URL - url = URL(url, encoded=True) - try: start_timestamp = time.time() - response = yield from asyncio.wait_for( + response = await asyncio.wait_for( self._session.request( - options.method_string, url, + options.method_string, + url, headers=self.headers, data=options.data if options.data else None, allow_redirects=options.allow_redirects @@ -182,12 +173,12 @@ def _request_helper(self, options_func, cancellation_event): raise if not options.non_json_response: - body = yield from response.text() + body = await response.text() else: if isinstance(response.content, bytes): body = response.content # TODO: simplify this logic within the v5 release else: - body = yield from response.read() + body = await response.read() if cancellation_event is not None and cancellation_event.is_set(): return @@ -196,8 +187,8 @@ def _request_helper(self, options_func, cancellation_event): status_category = PNStatusCategory.PNUnknownCategory if response is not None: - request_url = six.moves.urllib.parse.urlparse(str(response.url)) - query = six.moves.urllib.parse.parse_qs(request_url.query) + request_url = urllib.parse.urlparse(str(response.url)) + query = urllib.parse.parse_qs(request_url.query) uuid = None auth_key = None @@ -288,17 +279,16 @@ def __init__(self, pubnub): self._task = None super(AsyncioReconnectionManager, self).__init__(pubnub) - @asyncio.coroutine - def _register_heartbeat_timer(self): + async def _register_heartbeat_timer(self): while True: self._recalculate_interval() - yield from asyncio.sleep(self._timer_interval) + await asyncio.sleep(self._timer_interval) logger.debug("reconnect loop at: %s" % utils.datetime_now()) try: - yield from self._pubnub.time().future() + await self._pubnub.time().future() self._connection_errors = 1 self._callback.on_reconnect() break @@ -325,9 +315,8 @@ def __init__(self, ioloop, provided_max_sequence): self._lock = asyncio.Lock() self._event_loop = ioloop - @asyncio.coroutine - def get_next_sequence(self): - with (yield from self._lock): + async def get_next_sequence(self): + async with self._lock: if self.max_sequence == self.next_sequence: self.next_sequence = 1 else: @@ -396,11 +385,10 @@ def stop(self): if self._subscribe_loop_task is not None and not self._subscribe_loop_task.cancelled(): self._subscribe_loop_task.cancel() - @asyncio.coroutine - def _start_subscribe_loop(self): + async def _start_subscribe_loop(self): self._stop_subscribe_loop() - yield from self._subscription_lock.acquire() + await self._subscription_lock.acquire() combined_channels = self._subscription_state.prepare_channel_list(True) combined_groups = self._subscription_state.prepare_channel_group_list(True) @@ -416,7 +404,7 @@ def _start_subscribe_loop(self): .filter_expression(self._pubnub.config.filter_expression) .future()) - e = yield from self._subscribe_request_task + e = await self._subscribe_request_task if self._subscribe_request_task.cancelled(): self._subscription_lock.release() @@ -469,8 +457,7 @@ def _register_heartbeat_timer(self): if not self._should_stop: self._heartbeat_periodic_callback.start() - @asyncio.coroutine - def _perform_heartbeat_loop(self): + async def _perform_heartbeat_loop(self): if self._heartbeat_call is not None: # TODO: cancel call pass @@ -491,7 +478,7 @@ def _perform_heartbeat_loop(self): .cancellation_event(cancellation_event) .future()) - envelope = yield from heartbeat_call + envelope = await heartbeat_call heartbeat_verbosity = self._pubnub.config.heartbeat_notification_options if envelope.status.is_error: @@ -515,9 +502,8 @@ def _perform_heartbeat_loop(self): def _send_leave(self, unsubscribe_operation): asyncio.ensure_future(self._send_leave_helper(unsubscribe_operation)) - @asyncio.coroutine - def _send_leave_helper(self, unsubscribe_operation): - envelope = yield from Leave(self._pubnub) \ + async def _send_leave_helper(self, unsubscribe_operation): + envelope = await Leave(self._pubnub) \ .channels(unsubscribe_operation.channels) \ .channel_groups(unsubscribe_operation.channel_groups).future() @@ -525,15 +511,13 @@ def _send_leave_helper(self, unsubscribe_operation): class AsyncioSubscribeMessageWorker(SubscribeMessageWorker): - @asyncio.coroutine - def run(self): - yield from self._take_message() + async def run(self): + await self._take_message() - @asyncio.coroutine - def _take_message(self): + async def _take_message(self): while True: try: - msg = yield from self._queue.get() + msg = await self._queue.get() if msg is not None: self._process_incoming_payload(msg) self._queue.task_done() @@ -635,12 +619,11 @@ def message(self, pubnub, message): def presence(self, pubnub, presence): self.presence_queue.put_nowait(presence) - @asyncio.coroutine - def _wait_for(self, coro): + async def _wait_for(self, coro): scc_task = asyncio.ensure_future(coro) err_task = asyncio.ensure_future(self.error_queue.get()) - yield from asyncio.wait([ + await asyncio.wait([ scc_task, err_task ], return_when=asyncio.FIRST_COMPLETED) @@ -654,26 +637,23 @@ def _wait_for(self, coro): err_task.cancel() return scc_task.result() - @asyncio.coroutine - def wait_for_connect(self): + async def wait_for_connect(self): if not self.connected_event.is_set(): - yield from self._wait_for(self.connected_event.wait()) + await self._wait_for(self.connected_event.wait()) else: raise Exception("instance is already connected") - @asyncio.coroutine - def wait_for_disconnect(self): + async def wait_for_disconnect(self): if not self.disconnected_event.is_set(): - yield from self._wait_for(self.disconnected_event.wait()) + await self._wait_for(self.disconnected_event.wait()) else: raise Exception("instance is already disconnected") - @asyncio.coroutine - def wait_for_message_on(self, *channel_names): + async def wait_for_message_on(self, *channel_names): channel_names = list(channel_names) while True: try: - env = yield from self._wait_for(self.message_queue.get()) + env = await self._wait_for(self.message_queue.get()) if env.channel in channel_names: return env else: @@ -681,12 +661,11 @@ def wait_for_message_on(self, *channel_names): finally: self.message_queue.task_done() - @asyncio.coroutine - def wait_for_presence_on(self, *channel_names): + async def wait_for_presence_on(self, *channel_names): channel_names = list(channel_names) while True: try: - env = yield from self._wait_for(self.presence_queue.get()) + env = await self._wait_for(self.presence_queue.get()) if env.channel in channel_names: return env else: @@ -704,8 +683,7 @@ def __init__(self): asyncio.get_event_loop()) self._timer.start() - @asyncio.coroutine - def _start_clean_up_timer(self): + async def _start_clean_up_timer(self): self.clean_up_telemetry_data() def _stop_clean_up_timer(self): diff --git a/pubnub/pubnub_core.py b/pubnub/pubnub_core.py index 47a2d469..af059e28 100644 --- a/pubnub/pubnub_core.py +++ b/pubnub/pubnub_core.py @@ -65,7 +65,7 @@ class PubNubCore: """A base class for PubNub Python API implementations""" - SDK_VERSION = "4.8.1" + SDK_VERSION = "5.0.0" SDK_NAME = "PubNub-Python" TIMESTAMP_DIVIDER = 1000 diff --git a/pubnub/pubnub_tornado.py b/pubnub/pubnub_tornado.py deleted file mode 100644 index d2499ab7..00000000 --- a/pubnub/pubnub_tornado.py +++ /dev/null @@ -1,685 +0,0 @@ -import json -import logging -import time -import datetime - -import math -import six -import tornado.gen -import tornado.httpclient -import tornado.ioloop -from tornado import gen - -from tornado import ioloop -from tornado import stack_context -from tornado.concurrent import Future -from tornado.ioloop import PeriodicCallback -from tornado.locks import Event, Semaphore, Lock -from tornado.queues import Queue -from tornado.simple_httpclient import SimpleAsyncHTTPClient - -from . import utils -from .models.consumer.common import PNStatus -from .callbacks import SubscribeCallback, ReconnectionCallback -from .endpoints.presence.leave import Leave -from .endpoints.pubsub.subscribe import Subscribe -from .enums import PNStatusCategory, PNHeartbeatNotificationOptions, PNOperationType, PNReconnectionPolicy -from .errors import PNERR_SERVER_ERROR, PNERR_CLIENT_ERROR, PNERR_JSON_DECODING_FAILED, PNERR_CLIENT_TIMEOUT, \ - PNERR_CONNECTION_ERROR -from .exceptions import PubNubException -from .managers import SubscriptionManager, PublishSequenceManager, ReconnectionManager, TelemetryManager -from .pubnub_core import PubNubCore -from .structures import ResponseInfo -from .workers import SubscribeMessageWorker - -logger = logging.getLogger("pubnub") - -tornado.httpclient.AsyncHTTPClient.configure(SimpleAsyncHTTPClient) - - -class PubNubTornado(PubNubCore): - MAX_CLIENTS = 1000 - - def stop(self): - self.ioloop.stop() - - def start(self): - self.ioloop.start() - - def timeout(self, delay, callback, *args): - handle = None - - def cancel(): - self.ioloop.remove_timeout(handle) - - def cb(): - if callback is not None: - callback(*args) - - handle = self.ioloop.add_timeout(time.time() + float(delay), cb) - - return cancel - - def sdk_platform(self): - return "-Tornado" - - def __init__(self, config, custom_ioloop=None): - super(PubNubTornado, self).__init__(config) - self.ioloop = custom_ioloop or ioloop.IOLoop.instance() - - if self.config.enable_subscribe: - self._subscription_manager = TornadoSubscriptionManager(self) - - self._publish_sequence_manager = TornadoPublishSequenceManager(PubNubCore.MAX_SEQUENCE) - - self.http = tornado.httpclient.AsyncHTTPClient(max_clients=PubNubTornado.MAX_CLIENTS) - self.id = None - - self.headers = { - 'User-Agent': self.sdk_name, - 'Accept-Encoding': 'utf-8' - } - - self._telemetry_manager = TornadoTelemetryManager(self.ioloop) - - def request_sync(self, *args): - raise NotImplementedError - - def request_async(self, *args): - raise NotImplementedError - - def request_deferred(self, *args): - raise NotImplementedError - - @tornado.gen.coroutine - def request_result(self, options_func, cancellation_event): - try: - envelope = yield self._request_helper(options_func, cancellation_event) - raise tornado.gen.Return(envelope.result) - except PubNubTornadoException as ex: - raise ex.status.error_data.exception - - @tornado.gen.coroutine - def request_future(self, options_func, cancellation_event): - try: - e = yield self._request_helper(options_func, cancellation_event) - except PubNubTornadoException as ex: - e = ex - except Exception as ex: - e = PubNubTornadoException( - result=None, - status=options_func().create_status(PNStatusCategory.PNUnknownCategory, - None, - None, - ex) - ) - - raise tornado.gen.Return(e) - - # REFACTOR: quickly adjusted to fit the new result() and future() endpoints - def _request_helper(self, options_func, cancellation_event): - if cancellation_event is not None: - assert isinstance(cancellation_event, Event) - - # validate_params() - options = options_func() - - create_response = options.create_response - create_status_response = options.create_status - - params_to_merge_in = {} - - if options.operation_type == PNOperationType.PNPublishOperation: - params_to_merge_in['seqn'] = self._publish_sequence_manager.get_next_sequence() - - options.merge_params_in(params_to_merge_in) - - future = Future() - - url = utils.build_url(self.config.scheme(), self.base_origin, - options.path, options.query_string) - - logger.debug("%s %s %s" % (options.method_string, url, options.data)) - - if options.method_string == "POST": - self.headers['Content-type'] = "application/json" - - start_timestamp = time.time() - - request = tornado.httpclient.HTTPRequest( - url=url, - method=options.method_string, - headers=self.headers, - body=options.data if options.data is not None else None, - connect_timeout=options.connect_timeout, - request_timeout=options.request_timeout) - - def response_callback(response): - if cancellation_event is not None and cancellation_event.is_set(): - return - - body = response.body - response_info = None - status_category = PNStatusCategory.PNUnknownCategory - if response is not None: - request_url = six.moves.urllib.parse.urlparse(response.effective_url) - query = six.moves.urllib.parse.parse_qs(request_url.query) - uuid = None - auth_key = None - - if 'uuid' in query and len(query['uuid']) > 0: - uuid = query['uuid'][0] - - if 'auth_key' in query and len(query['auth_key']) > 0: - auth_key = query['auth_key'][0] - - response_info = ResponseInfo( - status_code=response.code, - tls_enabled='https' == request_url.scheme, - origin=request_url.hostname, - uuid=uuid, - auth_key=auth_key, - client_request=response.request - ) - - if body is not None and len(body) > 0: - try: - data = json.loads(body) - except (ValueError, TypeError): - try: - data = json.loads(body.decode("utf-8")) - except ValueError: - tornado_result = PubNubTornadoException( - create_response(None), - create_status_response(status_category, response, response_info, PubNubException( - pn_error=PNERR_JSON_DECODING_FAILED, - errormsg='json decode error') - ) - ) - future.set_exception(tornado_result) - return - else: - data = "N/A" - - logger.debug(data) - - if response.error is not None: - if response.code >= 500: - err = PNERR_SERVER_ERROR - data = str(response.error) - else: - err = PNERR_CLIENT_ERROR - - e = PubNubException( - errormsg=data, - pn_error=err, - status_code=response.code, - ) - - if response.code == 403: - status_category = PNStatusCategory.PNAccessDeniedCategory - - if response.code == 400: - status_category = PNStatusCategory.PNBadRequestCategory - - if response.code == 599: - if 'HTTP 599: Timeout during request' == data: - status_category = PNStatusCategory.PNTimeoutCategory - e = PubNubException( - pn_error=PNERR_CLIENT_TIMEOUT, - errormsg=str(e) - ) - elif 'HTTP 599: Stream closed' == data or\ - 'Name or service not known' in data or\ - 'Temporary failure in name resolution' in data: - status_category = PNStatusCategory.PNNetworkIssuesCategory - e = PubNubException( - pn_error=PNERR_CONNECTION_ERROR, - errormsg=str(e) - ) - # TODO: add check for other status codes - - future.set_exception(PubNubTornadoException( - result=data, - status=create_status_response(status_category, data, response_info, e) - )) - else: - self._telemetry_manager.store_latency(time.time() - start_timestamp, options.operation_type) - - future.set_result(TornadoEnvelope( - result=create_response(data), - status=create_status_response( - PNStatusCategory.PNAcknowledgmentCategory, - data, - response_info, - None) - )) - - self.http.fetch( - request=request, - callback=response_callback - ) - - return future - - -class TornadoReconnectionManager(ReconnectionManager): - def __init__(self, pubnub): - self._cancelled_event = Event() - super(TornadoReconnectionManager, self).__init__(pubnub) - - @gen.coroutine - def _register_heartbeat_timer(self): - self._cancelled_event.clear() - - while not self._cancelled_event.is_set(): - if self._pubnub.config.reconnect_policy == PNReconnectionPolicy.EXPONENTIAL: - self._timer_interval = int(math.pow(2, self._connection_errors) - 1) - if self._timer_interval > self.MAXEXPONENTIALBACKOFF: - self._timer_interval = self.MINEXPONENTIALBACKOFF - self._connection_errors = 1 - logger.debug("timerInterval > MAXEXPONENTIALBACKOFF at: %s" % utils.datetime_now()) - elif self._timer_interval < 1: - self._timer_interval = self.MINEXPONENTIALBACKOFF - logger.debug("timerInterval = %d at: %s" % (self._timer_interval, utils.datetime_now())) - else: - self._timer_interval = self.INTERVAL - - # >>> Wait given interval or cancel - sleeper = tornado.gen.sleep(self._timer_interval) - canceller = self._cancelled_event.wait() - - wi = tornado.gen.WaitIterator(canceller, sleeper) - - while not wi.done(): - try: - future = wi.next() - yield future - except Exception as e: - # TODO: verify the error will not be eaten - logger.error(e) - raise - else: - if wi.current_future == sleeper: - break - elif wi.current_future == canceller: - return - else: - raise Exception("unknown future raised") - - logger.debug("reconnect loop at: %s" % utils.datetime_now()) - - # >>> Attempt to request /time/0 endpoint - try: - yield self._pubnub.time().result() - self._connection_errors = 1 - self._callback.on_reconnect() - logger.debug("reconnection manager stop due success time endpoint call: %s" % utils.datetime_now()) - break - except Exception: - if self._pubnub.config.reconnect_policy == PNReconnectionPolicy.EXPONENTIAL: - logger.debug("reconnect interval increment at: %s" % utils.datetime_now()) - self._connection_errors += 1 - - def start_polling(self): - if self._pubnub.config.reconnect_policy == PNReconnectionPolicy.NONE: - logger.warning("reconnection policy is disabled, please handle reconnection manually.") - return - - self._pubnub.ioloop.spawn_callback(self._register_heartbeat_timer) - - def stop_polling(self): - if self._cancelled_event is not None and not self._cancelled_event.is_set(): - self._cancelled_event.set() - - -class TornadoPublishSequenceManager(PublishSequenceManager): - def __init__(self, provided_max_sequence): - super(TornadoPublishSequenceManager, self).__init__(provided_max_sequence) - self._lock = Lock() - self._ioloop = ioloop - - def get_next_sequence(self): - if self.max_sequence == self.next_sequence: - self.next_sequence = 1 - else: - self.next_sequence += 1 - - return self.next_sequence - - -class TornadoSubscribeMessageWorker(SubscribeMessageWorker): - @tornado.gen.coroutine - def run(self): - self._take_message() - - @tornado.gen.coroutine - def _take_message(self): - i = 0 - while not self._event.is_set(): - try: - msg = yield self._queue.get(datetime.timedelta(seconds=1)) - if msg is not None: - self._process_incoming_payload(msg) - self._queue.task_done() - except tornado.gen.TimeoutError: - i += 1 - continue - - -class TornadoSubscriptionManager(SubscriptionManager): - def __init__(self, pubnub_instance): - - subscription_manager = self - - self._message_queue = Queue() - self._consumer_event = Event() - self._cancellation_event = Event() - self._subscription_lock = Semaphore(1) - # self._current_request_key_object = None - self._heartbeat_periodic_callback = None - self._reconnection_manager = TornadoReconnectionManager(pubnub_instance) - - super(TornadoSubscriptionManager, self).__init__(pubnub_instance) - self._start_worker() - - class TornadoReconnectionCallback(ReconnectionCallback): - def on_reconnect(self): - subscription_manager.reconnect() - - pn_status = PNStatus() - pn_status.category = PNStatusCategory.PNReconnectedCategory - pn_status.error = False - - subscription_manager._subscription_status_announced = True - subscription_manager._listener_manager.announce_status(pn_status) - - self._reconnection_listener = TornadoReconnectionCallback() - self._reconnection_manager.set_reconnection_listener(self._reconnection_listener) - - def _set_consumer_event(self): - self._consumer_event.set() - - def _message_queue_put(self, message): - self._message_queue.put(message) - - def _start_worker(self): - self._consumer = TornadoSubscribeMessageWorker(self._pubnub, - self._listener_manager, - self._message_queue, - self._consumer_event) - run = stack_context.wrap(self._consumer.run) - self._pubnub.ioloop.spawn_callback(run) - - def reconnect(self): - self._should_stop = False - self._pubnub.ioloop.spawn_callback(self._start_subscribe_loop) - # self._register_heartbeat_timer() - - def disconnect(self): - self._should_stop = True - self._stop_heartbeat_timer() - self._stop_subscribe_loop() - - @tornado.gen.coroutine - def _start_subscribe_loop(self): - self._stop_subscribe_loop() - - yield self._subscription_lock.acquire() - - self._cancellation_event.clear() - - combined_channels = self._subscription_state.prepare_channel_list(True) - combined_groups = self._subscription_state.prepare_channel_group_list(True) - - if len(combined_channels) == 0 and len(combined_groups) == 0: - return - - envelope_future = Subscribe(self._pubnub) \ - .channels(combined_channels).channel_groups(combined_groups) \ - .timetoken(self._timetoken).region(self._region) \ - .filter_expression(self._pubnub.config.filter_expression) \ - .cancellation_event(self._cancellation_event) \ - .future() - - canceller_future = self._cancellation_event.wait() - - wi = tornado.gen.WaitIterator(envelope_future, canceller_future) - - # iterates 2 times: one for result one for cancelled - while not wi.done(): - try: - result = yield wi.next() - except Exception as e: - # TODO: verify the error will not be eaten - logger.error(e) - raise - else: - if wi.current_future == envelope_future: - e = result - elif wi.current_future == canceller_future: - return - else: - raise Exception("Unexpected future resolved: %s" % str(wi.current_future)) - - if e.is_error(): - # 599 error doesn't works - tornado use this status code - # for a wide range of errors, for ex: - # HTTP Server Error (599): [Errno -2] Name or service not known - if e.status is not None and e.status.category == PNStatusCategory.PNTimeoutCategory: - self._pubnub.ioloop.spawn_callback(self._start_subscribe_loop) - return - - logger.error("Exception in subscribe loop: %s" % str(e)) - - if e.status is not None and e.status.category == PNStatusCategory.PNAccessDeniedCategory: - e.status.operation = PNOperationType.PNUnsubscribeOperation - - self._listener_manager.announce_status(e.status) - - self._reconnection_manager.start_polling() - self.disconnect() - return - else: - self._handle_endpoint_call(e.result, e.status) - - self._pubnub.ioloop.spawn_callback(self._start_subscribe_loop) - - finally: - self._cancellation_event.set() - yield tornado.gen.moment - self._subscription_lock.release() - self._cancellation_event.clear() - break - - def _stop_subscribe_loop(self): - if self._cancellation_event is not None and not self._cancellation_event.is_set(): - self._cancellation_event.set() - - def _stop_heartbeat_timer(self): - if self._heartbeat_periodic_callback is not None: - self._heartbeat_periodic_callback.stop() - - def _register_heartbeat_timer(self): - super(TornadoSubscriptionManager, self)._register_heartbeat_timer() - self._heartbeat_periodic_callback = PeriodicCallback( - stack_context.wrap(self._perform_heartbeat_loop), - self._pubnub.config.heartbeat_interval * TornadoSubscriptionManager.HEARTBEAT_INTERVAL_MULTIPLIER, - self._pubnub.ioloop) - self._heartbeat_periodic_callback.start() - - @tornado.gen.coroutine - def _perform_heartbeat_loop(self): - if self._heartbeat_call is not None: - # TODO: cancel call - pass - - cancellation_event = Event() - state_payload = self._subscription_state.state_payload() - presence_channels = self._subscription_state.prepare_channel_list(False) - presence_groups = self._subscription_state.prepare_channel_group_list(False) - - if len(presence_channels) == 0 and len(presence_groups) == 0: - return - - try: - envelope = yield self._pubnub.heartbeat() \ - .channels(presence_channels) \ - .channel_groups(presence_groups) \ - .state(state_payload) \ - .cancellation_event(cancellation_event) \ - .future() - - heartbeat_verbosity = self._pubnub.config.heartbeat_notification_options - if envelope.status.is_error: - if heartbeat_verbosity == PNHeartbeatNotificationOptions.ALL or \ - heartbeat_verbosity == PNHeartbeatNotificationOptions.ALL: - self._listener_manager.announce_status(envelope.status) - else: - if heartbeat_verbosity == PNHeartbeatNotificationOptions.ALL: - self._listener_manager.announce_status(envelope.status) - - except PubNubTornadoException: - pass - # TODO: check correctness - # if e.status is not None and e.status.category == PNStatusCategory.PNTimeoutCategory: - # self._start_subscribe_loop() - # else: - # self._listener_manager.announce_status(e.status) - except Exception as e: - print(e) - finally: - cancellation_event.set() - - @tornado.gen.coroutine - def _send_leave(self, unsubscribe_operation): - envelope = yield Leave(self._pubnub) \ - .channels(unsubscribe_operation.channels) \ - .channel_groups(unsubscribe_operation.channel_groups).future() - self._listener_manager.announce_status(envelope.status) - - -class TornadoEnvelope(object): - def __init__(self, result, status): - self.result = result - self.status = status - - @staticmethod - def is_error(): - return False - - -class PubNubTornadoException(Exception): - def __init__(self, result, status): - self.result = result - self.status = status - - def __str__(self): - return str(self.status.error_data.exception) - - @staticmethod - def is_error(): - return True - - def value(self): - return self.status.error_data.exception - - -class SubscribeListener(SubscribeCallback): - def __init__(self): - self.connected = False - self.connected_event = Event() - self.disconnected_event = Event() - self.presence_queue = Queue() - self.message_queue = Queue() - self.error_queue = Queue() - - def status(self, pubnub, status): - if utils.is_subscribed_event(status) and not self.connected_event.is_set(): - self.connected_event.set() - elif utils.is_unsubscribed_event(status) and not self.disconnected_event.is_set(): - self.disconnected_event.set() - elif status.is_error(): - self.error_queue.put_nowait(status.error_data.exception) - - def message(self, pubnub, message): - self.message_queue.put(message) - - def presence(self, pubnub, presence): - self.presence_queue.put(presence) - - @tornado.gen.coroutine - def _wait_for(self, coro): - error = self.error_queue.get() - wi = tornado.gen.WaitIterator(coro, error) - - while not wi.done(): - result = yield wi.next() - - if wi.current_future == coro: - raise gen.Return(result) - elif wi.current_future == error: - raise result - else: - raise Exception("Unexpected future resolved: %s" % str(wi.current_future)) - - @tornado.gen.coroutine - def wait_for_connect(self): - if not self.connected_event.is_set(): - yield self._wait_for(self.connected_event.wait()) - else: - raise Exception("instance is already connected") - - @tornado.gen.coroutine - def wait_for_disconnect(self): - if not self.disconnected_event.is_set(): - yield self._wait_for(self.disconnected_event.wait()) - else: - raise Exception("instance is already disconnected") - - @tornado.gen.coroutine - def wait_for_message_on(self, *channel_names): - channel_names = list(channel_names) - while True: - try: # NOQA - env = yield self._wait_for(self.message_queue.get()) - if env.channel in channel_names: - raise tornado.gen.Return(env) - else: - continue - finally: - self.message_queue.task_done() - - @tornado.gen.coroutine - def wait_for_presence_on(self, *channel_names): - channel_names = list(channel_names) - while True: - try: - try: - env = yield self._wait_for(self.presence_queue.get()) - except: # NOQA E722 pylint: disable=W0702 - break - if env.channel in channel_names: - raise tornado.gen.Return(env) - else: - continue - finally: - self.presence_queue.task_done() - - -class TornadoTelemetryManager(TelemetryManager): # pylint: disable=W0612 - def __init__(self, ioloop): - TelemetryManager.__init__(self) - self.ioloop = ioloop - self._timer = PeriodicCallback( - stack_context.wrap(self._start_clean_up_timer), - self.CLEAN_UP_INTERVAL * self.CLEAN_UP_INTERVAL_MULTIPLIER, - self.ioloop) - self._timer.start() - - @tornado.gen.coroutine - def _start_clean_up_timer(self): - self.clean_up_telemetry_data() - - def _stop_clean_up_timer(self): - self._timer.stop() diff --git a/pubnub/pubnub_twisted.py b/pubnub/pubnub_twisted.py deleted file mode 100644 index 4f4eb537..00000000 --- a/pubnub/pubnub_twisted.py +++ /dev/null @@ -1,412 +0,0 @@ -import json -import logging -import time - -from urlparse import urlparse, parse_qs -from StringIO import StringIO - -from twisted.internet import reactor as _reactor -from twisted.internet.task import LoopingCall -from twisted.internet.defer import Deferred, DeferredQueue -from twisted.internet.protocol import Protocol -from twisted.internet.error import ConnectingCancelledError -from twisted.web.client import Agent -from twisted.web.client import HTTPConnectionPool -from twisted.web.http_headers import Headers -from twisted.web.client import FileBodyProducer - -from . import utils -from .workers import SubscribeMessageWorker -from .pubnub_core import PubNubCore -from .managers import SubscriptionManager, PublishSequenceManager -from .enums import PNStatusCategory, PNHeartbeatNotificationOptions, PNOperationType -from .errors import PNERR_CLIENT_ERROR, PNERR_CONNECTION_ERROR, \ - PNERR_SERVER_ERROR, PNERR_JSON_DECODING_FAILED -from .exceptions import PubNubException -from .structures import ResponseInfo - -from .endpoints.pubsub.subscribe import Subscribe -from .endpoints.presence.leave import Leave -from .endpoints.presence.heartbeat import Heartbeat - -logger = logging.getLogger("pubnub") - - -class PubNubResponse(Protocol): - def __init__(self, finished, code): - self.finished = finished - self.code = code - - def dataReceived(self, body): - self.finished.callback(TwistedResponse(body, self.code)) - - -class TwistedSubscribeMessageWorker(SubscribeMessageWorker): - def run(self): - self._take_message() - - def _take_message(self): - self._queue.get().addCallback(self.send_message_to_processing) - - def send_message_to_processing(self, message): - if message is not None: - self._pubnub.reactor.callInThread(self._process_incoming_payload, message) - - -class TwistedSubscriptionManager(SubscriptionManager): - def __init__(self, pubnub_instance): - self._message_queue = DeferredQueue() - self.worker_loop = None - self._heartbeat_loop = None - self._heartbeat_call = None - self.clock = pubnub_instance.clock - super(TwistedSubscriptionManager, self).__init__(pubnub_instance) - - def _announce_status(self, status): - self._listener_manager.announce_status(status) - - def _start_worker(self): - consumer = TwistedSubscribeMessageWorker(self._pubnub, self._listener_manager, self._message_queue, None) - looping_call = LoopingCall(consumer.run) - - if self.clock is not None: - looping_call.clock = self.clock - - self.worker_loop = looping_call.start(0.1, False) - - def _set_consumer_event(self): - raise NotImplementedError - - def _message_queue_put(self, message): - self._message_queue.put(message) - - def _start_subscribe_loop(self): - self._stop_subscribe_loop() - - combined_channels = self._subscription_state.prepare_channel_list(True) - combined_groups = self._subscription_state.prepare_channel_group_list(True) - - if len(combined_channels) == 0 and len(combined_groups) == 0: - return - - def continue_subscribe_loop(envelope): - try: - self._handle_endpoint_call(envelope.raw_result, envelope.status) - except Exception as ex: - return ex - self._start_subscribe_loop() - - def manage_failure(failure): - if failure.type == PubNubTwistedException: - self._announce_status(failure.value.status) - if failure.value.status.category in (PNStatusCategory.PNDisconnectedCategory, - PNStatusCategory.PNUnexpectedDisconnectCategory, - PNStatusCategory.PNCancelledCategory, - PNStatusCategory.PNBadRequestCategory, - PNStatusCategory.PNMalformedFilterExpressionCategory): - time.sleep(30) # TODO: SET VALUE ACCORDING TO DOCS - self._start_subscribe_loop() - else: - return failure - - try: - self._subscribe_request_task = Subscribe(self._pubnub) \ - .channels(combined_channels) \ - .channel_groups(combined_groups) \ - .timetoken(self._timetoken) \ - .region(self._region) \ - .filter_expression(self._pubnub.config.filter_expression) \ - .deferred() \ - .addCallbacks(continue_subscribe_loop, manage_failure) - - except Exception as ex: - raise ex - - def _stop_subscribe_loop(self): - if self._subscribe_request_task is not None and not self._subscribe_request_task.called: - self._subscribe_request_task.cancel() - - def _stop_heartbeat_timer(self): - if self._heartbeat_call is not None: - self._heartbeat_call.cancel() - - if self._heartbeat_loop is not None: - self._heartbeat_loop.stop() - - def _register_heartbeat_timer(self): - super(TwistedSubscriptionManager, self)._register_heartbeat_timer() - self._heartbeat_loop = LoopingCall(self._perform_heartbeat_loop) - interval = self._pubnub.config.heartbeat_interval / 2 - 1 - self._heartbeat_loop.start(interval, True) - - def _perform_heartbeat_loop(self): - def heartbeat_callback(_, status): - heartbeat_verbosity = self._pubnub.config.heartbeat_notification_options - if heartbeat_verbosity == PNHeartbeatNotificationOptions.ALL or ( - status.is_error() is True and heartbeat_verbosity == PNHeartbeatNotificationOptions.FAILURES): - self._listener_manager.announce_status(status) - - if self._heartbeat_call is not None: - self._heartbeat_call.cancel() - - state_payload = self._subscription_state.state_payload() - channels = self._subscription_state.prepare_channel_list(False) - channel_groups = self._subscription_state.prepare_channel_group_list(False) - - self._heartbeat_call = Heartbeat(self._pubnub) \ - .channels(channels) \ - .channel_groups(channel_groups) \ - .state(state_payload) \ - .pn_async(heartbeat_callback) - - def _send_leave(self, unsubscribe_operation): - def announce_leave_status(response, status): - self._listener_manager.announce_status(status) - - Leave(self._pubnub) \ - .channels(unsubscribe_operation.channels) \ - .channel_groups(unsubscribe_operation.channel_groups) \ - .pn_async(announce_leave_status) - - def reconnect(self): - # TODO: REVIEW - self._start_subscribe_loop() - self._register_heartbeat_timer() - - -class PubNubTwisted(PubNubCore): - """PubNub Python API for Twisted framework""" - - def sdk_platform(self): - return "-Twisted" - - def __init__(self, config, pool=None, reactor=None, clock=None): - super(PubNubTwisted, self).__init__(config) - - self.clock = clock - self._publish_sequence_manager = PublishSequenceManager(PubNubCore.MAX_SEQUENCE) - - if self.config.enable_subscribe: - self._subscription_manager = TwistedSubscriptionManager(self) - - self.disconnected_times = 0 - - if reactor is None: - self.reactor = _reactor - else: - self.reactor = reactor - - if pool is None: - self.pnconn_pool = HTTPConnectionPool(self.reactor, persistent=True) - self.pnconn_pool.maxPersistentPerHost = 3 - self.pnconn_pool.cachedConnectionTimeout = self.config.subscribe_request_timeout - self.pnconn_pool.retryAutomatically = False - else: - self.pnconn_pool = pool - - self.headers = { - 'User-Agent': [self.sdk_name], - } - - def start(self, skip_reactor=False): - if self._subscription_manager is not None: - self._subscription_manager._start_worker() - if not skip_reactor: - self.reactor.run() - - def stop(self): - self.reactor.stop() - - def add_listener(self, listener): - if self._subscription_manager is not None: - self._subscription_manager.add_listener(listener) - else: - raise Exception("Subscription manager is not enabled for this instance") - - def request_async(self, endpoint_name, endpoint_call_options, callback, cancellation_event): - if endpoint_call_options.method_string == "POST": - self.headers['Content-type'] = "application/json" - - def async_request(endpoint_call_options, cancellation_event, callback): - def manage_failures(failure): - # Cancelled - if failure.type == ConnectingCancelledError: - return - elif failure.type == PubNubTwistedException: - callback(failure.value) - else: - return failure - - def options_func(): - return endpoint_call_options - - request = self.request_deferred(options_func, cancellation_event) - request.addCallbacks(callback, manage_failures) - - self.reactor.callLater(0, async_request, endpoint_call_options, cancellation_event, callback) - - return - - # REVIEW: cancellation_event doesn't used inside function - def request_deferred(self, options_func, cancellation_event): - options = options_func() - reactor = self.reactor - pnconn_pool = self.pnconn_pool - headers = self.headers - params_to_merge_in = {} - - if options.operation_type == PNOperationType.PNPublishOperation: - params_to_merge_in['seqn'] = self._publish_sequence_manager.get_next_sequence() - - options.merge_params_in(params_to_merge_in) - - create_response = options.create_response - create_status_response = options.create_status - - url = utils.build_url(self.config.scheme(), self.base_origin, - options.path, options.query_string) - - logger.debug("%s %s %s" % (options.method_string, url, options.data)) - - def handler(): - agent = Agent(reactor, pool=pnconn_pool) - - if options.data is not None: - body = FileBodyProducer(StringIO(options.data)) - else: - body = None - request = agent.request( - options.method_string, - url, - Headers(headers), - body) - - def received(response): - finished = Deferred() - response.deliverBody(PubNubResponse(finished, response.code)) - return finished - - def success(response, req_url, request): - parsed_url = urlparse(req_url) - query = parse_qs(parsed_url.query) - uuid = None - auth_key = None - - if 'uuid' in query and len(query['uuid']) > 0: - uuid = query['uuid'][0] - - if 'auth_key' in query and len(query['auth_key']) > 0: - auth_key = query['auth_key'][0] - - response_body = response.body - code = response.code - d = Deferred() - - response_info = ResponseInfo( - status_code=response.code, - tls_enabled='https' == parsed_url.scheme, - origin=parsed_url.netloc, - uuid=uuid, - auth_key=auth_key, - client_request=request - ) - - if code != 200: - if code == 403: - status_category = PNStatusCategory.PNAccessDeniedCategory - elif code == 400: - status_category = PNStatusCategory.PNBadRequestCategory - else: - status_category = self - - if code >= 500: - error = PNERR_SERVER_ERROR - else: - error = PNERR_CLIENT_ERROR - else: - error = None - status_category = PNStatusCategory.PNAcknowledgmentCategory - - try: - data = json.loads(response_body) - except ValueError: - try: - data = json.loads(response_body.decode("utf-8")) - except ValueError: - raise PubNubTwistedException( - result=create_response(None), - status=create_status_response( - status_category, - response_info, - PubNubException( - pn_error=PNERR_JSON_DECODING_FAILED, - errormsg='json decode error' - ) - ) - ) - - if error: - raise PubNubTwistedException( - result=data, - status=create_status_response(status_category, data, response_info, - PubNubException( - errormsg=data, - pn_error=error, - status_code=response.code - ))) - - envelope = TwistedEnvelope( - create_response(data), - create_status_response( - status_category, - response, - response_info, - error), - data - ) - d.callback(envelope) - return d - - def failed(failure): - raise PubNubTwistedException( - result=None, - status=create_status_response(PNStatusCategory.PNTLSConnectionFailedCategory, - None, - None, - PubNubException( - errormsg=str(failure), - pn_error=PNERR_CONNECTION_ERROR, - status_code=0 - ))) - request.addErrback(failed) - request.addCallback(received) - request.addCallback(success, url, request) - - return request - - return handler() - - def disconnected(self): - return self.disconnected_times > 0 - - -class TwistedEnvelope(object): - def __init__(self, result, status, raw_result=None): - self.result = result - self.status = status - self.raw_result = raw_result - - -class TwistedResponse(object): - def __init__(self, body, code): - self.body = body - self.code = code - - -class PubNubTwistedException(Exception): - def __init__(self, result, status): - self.result = result - self.status = status - - def __str__(self): - return str(self.status.error_data.exception) diff --git a/pubnub/request_handlers/requests_handler.py b/pubnub/request_handlers/requests_handler.py index ff83e9e6..bbe00c5a 100644 --- a/pubnub/request_handlers/requests_handler.py +++ b/pubnub/request_handlers/requests_handler.py @@ -1,8 +1,8 @@ import logging import threading import requests -import six import json # noqa # pylint: disable=W0611 +import urllib from requests import Session from requests.adapters import HTTPAdapter @@ -153,8 +153,8 @@ def _build_envelope(self, p_options, e_options): exception=e)) if res is not None: - url = six.moves.urllib.parse.urlparse(res.url) - query = six.moves.urllib.parse.parse_qs(url.query) + url = urllib.parse.urlparse(res.url) + query = urllib.parse.parse_qs(url.query) uuid = None auth_key = None diff --git a/pubnub/request_handlers/urllib2_handler.py b/pubnub/request_handlers/urllib2_handler.py deleted file mode 100644 index 34aefb04..00000000 --- a/pubnub/request_handlers/urllib2_handler.py +++ /dev/null @@ -1,259 +0,0 @@ -import json -import logging -import socket -import threading - -import six -from six.moves import urllib - -from pubnub import utils -from pubnub.enums import PNStatusCategory -from pubnub.errors import PNERR_CLIENT_ERROR, PNERR_UNKNOWN_ERROR, PNERR_CLIENT_TIMEOUT, \ - PNERR_HTTP_ERROR, PNERR_CONNECTION_ERROR -from pubnub.errors import PNERR_SERVER_ERROR -from pubnub.exceptions import PubNubException -from pubnub.request_handlers.base import BaseRequestHandler -from pubnub.structures import RequestOptions, PlatformOptions, ResponseInfo, Envelope - -logger = logging.getLogger("pubnub") - - -class Urllib2RequestHandler(BaseRequestHandler): - """ - PubNub Python SDK Native requests handler based on `urllib2/urllib` native HTTP library. - - Do not use this helper since it's doesnt finished yet. Treat it as an example how to write a custom - handler for PubNub SDK - """ - ENDPOINT_THREAD_COUNTER = 0 - - def __init__(self, pubnub): - self.pubnub = pubnub - - def sync_request(self, platform_options, endpoint_call_options): - return self._build_envelope(platform_options, endpoint_call_options) - - def async_request(self, endpoint_name, platform_options, endpoint_call_options, callback, cancellation_event): - call = Call() - - def callback_to_invoke_in_another_thread(): - try: - envelope = self._build_envelope(platform_options, endpoint_call_options) - if cancellation_event is not None and cancellation_event.isSet(): - # Since there are no way to affect on ongoing request it's response will - # be just ignored on cancel call - return - - callback(envelope) - except PubNubException as e: - logger.error("Async request PubNubException. %s" % str(e)) - callback(Envelope( - result=None, - status=endpoint_call_options.create_status( - category=PNStatusCategory.PNBadRequestCategory, - response=None, - response_info=None, - exception=e))) - except Exception as e: - logger.error("Async request Exception. %s" % str(e)) - callback(Envelope( - result=None, - status=endpoint_call_options.create_status( - category=PNStatusCategory.PNInternalExceptionCategory, - response=None, - response_info=None, - exception=e))) - finally: - call.executed_cb() - - client = AsyncHTTPClient(callback_to_invoke_in_another_thread) - - thread = threading.Thread( - target=client.run, - name="EndpointThread-%s-%d" % (endpoint_name, ++Urllib2RequestHandler.ENDPOINT_THREAD_COUNTER) - ) - thread.setDaemon(self.pubnub.config.daemon) - thread.start() - - call.thread = thread - call.cancellation_event = cancellation_event - - return call - - def _build_envelope(self, p_options, e_options): - """ A wrapper for _invoke_url to separate request logic """ - - status_category = PNStatusCategory.PNUnknownCategory - response_info = None - - try: - res = self._invoke_request(p_options, e_options, self.pubnub.base_origin) - except PubNubException as e: - if e._pn_error is PNERR_CONNECTION_ERROR: - status_category = PNStatusCategory.PNUnexpectedDisconnectCategory - elif e._pn_error is PNERR_CLIENT_TIMEOUT: - status_category = PNStatusCategory.PNTimeoutCategory - - return Envelope( - result=None, - status=e_options.create_status( - category=status_category, - response=None, - response_info=response_info, - exception=e)) - - if res is not None: - url = six.moves.urllib.parse.urlparse(res.url) - query = six.moves.urllib.parse.parse_qs(url.query) - uuid = None - auth_key = None - - if 'uuid' in query and len(query['uuid']) > 0: - uuid = query['uuid'][0] - - if 'auth_key' in query and len(query['auth_key']) > 0: - auth_key = query['auth_key'][0] - - response_info = ResponseInfo( - status_code=res.code, - tls_enabled='https' == url.scheme, - origin=url.hostname, - uuid=uuid, - auth_key=auth_key, - client_request=None - ) - - decoded_text = res.read().decode('utf-8') - decoded_json = json.loads(decoded_text) - logger.debug("GOT %s" % decoded_text) - - if res.code != 200: - if res.code == 403: - status_category = PNStatusCategory.PNAccessDeniedCategory - - if res.code == 400: - status_category = PNStatusCategory.PNBadRequestCategory - - if decoded_json is None: - text = "N/A" - else: - text = decoded_json - - if res.status_code >= 500: - err = PNERR_SERVER_ERROR - else: - err = PNERR_CLIENT_ERROR - - return Envelope( - result=e_options.create_response(decoded_json), - status=e_options.create_status( - category=status_category, - response=decoded_json, - response_info=response_info, - exception=PubNubException( - pn_error=err, - errormsg=text, - status_code=res.status_code - ))) - else: - - return Envelope( - result=e_options.create_response(decoded_json), - status=e_options.create_status( - category=PNStatusCategory.PNAcknowledgmentCategory, - response=decoded_json, - response_info=response_info, - exception=None)) - - @staticmethod - def _invoke_request(p_options, e_options, base_origin): - assert isinstance(p_options, PlatformOptions) - assert isinstance(e_options, RequestOptions) - - url = utils.build_url(p_options.pn_config.scheme(), base_origin, - e_options.path, e_options.query_string) - - args = { - "method": e_options.method_string, - 'headers': p_options.headers, - "url": url, - 'params': e_options.query_string, - 'timeout': (e_options.connect_timeout, e_options.request_timeout) - } - - if e_options.is_post() or e_options.is_patch(): - args['data'] = e_options.data - logger.debug("%s %s %s" % (e_options.method_string, url, e_options.data)) - else: - logger.debug("%s %s" % (e_options.method_string, url)) - - try: - req = urllib.request.Request(url, e_options.data, p_options.headers) - res = urllib.request.urlopen(req) - except urllib.error.URLError as e: - # For Python 2.6 - if isinstance(e.reason, socket.timeout): - raise PubNubException( - pn_error=PNERR_CLIENT_TIMEOUT, - errormsg=str(e) - ) - else: - # TODO: wrap - raise - - except urllib.error.HTTPError as e: - raise PubNubException( - pn_error=PNERR_HTTP_ERROR, - errormsg=str(e) - ) - except socket.timeout as e: - raise PubNubException( - pn_error=PNERR_CLIENT_TIMEOUT, - errormsg=str(e) - ) - except Exception as e: - raise PubNubException( - pn_error=PNERR_UNKNOWN_ERROR, - errormsg=str(e) - ) - - return res - - -class AsyncHTTPClient: - """A wrapper for threaded calls""" - - def __init__(self, callback_to_invoke): - self._callback_to_invoke = callback_to_invoke - - def run(self): - self._callback_to_invoke() - - -class Call(object): - """ - A platform dependent representation of async PubNub method call - """ - - def __init__(self): - self.thread = None - self.cancellation_event = None - self.is_executed = False - self.is_canceled = False - - def cancel(self): - """ - Set Event flag to stop thread on timeout. This will not stop thread immediately, it will stopped - only after ongoing request will be finished - :return: nothing - """ - if self.cancellation_event is not None: - self.cancellation_event.set() - self.is_canceled = True - - def join(self): - if isinstance(self.thread, threading.Thread): - self.thread.join() - - def executed_cb(self): - self.is_executed = True diff --git a/pubnub/structures.py b/pubnub/structures.py index cc01e52f..036a8d69 100644 --- a/pubnub/structures.py +++ b/pubnub/structures.py @@ -1,5 +1,3 @@ -import six - from .enums import HttpMethod @@ -14,9 +12,9 @@ def __init__( ): assert len(path) > 0 assert callable(params_callback) - assert isinstance(method, six.integer_types) - assert isinstance(request_timeout, six.integer_types) - assert isinstance(connect_timeout, six.integer_types) + assert isinstance(method, int) + assert isinstance(request_timeout, int) + assert isinstance(connect_timeout, int) if not (method is HttpMethod.GET or method is HttpMethod.POST or method is HttpMethod.DELETE or method is HttpMethod.PATCH): # noqa raise AssertionError() diff --git a/pubnub/utils.py b/pubnub/utils.py index 03e2b6aa..0a21d78b 100644 --- a/pubnub/utils.py +++ b/pubnub/utils.py @@ -3,17 +3,8 @@ import json import uuid as u import threading - -try: - from hashlib import sha256 - - digestmod = sha256 -except ImportError: - import Crypto.Hash.SHA256 as digestmod - - sha256 = digestmod.new - -import six +import urllib +from hashlib import sha256 from .enums import PNStatusCategory, PNOperationType, PNPushType, HttpMethod from .models.consumer.common import PNStatus @@ -33,7 +24,7 @@ def get_data_for_user(data): def write_value_as_string(data): try: - if isinstance(data, six.string_types): + if isinstance(data, str): return "\"%s\"" % data else: return json.dumps(data) @@ -44,7 +35,7 @@ def write_value_as_string(data): def url_encode(data): - return six.moves.urllib.parse.quote(data, safe="~").replace("+", "%2B") + return urllib.parse.quote(data, safe="~").replace("+", "%2B") def url_write(data): @@ -79,14 +70,14 @@ def join_channels(items_list): def extend_list(existing_items, new_items): - if isinstance(new_items, six.string_types): + if isinstance(new_items, str): existing_items.extend(split_items(new_items)) else: existing_items.extend(new_items) def build_url(scheme, origin, path, params={}): - return six.moves.urllib.parse.urlunsplit((scheme, origin, path, params, '')) + return urllib.parse.urlunsplit((scheme, origin, path, params, '')) def synchronized(func): diff --git a/requirements-dev.txt b/requirements-dev.txt index 4fab7d8f..ac24fcc7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,5 +1,10 @@ -codacy-coverage -pyyaml==5.2 +pyyaml +pytest-cov pycryptodomex -flake8==3.6.0 --e git://github.com/pubnub/vcrpy@twisted#egg=vcrpy +flake8 +pytest +pytest-asyncio +aiohttp +requests +cbor2 +-e git://github.com/pubnub/vcrpy.git@aiotthp_redirect_enabled#egg=vcrpy \ No newline at end of file diff --git a/requirements-pypy-dev.txt b/requirements-pypy-dev.txt deleted file mode 100644 index 1105ebb7..00000000 --- a/requirements-pypy-dev.txt +++ /dev/null @@ -1,4 +0,0 @@ -tornado==4.5.3 -pytest==4.3.0 -pytest-cov<2.6.0 -cbor2 diff --git a/requirements27-dev.txt b/requirements27-dev.txt deleted file mode 100644 index dbb2063a..00000000 --- a/requirements27-dev.txt +++ /dev/null @@ -1,6 +0,0 @@ -pytest==4.3.0 -tornado==4.5.3 -twisted==19.10.0 -pyopenssl -pytest-cov<2.6.0 -cbor2 diff --git a/requirements34-dev.txt b/requirements34-dev.txt deleted file mode 100644 index 3751f6c4..00000000 --- a/requirements34-dev.txt +++ /dev/null @@ -1,7 +0,0 @@ -pytest==3.10.1 -pytest-asyncio==0.5.0 -pytest-cov<2.6.0 -tornado==4.5.3 -aiohttp==2.3.10 -typing==3.6.4 -cbor2 diff --git a/requirements35-dev.txt b/requirements35-dev.txt deleted file mode 100644 index 59f9da2d..00000000 --- a/requirements35-dev.txt +++ /dev/null @@ -1,6 +0,0 @@ -pytest==5.4.0 -pytest-asyncio -tornado==4.5.3 -aiohttp==2.3.10 -pytest-cov<2.6.0 -cbor2 diff --git a/requirements36-dev.txt b/requirements36-dev.txt deleted file mode 100644 index 005d08c2..00000000 --- a/requirements36-dev.txt +++ /dev/null @@ -1,6 +0,0 @@ -pytest==5.4.0 -pytest-asyncio -tornado==4.5.3 -aiohttp==2.3.10 -pytest-cov -cbor2 diff --git a/requirements37-dev.txt b/requirements37-dev.txt deleted file mode 100644 index 974b2276..00000000 --- a/requirements37-dev.txt +++ /dev/null @@ -1,6 +0,0 @@ -pytest==4.3.0 -pytest-asyncio -tornado==4.5.3 -aiohttp==2.3.10 -pytest-cov -cbor2 diff --git a/scripts/install.sh b/scripts/install.sh index 1bdf69f5..335a4f02 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1,12 +1,3 @@ #!/usr/bin/env bash pip install -r requirements-dev.txt -if [[ $TRAVIS_PYTHON_VERSION == 2.7* ]]; then pip install -r requirements27-dev.txt; fi -if [[ $TRAVIS_PYTHON_VERSION == 3.4* ]]; then pip install -r requirements34-dev.txt; fi -if [[ $TRAVIS_PYTHON_VERSION == 3.5* ]]; then pip install -r requirements35-dev.txt; fi -if [[ $TRAVIS_PYTHON_VERSION == 3.6* ]]; then - pip install -r requirements36-dev.txt; - pip install keyring==21.4.0 -fi -if [[ $TRAVIS_PYTHON_VERSION == "nightly" ]]; then pip install -r requirements36-dev.txt; fi -if [[ $TRAVIS_PYTHON_VERSION == "pypy" ]]; then pip install -r requirements-pypy-dev.txt; fi \ No newline at end of file diff --git a/scripts/run-tests.py b/scripts/run-tests.py index aa21ff3c..5e059300 100755 --- a/scripts/run-tests.py +++ b/scripts/run-tests.py @@ -4,7 +4,6 @@ # binary package not from the CWD. import os -import sys from subprocess import check_call _dname = os.path.dirname @@ -12,35 +11,13 @@ REPO_ROOT = _dname(_dname(os.path.abspath(__file__))) os.chdir(os.path.join(REPO_ROOT)) -try: - version = str(sys.version_info.major) + "." + str(sys.version_info.minor) -except: - version = str(sys.version_info[0]) + "." + str(sys.version_info[1]) - -tcmn = 'py.test tests --cov-report=xml --cov=./pubnub --ignore=tests/manual/ ' +tcmn = 'py.test tests --cov=pubnub --ignore=tests/manual/' fcmn = 'flake8 --exclude=scripts/,src/,.cache,.git,.idea,.tox,._trial_temp/' -print("Version is", version) - - def run(command): return check_call(command, shell=True) -if version.startswith('2.7') or version.startswith('anaconda2'): - run("%s,*asyncio*,*python_v35*,examples/" % fcmn) - run('%s --ignore=tests/integrational/asyncio/ --ignore=tests/integrational/twisted/ --ignore=tests/integrational/python_v35/' % tcmn) -elif version.startswith('3.4'): - run("%s,*python_v35*,examples" % fcmn) - run('%s--ignore=tests/integrational/python_v35/ --ignore=tests/integrational/twisted/' % tcmn) -elif version.startswith('3.5'): - run(fcmn) - run('%s--ignore=tests/integrational/twisted/' % tcmn) -elif version.startswith('3.6') or version == 'nightly': - run(fcmn) - run('%s--ignore=tests/integrational/twisted/' % tcmn) -elif version.startswith('pypy'): - run("%s,*asyncio*,*python_v35*,examples" % fcmn) - run('%s--ignore=tests/integrational/asyncio/ --ignore=tests/integrational/twisted/ --ignore=tests/integrational/python_v35/' % tcmn) -else: - raise Exception("Version %s is not supported by this script runner" % version) + +run(tcmn) +run(fcmn) diff --git a/setup.py b/setup.py index e6d16542..d7f232b9 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ setup( name='pubnub', - version='4.8.1', + version='5.0.0', description='PubNub Real-time push service in the cloud', author='PubNub', author_email='support@pubnub.com', @@ -13,13 +13,11 @@ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', - 'Programming Language :: Python :: 2.7', - '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 :: 3.9', 'Programming Language :: Python :: Implementation :: CPython', - 'Programming Language :: Python :: Implementation :: PyPy', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP', @@ -28,8 +26,8 @@ install_requires=[ 'pycryptodomex>=3.3', 'requests>=2.4', - 'six>=1.10', - 'cbor2' + 'cbor2', + 'aiohttp' ], zip_safe=False, ) diff --git a/tests/functional/push/test_remove_channels_from_push.py b/tests/functional/push/test_remove_channels_from_push.py index 1e03bbec..516f92dc 100644 --- a/tests/functional/push/test_remove_channels_from_push.py +++ b/tests/functional/push/test_remove_channels_from_push.py @@ -1,14 +1,8 @@ import unittest - -try: - from mock import MagicMock -except ImportError: - from unittest.mock import MagicMock +from unittest.mock import MagicMock from pubnub.pubnub import PubNub - import pubnub.enums - from pubnub.endpoints.push.remove_channels_from_push import RemoveChannelsFromPush from tests.helper import pnconf, sdk_name from pubnub.managers import TelemetryManager diff --git a/tests/functional/test_heartbeat.py b/tests/functional/test_heartbeat.py index 90b813d2..ebe82a5e 100644 --- a/tests/functional/test_heartbeat.py +++ b/tests/functional/test_heartbeat.py @@ -1,15 +1,10 @@ -import unittest - import json +import unittest +import urllib +from unittest.mock import MagicMock from pubnub.endpoints.presence.heartbeat import Heartbeat from pubnub.managers import TelemetryManager - -try: - from mock import MagicMock -except ImportError: - from unittest.mock import MagicMock - from pubnub.pubnub import PubNub from tests.helper import pnconf, sdk_name, pnconf_copy @@ -85,8 +80,6 @@ def test_hb_multiple_groups_using_list(self): self.assertEqual(self.hb._groups, ['gr1', 'gr2', 'gr3']) def test_hb_with_state(self): - import six - state = {"name": "Alex", "count": 7} self.hb.channels('ch1,ch2').state(state) @@ -94,7 +87,7 @@ def test_hb_with_state(self): % (pnconf.subscribe_key, "ch1,ch2")) params = self.hb.build_params_callback()({}) - params['state'] = json.loads(six.moves.urllib.parse.unquote(params['state'])) + params['state'] = json.loads(urllib.parse.unquote(params['state'])) self.assertEqual(params, { 'pnsdk': sdk_name, diff --git a/tests/helper.py b/tests/helper.py index 88e676a3..a6781fb1 100644 --- a/tests/helper.py +++ b/tests/helper.py @@ -1,20 +1,17 @@ import threading import string import random -import six +import urllib from copy import copy from pubnub import utils from pubnub.crypto import PubNubCryptodome from pubnub.pnconfiguration import PNConfiguration -try: - from mock import patch -except ImportError: - from unittest.mock import patch # noqa: F401 crypto = PubNubCryptodome(PNConfiguration()) +DEFAULT_TEST_CIPHER_KEY = "testKey" pub_key = "pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52" sub_key = "sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe" @@ -123,18 +120,18 @@ def url_encode(data): def url_decode(data): - return six.moves.urllib.parse.unquote(data) + return urllib.parse.unquote(data) def gen_channel(prefix): return "%s-%s" % (prefix, gen_string(8)) -def gen_string(l): - return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(l)) +def gen_string(length): + return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(length)) -def gen_decrypt_func(cipher_key): +def gen_decrypt_func(cipher_key=DEFAULT_TEST_CIPHER_KEY): def decrypter(entry): mr = crypto.decrypt(cipher_key, entry) return mr diff --git a/tests/integrational/asyncio/test_channel_groups.py b/tests/integrational/asyncio/test_channel_groups.py index 2787d680..bef384d4 100644 --- a/tests/integrational/asyncio/test_channel_groups.py +++ b/tests/integrational/asyncio/test_channel_groups.py @@ -13,41 +13,41 @@ @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/groups/add_remove_single_channel.yaml', filter_query_parameters=['uuid', 'pnsdk', 'l_cg', 'l_pub']) @pytest.mark.asyncio -def test_add_remove_single_channel(event_loop, sleeper=asyncio.sleep): +async def test_add_remove_single_channel(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) pubnub.config.uuid = 'test-channel-group-asyncio-uuid1' ch = "test-channel-groups-asyncio-ch" gr = "test-channel-groups-asyncio-cg" - yield from pubnub.publish().channel(ch).message("hey").future() + await pubnub.publish().channel(ch).message("hey").future() # add - env = yield from pubnub.add_channel_to_channel_group() \ + env = await pubnub.add_channel_to_channel_group() \ .channels(ch).channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsAddChannelResult) - yield from sleeper(1) + await sleeper(1) # list - env = yield from pubnub.list_channels_in_channel_group().channel_group(gr).future() + env = await pubnub.list_channels_in_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsListResult) assert len(env.result.channels) == 1 assert env.result.channels[0] == ch # remove - env = yield from pubnub.remove_channel_from_channel_group() \ + env = await pubnub.remove_channel_from_channel_group() \ .channels(ch).channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsRemoveChannelResult) - yield from sleeper(1) + await sleeper(1) # change uuid to let vcr to distinguish list requests pubnub.config.uuid = 'test-channel-group-asyncio-uuid2' # list - env = yield from pubnub.list_channels_in_channel_group().channel_group(gr).future() + env = await pubnub.list_channels_in_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsListResult) assert len(env.result.channels) == 0 @@ -58,7 +58,7 @@ def test_add_remove_single_channel(event_loop, sleeper=asyncio.sleep): @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/groups/add_remove_multiple_channels.yaml', filter_query_parameters=['uuid', 'pnsdk', 'l_cg', 'l_pub']) @pytest.mark.asyncio -def test_add_remove_multiple_channels(event_loop, sleeper=asyncio.sleep): +async def test_add_remove_multiple_channels(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop) ch1 = "channel-groups-tornado-ch1" @@ -66,30 +66,30 @@ def test_add_remove_multiple_channels(event_loop, sleeper=asyncio.sleep): gr = "channel-groups-tornado-cg" # add - env = yield from pubnub.add_channel_to_channel_group() \ + env = await pubnub.add_channel_to_channel_group() \ .channels([ch1, ch2]).channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsAddChannelResult) - yield from sleeper(1) + await sleeper(1) # list - env = yield from pubnub.list_channels_in_channel_group().channel_group(gr).future() + env = await pubnub.list_channels_in_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsListResult) assert len(env.result.channels) == 2 assert ch1 in env.result.channels assert ch2 in env.result.channels # remove - env = yield from pubnub.remove_channel_from_channel_group() \ + env = await pubnub.remove_channel_from_channel_group() \ .channels([ch1, ch2]).channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsRemoveChannelResult) - yield from sleeper(1) + await sleeper(1) # list - env = yield from pubnub.list_channels_in_channel_group().channel_group(gr).future() + env = await pubnub.list_channels_in_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsListResult) assert len(env.result.channels) == 0 @@ -100,35 +100,35 @@ def test_add_remove_multiple_channels(event_loop, sleeper=asyncio.sleep): @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/groups/add_channel_remove_group.yaml', filter_query_parameters=['uuid', 'pnsdk', 'l_cg', 'l_pub']) @pytest.mark.asyncio -def test_add_channel_remove_group(event_loop, sleeper=asyncio.sleep): +async def test_add_channel_remove_group(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop) ch = "channel-groups-tornado-ch" gr = "channel-groups-tornado-cg" # add - env = yield from pubnub.add_channel_to_channel_group() \ + env = await pubnub.add_channel_to_channel_group() \ .channels(ch).channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsAddChannelResult) - yield from sleeper(1) + await sleeper(1) # list - env = yield from pubnub.list_channels_in_channel_group().channel_group(gr).future() + env = await pubnub.list_channels_in_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsListResult) assert len(env.result.channels) == 1 assert env.result.channels[0] == ch # remove group - env = yield from pubnub.remove_channel_group().channel_group(gr).future() + env = await pubnub.remove_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsRemoveGroupResult) - yield from sleeper(1) + await sleeper(1) # list - env = yield from pubnub.list_channels_in_channel_group().channel_group(gr).future() + env = await pubnub.list_channels_in_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsListResult) assert len(env.result.channels) == 0 @@ -136,7 +136,7 @@ def test_add_channel_remove_group(event_loop, sleeper=asyncio.sleep): @pytest.mark.asyncio -def test_super_call(event_loop): +async def test_super_call(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) ch = "channel-groups-torna|do-ch" @@ -144,25 +144,25 @@ def test_super_call(event_loop): pubnub.config.auth = "h.e|l%l,0" # add - env = yield from pubnub.add_channel_to_channel_group() \ + env = await pubnub.add_channel_to_channel_group() \ .channels(ch).channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsAddChannelResult) # list - env = yield from pubnub.list_channels_in_channel_group().channel_group(gr).future() + env = await pubnub.list_channels_in_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsListResult) # remove channel - env = yield from pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() + env = await pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() assert isinstance(env.result, PNChannelGroupsRemoveChannelResult) # remove group - env = yield from pubnub.remove_channel_group().channel_group(gr).future() + env = await pubnub.remove_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsRemoveGroupResult) # list - env = yield from pubnub.list_channels_in_channel_group().channel_group(gr).future() + env = await pubnub.list_channels_in_channel_group().channel_group(gr).future() assert isinstance(env.result, PNChannelGroupsListResult) pubnub.stop() diff --git a/tests/integrational/asyncio/test_file_upload.py b/tests/integrational/asyncio/test_file_upload.py index b4f0e0ae..1890b6f2 100644 --- a/tests/integrational/asyncio/test_file_upload.py +++ b/tests/integrational/asyncio/test_file_upload.py @@ -13,9 +13,9 @@ CHANNEL = "files_asyncio_ch" -def send_file(pubnub, file_for_upload, cipher_key=None): +async def send_file(pubnub, file_for_upload, cipher_key=None): with open(file_for_upload.strpath, "rb") as fd: - envelope = yield from pubnub.send_file().\ + envelope = await pubnub.send_file().\ channel(CHANNEL).\ file_name(file_for_upload.basename).\ message({"test_message": "test"}).\ @@ -36,13 +36,13 @@ def send_file(pubnub, file_for_upload, cipher_key=None): filter_query_parameters=['uuid', 'l_file', 'pnsdk'] ) @pytest.mark.asyncio -def test_delete_file(event_loop, file_for_upload): +async def test_delete_file(event_loop, file_for_upload): pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "files_asyncio_uuid" - envelope = yield from send_file(pubnub, file_for_upload) + envelope = await send_file(pubnub, file_for_upload) - delete_envelope = yield from pubnub.delete_file().\ + delete_envelope = await pubnub.delete_file().\ channel(CHANNEL).\ file_id(envelope.result.file_id).\ file_name(envelope.result.name).future() @@ -54,11 +54,13 @@ def test_delete_file(event_loop, file_for_upload): @pn_vcr.use_cassette( "tests/integrational/fixtures/asyncio/file_upload/list_files.yaml", filter_query_parameters=['uuid', 'l_file', 'pnsdk'] + + ) @pytest.mark.asyncio -def test_list_files(event_loop): +async def test_list_files(event_loop): pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop) - envelope = yield from pubnub.list_files().channel(CHANNEL).future() + envelope = await pubnub.list_files().channel(CHANNEL).future() assert isinstance(envelope.result, PNGetFilesResult) assert envelope.result.count == 23 @@ -70,10 +72,10 @@ def test_list_files(event_loop): filter_query_parameters=['uuid', 'l_file', 'pnsdk'] ) @pytest.mark.asyncio -def test_send_and_download_file(event_loop, file_for_upload): +async def test_send_and_download_file(event_loop, file_for_upload): pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop) - envelope = yield from send_file(pubnub, file_for_upload) - download_envelope = yield from pubnub.download_file().\ + envelope = await send_file(pubnub, file_for_upload) + download_envelope = await pubnub.download_file().\ channel(CHANNEL).\ file_id(envelope.result.file_id).\ file_name(envelope.result.name).future() @@ -82,16 +84,15 @@ def test_send_and_download_file(event_loop, file_for_upload): pubnub.stop() -@pytest.mark.skip("Aiohttp and VCR needs to be upgraded(serialization problems). To be fixed within v5 release.") @pn_vcr.use_cassette( "tests/integrational/fixtures/asyncio/file_upload/send_and_download_encrypted_file.yaml", filter_query_parameters=['uuid', 'l_file', 'pnsdk'] ) @pytest.mark.asyncio -def test_send_and_download_file_encrypted(event_loop, file_for_upload, file_upload_test_data): +async def test_send_and_download_file_encrypted(event_loop, file_for_upload, file_upload_test_data): pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop) - envelope = yield from send_file(pubnub, file_for_upload, cipher_key="test") - download_envelope = yield from pubnub.download_file().\ + envelope = await send_file(pubnub, file_for_upload, cipher_key="test") + download_envelope = await pubnub.download_file().\ channel(CHANNEL).\ file_id(envelope.result.file_id).\ file_name(envelope.result.name).\ @@ -108,10 +109,10 @@ def test_send_and_download_file_encrypted(event_loop, file_for_upload, file_uplo filter_query_parameters=['uuid', 'l_file', 'pnsdk'] ) @pytest.mark.asyncio -def test_get_file_url(event_loop, file_for_upload): +async def test_get_file_url(event_loop, file_for_upload): pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop) - envelope = yield from send_file(pubnub, file_for_upload) - file_url_envelope = yield from pubnub.get_file_url().\ + envelope = await send_file(pubnub, file_for_upload) + file_url_envelope = await pubnub.get_file_url().\ channel(CHANNEL).\ file_id(envelope.result.file_id).\ file_name(envelope.result.name).future() @@ -125,9 +126,9 @@ def test_get_file_url(event_loop, file_for_upload): filter_query_parameters=['uuid', 'l_file', 'pnsdk'] ) @pytest.mark.asyncio -def test_fetch_file_upload_s3_data_with_result_invocation(event_loop, file_upload_test_data): +async def test_fetch_file_upload_s3_data_with_result_invocation(event_loop, file_upload_test_data): pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop) - result = yield from pubnub._fetch_file_upload_s3_data().\ + result = await pubnub._fetch_file_upload_s3_data().\ channel(CHANNEL).\ file_name(file_upload_test_data["UPLOADED_FILENAME"]).result() @@ -140,9 +141,9 @@ def test_fetch_file_upload_s3_data_with_result_invocation(event_loop, file_uploa filter_query_parameters=['uuid', 'seqn', 'pnsdk'] ) @pytest.mark.asyncio -def test_publish_file_message_with_encryption(event_loop, file_upload_test_data): +async def test_publish_file_message_with_encryption(event_loop, file_upload_test_data): pubnub = PubNubAsyncio(pnconf_file_copy(), custom_event_loop=event_loop) - envelope = yield from PublishFileMessage(pubnub).\ + envelope = await PublishFileMessage(pubnub).\ channel(CHANNEL).\ meta({}).\ message({"test": "test"}).\ diff --git a/tests/integrational/asyncio/test_fire.py b/tests/integrational/asyncio/test_fire.py index 62b4a894..4ab15762 100644 --- a/tests/integrational/asyncio/test_fire.py +++ b/tests/integrational/asyncio/test_fire.py @@ -7,15 +7,17 @@ from pubnub.models.consumer.common import PNStatus -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/publish/fire_get.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/publish/fire_get.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_single_channel(event_loop): +async def test_single_channel(event_loop): config = pnconf_copy() config.enable_subscribe = False pn = PubNubAsyncio(config, custom_event_loop=event_loop) chan = 'unique_sync' - envelope = yield from pn.fire().channel(chan).message('bla').future() + envelope = await pn.fire().channel(chan).message('bla').future() assert(isinstance(envelope, AsyncioEnvelope)) assert not envelope.status.is_error() diff --git a/tests/integrational/asyncio/test_heartbeat.py b/tests/integrational/asyncio/test_heartbeat.py index 71bb000b..1739e51b 100644 --- a/tests/integrational/asyncio/test_heartbeat.py +++ b/tests/integrational/asyncio/test_heartbeat.py @@ -19,7 +19,7 @@ @pytest.mark.asyncio -def test_timeout_event_on_broken_heartbeat(event_loop): +async def test_timeout_event_on_broken_heartbeat(event_loop): ch = helper.gen_channel("heartbeat-test") pubnub = PubNubAsyncio(messenger_config, custom_event_loop=event_loop) @@ -32,9 +32,9 @@ def test_timeout_event_on_broken_heartbeat(event_loop): callback_presence = SubscribeListener() pubnub_listener.add_listener(callback_presence) pubnub_listener.subscribe().channels(ch).with_presence().execute() - yield from callback_presence.wait_for_connect() + await callback_presence.wait_for_connect() - envelope = yield from callback_presence.wait_for_presence_on(ch) + envelope = await callback_presence.wait_for_presence_on(ch) assert ch == envelope.channel assert 'join' == envelope.event assert pubnub_listener.uuid == envelope.uuid @@ -48,7 +48,7 @@ def test_timeout_event_on_broken_heartbeat(event_loop): presence_future = asyncio.ensure_future(callback_presence.wait_for_presence_on(ch)) # - assert join event - yield from asyncio.wait([useless_connect_future, presence_future]) + await asyncio.wait([useless_connect_future, presence_future]) prs_envelope = presence_future.result() @@ -57,23 +57,23 @@ def test_timeout_event_on_broken_heartbeat(event_loop): assert pubnub.uuid == prs_envelope.uuid # wait for one heartbeat call - yield from asyncio.sleep(8) + await asyncio.sleep(8) # - break messenger heartbeat loop pubnub._subscription_manager._stop_heartbeat_timer() # - assert for timeout - envelope = yield from callback_presence.wait_for_presence_on(ch) + envelope = await callback_presence.wait_for_presence_on(ch) assert ch == envelope.channel assert 'timeout' == envelope.event assert pubnub.uuid == envelope.uuid pubnub.unsubscribe().channels(ch).execute() - yield from callback_messages.wait_for_disconnect() + await callback_messages.wait_for_disconnect() # - disconnect from :ch-pnpres pubnub_listener.unsubscribe().channels(ch).execute() - yield from callback_presence.wait_for_disconnect() + await callback_presence.wait_for_disconnect() pubnub.stop() pubnub_listener.stop() diff --git a/tests/integrational/asyncio/test_here_now.py b/tests/integrational/asyncio/test_here_now.py index 9b8987ad..ddf2e1a3 100644 --- a/tests/integrational/asyncio/test_here_now.py +++ b/tests/integrational/asyncio/test_here_now.py @@ -9,10 +9,12 @@ @get_sleeper('tests/integrational/fixtures/asyncio/here_now/single_channel.yaml') -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/here_now/single_channel.yaml', - filter_query_parameters=['tr', 'uuid', 'pnsdk', 'l_pres']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/here_now/single_channel.yaml', + filter_query_parameters=['tr', 'uuid', 'pnsdk', 'l_pres', 'tt'] +) @pytest.mark.asyncio -def test_single_channel(event_loop, sleeper=asyncio.sleep): +async def test_single_channel(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) pubnub.config.uuid = 'test-here-now-asyncio-uuid1' ch = "test-here-now-asyncio-ch" @@ -21,13 +23,13 @@ def test_single_channel(event_loop, sleeper=asyncio.sleep): pubnub.add_listener(callback) pubnub.subscribe().channels(ch).execute() - yield from callback.wait_for_connect() + await callback.wait_for_connect() - yield from sleeper(5) + await sleeper(5) - env = yield from pubnub.here_now() \ - .channels(ch) \ - .include_uuids(True) \ + env = await pubnub.here_now()\ + .channels(ch)\ + .include_uuids(True)\ .future() assert env.result.total_channels == 1 @@ -39,31 +41,28 @@ def test_single_channel(event_loop, sleeper=asyncio.sleep): assert channels[0].occupancy == 1 assert channels[0].occupants[0].uuid == pubnub.uuid - result = yield from pubnub.here_now() \ - .channels(ch) \ - .include_state(True) \ + result = await pubnub.here_now()\ + .channels(ch)\ + .include_state(True)\ .result() assert result.total_channels == 1 assert result.total_occupancy == 1 pubnub.unsubscribe().channels(ch).execute() - yield from callback.wait_for_disconnect() + await callback.wait_for_disconnect() pubnub.stop() @get_sleeper('tests/integrational/fixtures/asyncio/here_now/multiple_channels.yaml') -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/here_now/multiple_channels.yaml', - filter_query_parameters=['pnsdk', 'l_pres'], - match_on=['method', 'scheme', 'host', 'port', 'string_list_in_path', 'query'], - match_on_kwargs={ - 'string_list_in_path': { - 'positions': [4, 6] - } - }) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/here_now/multiple_channels.yaml', + filter_query_parameters=['pnsdk', 'l_pres'], + match_on=['method', 'scheme', 'host', 'port', 'string_list_in_path', 'query'] +) @pytest.mark.asyncio -def test_multiple_channels(event_loop, sleeper=asyncio.sleep): +async def test_multiple_channels(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) pubnub.config.uuid = 'test-here-now-asyncio-uuid1' @@ -74,10 +73,11 @@ def test_multiple_channels(event_loop, sleeper=asyncio.sleep): pubnub.add_listener(callback) pubnub.subscribe().channels([ch1, ch2]).execute() - yield from callback.wait_for_connect() + await callback.wait_for_connect() + + await sleeper(5) - yield from sleeper(5) - env = yield from pubnub.here_now() \ + env = await pubnub.here_now() \ .channels([ch1, ch2]) \ .future() @@ -92,7 +92,7 @@ def test_multiple_channels(event_loop, sleeper=asyncio.sleep): assert channels[1].occupancy == 1 assert channels[1].occupants[0].uuid == pubnub.uuid - result = yield from pubnub.here_now() \ + result = await pubnub.here_now() \ .channels([ch1, ch2]) \ .include_state(True) \ .result() @@ -100,7 +100,7 @@ def test_multiple_channels(event_loop, sleeper=asyncio.sleep): assert result.total_channels == 2 pubnub.unsubscribe().channels([ch1, ch2]).execute() - yield from callback.wait_for_disconnect() + await callback.wait_for_disconnect() pubnub.stop() @@ -115,7 +115,7 @@ def test_multiple_channels(event_loop, sleeper=asyncio.sleep): } }) @pytest.mark.asyncio -def test_global(event_loop, sleeper=asyncio.sleep): +async def test_global(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) pubnub.config.uuid = 'test-here-now-asyncio-uuid1' @@ -126,36 +126,36 @@ def test_global(event_loop, sleeper=asyncio.sleep): pubnub.add_listener(callback) pubnub.subscribe().channels([ch1, ch2]).execute() - yield from callback.wait_for_connect() + await callback.wait_for_connect() - yield from sleeper(5) + await sleeper(5) - env = yield from pubnub.here_now().future() + env = await pubnub.here_now().future() assert env.result.total_channels >= 2 assert env.result.total_occupancy >= 1 pubnub.unsubscribe().channels([ch1, ch2]).execute() - yield from callback.wait_for_disconnect() + await callback.wait_for_disconnect() pubnub.stop() @pytest.mark.asyncio -def test_here_now_super_call(event_loop): +async def test_here_now_super_call(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = 'test-here-now-asyncio-uuid1' - env = yield from pubnub.here_now().future() + env = await pubnub.here_now().future() assert isinstance(env.result, PNHereNowResult) - env = yield from pubnub.here_now().channel_groups("gr").include_uuids(True).include_state(True).future() + env = await pubnub.here_now().channel_groups("gr").include_uuids(True).include_state(True).future() assert isinstance(env.result, PNHereNowResult) - env = yield from pubnub.here_now().channels('ch.bar*').channel_groups("gr.k").future() + env = await pubnub.here_now().channels('ch.bar*').channel_groups("gr.k").future() assert isinstance(env.result, PNHereNowResult) - env = yield from pubnub.here_now().channels(['ch.bar*', 'ch2']).channel_groups("gr.k").future() + env = await pubnub.here_now().channels(['ch.bar*', 'ch2']).channel_groups("gr.k").future() assert isinstance(env.result, PNHereNowResult) pubnub.stop() diff --git a/tests/integrational/asyncio/test_history_delete.py b/tests/integrational/asyncio/test_history_delete.py index b4513b1f..a0e8511f 100644 --- a/tests/integrational/asyncio/test_history_delete.py +++ b/tests/integrational/asyncio/test_history_delete.py @@ -10,24 +10,28 @@ filter_query_parameters=['uuid', 'pnsdk'] ) @pytest.mark.asyncio -def test_success(event_loop): +async def test_success(event_loop): pubnub = PubNubAsyncio(mocked_config_copy(), custom_event_loop=event_loop) - res = yield from pubnub.delete_messages().channel("my-ch").start(123).end(456).future() + res = await pubnub.delete_messages().channel("my-ch").start(123).end(456).future() if res.status.is_error(): raise AssertionError() + pubnub.stop() + @pn_vcr.use_cassette( "tests/integrational/fixtures/asyncio/history/delete_with_space_and_wildcard_in_channel_name.yaml", filter_query_parameters=['uuid', 'pnsdk'] ) @pytest.mark.asyncio -def test_delete_with_space_and_wildcard_in_channel_name(event_loop): +async def test_delete_with_space_and_wildcard_in_channel_name(event_loop): pubnub = PubNubAsyncio(mocked_config_copy(), custom_event_loop=event_loop) - res = yield from pubnub.delete_messages().channel("my-ch- |.* $").start(123).end(456).future() + res = await pubnub.delete_messages().channel("my-ch- |.* $").start(123).end(456).future() if res.status.is_error(): raise AssertionError() + + pubnub.stop() diff --git a/tests/integrational/asyncio/test_invocations.py b/tests/integrational/asyncio/test_invocations.py index 11afb420..cdb63e84 100644 --- a/tests/integrational/asyncio/test_invocations.py +++ b/tests/integrational/asyncio/test_invocations.py @@ -17,25 +17,29 @@ corrupted_keys.subscribe_key = "blah" -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/invocations/future.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/invocations/future.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_publish_future(event_loop): +async def test_publish_future(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - result = yield from pubnub.publish().message('hey').channel('blah').result() + result = await pubnub.publish().message('hey').channel('blah').result() assert isinstance(result, PNPublishResult) pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/invocations/future_raises_pubnub_error.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/invocations/future_raises_pubnub_error.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_publish_future_raises_pubnub_error(event_loop): +async def test_publish_future_raises_pubnub_error(event_loop): pubnub = PubNubAsyncio(corrupted_keys, custom_event_loop=event_loop) with pytest.raises(PubNubException) as exinfo: - yield from pubnub.publish().message('hey').channel('blah').result() + await pubnub.publish().message('hey').channel('blah').result() assert 'Invalid Subscribe Key' in str(exinfo.value) assert 400 == exinfo.value._status_code @@ -43,40 +47,46 @@ def test_publish_future_raises_pubnub_error(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/invocations/future_raises_ll_error.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/invocations/future_raises_ll_error.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_publish_future_raises_lower_level_error(event_loop): +async def test_publish_future_raises_lower_level_error(event_loop): pubnub = PubNubAsyncio(corrupted_keys, custom_event_loop=event_loop) pubnub._connector.close() with pytest.raises(RuntimeError) as exinfo: - yield from pubnub.publish().message('hey').channel('blah').result() + await pubnub.publish().message('hey').channel('blah').result() assert 'Session is closed' in str(exinfo.value) pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/invocations/envelope.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/invocations/envelope.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_publish_envelope(event_loop): +async def test_publish_envelope(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - envelope = yield from pubnub.publish().message('hey').channel('blah').future() + envelope = await pubnub.publish().message('hey').channel('blah').future() assert isinstance(envelope, AsyncioEnvelope) assert not envelope.is_error() pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/invocations/envelope_raises.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/invocations/envelope_raises.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_publish_envelope_raises(event_loop): +async def test_publish_envelope_raises(event_loop): pubnub = PubNubAsyncio(corrupted_keys, custom_event_loop=event_loop) - e = yield from pubnub.publish().message('hey').channel('blah').future() + e = await pubnub.publish().message('hey').channel('blah').future() assert isinstance(e, PubNubAsyncioException) assert e.is_error() assert 400 == e.value()._status_code @@ -84,15 +94,17 @@ def test_publish_envelope_raises(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/invocations/envelope_raises_ll_error.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/invocations/envelope_raises_ll_error.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_publish_envelope_raises_lower_level_error(event_loop): +async def test_publish_envelope_raises_lower_level_error(event_loop): pubnub = PubNubAsyncio(corrupted_keys, custom_event_loop=event_loop) pubnub._connector.close() - e = yield from pubnub.publish().message('hey').channel('blah').future() + e = await pubnub.publish().message('hey').channel('blah').future() assert isinstance(e, PubNubAsyncioException) assert e.is_error() assert str(e.value()) == 'Session is closed' diff --git a/tests/integrational/asyncio/test_message_count.py b/tests/integrational/asyncio/test_message_count.py index b6cacb47..bfbeba91 100644 --- a/tests/integrational/asyncio/test_message_count.py +++ b/tests/integrational/asyncio/test_message_count.py @@ -16,34 +16,38 @@ def pn(event_loop): pn.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/message_count/single.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pub']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/message_count/single.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pub'] +) @pytest.mark.asyncio -def test_single_channel(pn): +async def test_single_channel(pn): chan = 'unique_asyncio' - envelope = yield from pn.publish().channel(chan).message('bla').future() + envelope = await pn.publish().channel(chan).message('bla').future() time = envelope.result.timetoken - 10 - envelope = yield from pn.message_counts().channel(chan).channel_timetokens([time]).future() + envelope = await pn.message_counts().channel(chan).channel_timetokens([time]).future() - assert(isinstance(envelope, AsyncioEnvelope)) + assert isinstance(envelope, AsyncioEnvelope) assert not envelope.status.is_error() assert envelope.result.channels[chan] == 1 assert isinstance(envelope.result, PNMessageCountResult) assert isinstance(envelope.status, PNStatus) -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/message_count/multi.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pub']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/message_count/multi.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pub'] +) @pytest.mark.asyncio -def test_multiple_channels(pn): +async def test_multiple_channels(pn): chan_1 = 'unique_asyncio_1' chan_2 = 'unique_asyncio_2' chans = ','.join([chan_1, chan_2]) - envelope = yield from pn.publish().channel(chan_1).message('something').future() + envelope = await pn.publish().channel(chan_1).message('something').future() time = envelope.result.timetoken - 10 - envelope = yield from pn.message_counts().channel(chans).channel_timetokens([time, time]).future() + envelope = await pn.message_counts().channel(chans).channel_timetokens([time, time]).future() - assert(isinstance(envelope, AsyncioEnvelope)) + assert isinstance(envelope, AsyncioEnvelope) assert not envelope.status.is_error() assert envelope.result.channels[chan_1] == 1 assert envelope.result.channels[chan_2] == 0 diff --git a/tests/integrational/asyncio/test_pam.py b/tests/integrational/asyncio/test_pam.py index 89bf84b4..b33f2306 100644 --- a/tests/integrational/asyncio/test_pam.py +++ b/tests/integrational/asyncio/test_pam.py @@ -6,17 +6,16 @@ from tests.integrational.vcr_helper import pn_vcr -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/global_level.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/global_level.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'] +) @pytest.mark.asyncio -def test_global_level(event_loop): +async def test_global_level(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "my_uuid" - env = (yield from pubnub.grant() - .write(True) - .read(True) - .future()) + env = await pubnub.grant().write(True).read(True).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert len(env.result.channels) == 0 @@ -26,7 +25,7 @@ def test_global_level(event_loop): assert env.result.manage_enabled is False assert env.result.delete_enabled is False - env = yield from pubnub.revoke().future() + env = await pubnub.revoke().future() assert isinstance(env.result, PNAccessManagerGrantResult) assert len(env.result.channels) == 0 @@ -39,19 +38,17 @@ def test_global_level(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/single_channel.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/single_channel.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'] +) @pytest.mark.asyncio -def test_single_channel(event_loop): +async def test_single_channel(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "my_uuid" ch = "test-pam-asyncio-ch" - env = (yield from pubnub.grant() - .channels(ch) - .write(True) - .read(True) - .future()) + env = await pubnub.grant().channels(ch).write(True).read(True).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert env.result.channels[ch].read_enabled == 1 @@ -62,21 +59,18 @@ def test_single_channel(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/single_channel_with_auth.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/single_channel_with_auth.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'] +) @pytest.mark.asyncio -def test_single_channel_with_auth(event_loop): +async def test_single_channel_with_auth(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "test-pam-asyncio-uuid" ch = "test-pam-asyncio-ch" auth = "test-pam-asyncio-auth" - env = (yield from pubnub.grant() - .channels(ch) - .write(True) - .read(True) - .auth_keys(auth) - .future()) + env = await pubnub.grant().channels(ch).write(True).read(True).auth_keys(auth).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert env.result.channels[ch].auth_keys[auth].read_enabled == 1 @@ -87,25 +81,20 @@ def test_single_channel_with_auth(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/multiple_channels.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'], - match_on=['method', 'scheme', 'host', 'port', 'path', 'string_list_in_query'], - match_on_kwargs={ - 'list_keys': ['channel'], - 'filter_keys': ['signature', 'timestamp'] - }) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/multiple_channels.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'], + match_on=['method', 'scheme', 'host', 'port', 'path', 'string_list_in_query'], + +) @pytest.mark.asyncio -def test_multiple_channels(event_loop): +async def test_multiple_channels(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "test-pam-asyncio-uuid" ch1 = "test-pam-asyncio-ch1" ch2 = "test-pam-asyncio-ch2" - env = (yield from pubnub.grant() - .channels([ch1, ch2]) - .write(True) - .read(True) - .future()) + env = await pubnub.grant().channels([ch1, ch2]).write(True).read(True).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert env.result.channels[ch1].read_enabled is True @@ -120,27 +109,20 @@ def test_multiple_channels(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/multiple_channels_with_auth.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'], - match_on=['method', 'scheme', 'host', 'port', 'path', 'string_list_in_query'], - match_on_kwargs={ - 'list_keys': ['channel'], - 'filter_keys': ['signature', 'timestamp'] - }) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/multiple_channels_with_auth.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'], + match_on=['method', 'scheme', 'host', 'port', 'path', 'string_list_in_query'] +) @pytest.mark.asyncio -def test_multiple_channels_with_auth(event_loop): +async def test_multiple_channels_with_auth(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "my_uuid" ch1 = "test-pam-asyncio-ch1" ch2 = "test-pam-asyncio-ch2" auth = "test-pam-asyncio-auth" - env = (yield from pubnub.grant() - .channels([ch1, ch2]) - .write(True) - .read(True) - .auth_keys(auth) - .future()) + env = await pubnub.grant().channels([ch1, ch2]).write(True).read(True).auth_keys(auth).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert env.result.channels[ch1].auth_keys[auth].read_enabled is True @@ -155,19 +137,17 @@ def test_multiple_channels_with_auth(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/single_channel_group.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/single_channel_group.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'] +) @pytest.mark.asyncio -def test_single_channel_group(event_loop): +async def test_single_channel_group(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "test-pam-asyncio-uuid" cg = "test-pam-asyncio-cg" - env = (yield from pubnub.grant() - .channel_groups(cg) - .write(True) - .read(True) - .future()) + env = await pubnub.grant().channel_groups(cg).write(True).read(True).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert env.result.level == 'channel-group' @@ -179,21 +159,18 @@ def test_single_channel_group(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/single_channel_group_with_auth.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/single_channel_group_with_auth.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'] +) @pytest.mark.asyncio -def test_single_channel_group_with_auth(event_loop): +async def test_single_channel_group_with_auth(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "test-pam-asyncio-uuid" gr = "test-pam-asyncio-cg" auth = "test-pam-asyncio-auth" - env = (yield from pubnub.grant() - .channel_groups(gr) - .write(True) - .read(True) - .auth_keys(auth) - .future()) + env = await pubnub.grant().channel_groups(gr).write(True).read(True).auth_keys(auth).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert env.result.level == 'channel-group+auth' @@ -205,25 +182,19 @@ def test_single_channel_group_with_auth(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/multiple_channel_groups.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'], - match_on=['method', 'scheme', 'host', 'port', 'path', 'string_list_in_query'], - match_on_kwargs={ - 'list_keys': ['channel-group'], - 'filter_keys': ['signature', 'timestamp'] - }) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/multiple_channel_groups.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'], + match_on=['method', 'scheme', 'host', 'port', 'path', 'string_list_in_query'], +) @pytest.mark.asyncio -def test_multiple_channel_groups(event_loop): +async def test_multiple_channel_groups(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "my_uuid" gr1 = "test-pam-asyncio-cg1" gr2 = "test-pam-asyncio-cg2" - env = (yield from pubnub.grant() - .channel_groups([gr1, gr2]) - .write(True) - .read(True) - .future()) + env = await pubnub.grant().channel_groups([gr1, gr2]).write(True).read(True).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert env.result.groups[gr1].read_enabled is True @@ -238,27 +209,20 @@ def test_multiple_channel_groups(event_loop): pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/pam/multiple_channel_groups_with_auth.yaml', - filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'], - match_on=['method', 'scheme', 'host', 'port', 'path', 'string_list_in_query'], - match_on_kwargs={ - 'list_keys': ['channel-group'], - 'filter_keys': ['signature', 'timestamp'] - }) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/pam/multiple_channel_groups_with_auth.yaml', + filter_query_parameters=['signature', 'timestamp', 'pnsdk', 'l_pam'], + match_on=['method', 'scheme', 'host', 'port', 'path', 'string_list_in_query'], +) @pytest.mark.asyncio -def test_multiple_channel_groups_with_auth(event_loop): +async def test_multiple_channel_groups_with_auth(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "my_uuid" gr1 = "test-pam-asyncio-cg1" gr2 = "test-pam-asyncio-cg2" auth = "test-pam-asyncio-auth" - env = (yield from pubnub.grant() - .channel_groups([gr1, gr2]) - .write(True) - .read(True) - .auth_keys(auth) - .future()) + env = await pubnub.grant().channel_groups([gr1, gr2]).write(True).read(True).auth_keys(auth).future() assert isinstance(env.result, PNAccessManagerGrantResult) assert env.result.groups[gr1].auth_keys[auth].read_enabled is True diff --git a/tests/integrational/asyncio/test_publish.py b/tests/integrational/asyncio/test_publish.py index 56e39a2a..c7153552 100644 --- a/tests/integrational/asyncio/test_publish.py +++ b/tests/integrational/asyncio/test_publish.py @@ -9,7 +9,7 @@ from pubnub.models.consumer.pubsub import PNPublishResult from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub_asyncio import PubNubAsyncio, AsyncioEnvelope, PubNubAsyncioException -from tests.helper import pnconf_copy, pnconf_enc_copy, gen_decrypt_func, pnconf_pam_copy +from tests.helper import pnconf_copy, pnconf_enc_copy, pnconf_pam_copy from tests.integrational.vcr_helper import pn_vcr pn.set_stream_logger('pubnub', logging.DEBUG) @@ -18,8 +18,8 @@ @pytest.mark.asyncio -def assert_success_await(pub): - envelope = yield from pub.future() +async def assert_success_await(pub): + envelope = await pub.future() assert isinstance(envelope, AsyncioEnvelope) assert isinstance(envelope.result, PNPublishResult) @@ -29,44 +29,49 @@ def assert_success_await(pub): @pytest.mark.asyncio -def assert_client_side_error(pub, expected_err_msg): +async def assert_client_side_error(pub, expected_err_msg): try: - yield from pub.future() + await pub.future() except PubNubException as e: assert expected_err_msg in str(e) @pytest.mark.asyncio -def assert_success_publish_get(pubnub, msg): - yield from assert_success_await(pubnub.publish().channel(ch).message(msg)) +async def assert_success_publish_get(pubnub, msg): + await assert_success_await(pubnub.publish().channel(ch).message(msg)) @pytest.mark.asyncio -def assert_success_publish_post(pubnub, msg): - yield from assert_success_await(pubnub.publish().channel(ch).message(msg).use_post(True)) +async def assert_success_publish_post(pubnub, msg): + await assert_success_await(pubnub.publish().channel(ch).message(msg).use_post(True)) -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/publish/mixed_via_get.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/publish/mixed_via_get.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_publish_mixed_via_get(event_loop): +async def test_publish_mixed_via_get(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - yield from asyncio.gather( + await asyncio.gather( asyncio.ensure_future(assert_success_publish_get(pubnub, "hi")), asyncio.ensure_future(assert_success_publish_get(pubnub, 5)), asyncio.ensure_future(assert_success_publish_get(pubnub, True)), - asyncio.ensure_future(assert_success_publish_get(pubnub, ["hi", "hi2", "hi3"]))) + asyncio.ensure_future(assert_success_publish_get(pubnub, ["hi", "hi2", "hi3"])) + ) pubnub.stop() -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/publish/object_via_get.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk'], - match_on=['method', 'scheme', 'host', 'port', 'object_in_path', 'query']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/publish/object_via_get.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'], + match_on=['method', 'scheme', 'host', 'port', 'object_in_path', 'query'] +) @pytest.mark.asyncio -def test_publish_object_via_get(event_loop): +async def test_publish_object_via_get(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - yield from asyncio.ensure_future(assert_success_publish_get(pubnub, {"name": "Alex", "online": True})) + await asyncio.ensure_future(assert_success_publish_get(pubnub, {"name": "Alex", "online": True})) pubnub.stop() @@ -75,9 +80,9 @@ def test_publish_object_via_get(event_loop): 'tests/integrational/fixtures/asyncio/publish/mixed_via_post.yaml', filter_query_parameters=['uuid', 'seqn', 'pnsdk']) @pytest.mark.asyncio -def test_publish_mixed_via_post(event_loop): +async def test_publish_mixed_via_post(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - yield from asyncio.gather( + await asyncio.gather( asyncio.ensure_future(assert_success_publish_post(pubnub, "hi")), asyncio.ensure_future(assert_success_publish_post(pubnub, 5)), asyncio.ensure_future(assert_success_publish_post(pubnub, True)), @@ -91,9 +96,9 @@ def test_publish_mixed_via_post(event_loop): filter_query_parameters=['uuid', 'seqn', 'pnsdk'], match_on=['method', 'scheme', 'host', 'port', 'path', 'query', 'object_in_body']) @pytest.mark.asyncio -def test_publish_object_via_post(event_loop): +async def test_publish_object_via_post(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - yield from asyncio.ensure_future(assert_success_publish_post(pubnub, {"name": "Alex", "online": True})) + await asyncio.ensure_future(assert_success_publish_post(pubnub, {"name": "Alex", "online": True})) pubnub.stop() @@ -102,9 +107,9 @@ def test_publish_object_via_post(event_loop): 'tests/integrational/fixtures/asyncio/publish/mixed_via_get_encrypted.yaml', filter_query_parameters=['uuid', 'seqn', 'pnsdk']) @pytest.mark.asyncio -def test_publish_mixed_via_get_encrypted(event_loop): +async def test_publish_mixed_via_get_encrypted(event_loop): pubnub = PubNubAsyncio(pnconf_enc_copy(), custom_event_loop=event_loop) - yield from asyncio.gather( + await asyncio.gather( asyncio.ensure_future(assert_success_publish_get(pubnub, "hi")), asyncio.ensure_future(assert_success_publish_get(pubnub, 5)), asyncio.ensure_future(assert_success_publish_get(pubnub, True)), @@ -116,13 +121,12 @@ def test_publish_mixed_via_get_encrypted(event_loop): @pn_vcr.use_cassette( 'tests/integrational/fixtures/asyncio/publish/object_via_get_encrypted.yaml', filter_query_parameters=['uuid', 'seqn', 'pnsdk'], - match_on=['host', 'method', 'query', 'object_in_path'], - match_on_kwargs={'object_in_path': { - 'decrypter': gen_decrypt_func('testKey')}}) + match_on=['host', 'method', 'query', 'object_in_path_with_decrypt'] +) @pytest.mark.asyncio -def test_publish_object_via_get_encrypted(event_loop): +async def test_publish_object_via_get_encrypted(event_loop): pubnub = PubNubAsyncio(pnconf_enc_copy(), custom_event_loop=event_loop) - yield from asyncio.ensure_future(assert_success_publish_get(pubnub, {"name": "Alex", "online": True})) + await asyncio.ensure_future(assert_success_publish_get(pubnub, {"name": "Alex", "online": True})) pubnub.stop() @@ -130,15 +134,17 @@ def test_publish_object_via_get_encrypted(event_loop): @pn_vcr.use_cassette( 'tests/integrational/fixtures/asyncio/publish/mixed_via_post_encrypted.yaml', filter_query_parameters=['uuid', 'seqn', 'pnsdk'], - match_on=['method', 'path', 'query', 'body']) + match_on=['method', 'path', 'query', 'body'] +) @pytest.mark.asyncio -def test_publish_mixed_via_post_encrypted(event_loop): +async def test_publish_mixed_via_post_encrypted(event_loop): pubnub = PubNubAsyncio(pnconf_enc_copy(), custom_event_loop=event_loop) - yield from asyncio.gather( + await asyncio.gather( asyncio.ensure_future(assert_success_publish_post(pubnub, "hi")), asyncio.ensure_future(assert_success_publish_post(pubnub, 5)), asyncio.ensure_future(assert_success_publish_post(pubnub, True)), - asyncio.ensure_future(assert_success_publish_post(pubnub, ["hi", "hi2", "hi3"]))) + asyncio.ensure_future(assert_success_publish_post(pubnub, ["hi", "hi2", "hi3"])) + ) pubnub.stop() @@ -146,41 +152,40 @@ def test_publish_mixed_via_post_encrypted(event_loop): @pn_vcr.use_cassette( 'tests/integrational/fixtures/asyncio/publish/object_via_post_encrypted.yaml', filter_query_parameters=['uuid', 'seqn', 'pnsdk'], - match_on=['method', 'path', 'query', 'object_in_body'], - match_on_kwargs={'object_in_body': { - 'decrypter': gen_decrypt_func('testKey')}}) + match_on=['method', 'path', 'query', 'object_in_body_with_decrypt'] +) @pytest.mark.asyncio -def test_publish_object_via_post_encrypted(event_loop): +async def test_publish_object_via_post_encrypted(event_loop): pubnub = PubNubAsyncio(pnconf_enc_copy(), custom_event_loop=event_loop) - yield from asyncio.ensure_future(assert_success_publish_post(pubnub, {"name": "Alex", "online": True})) + await asyncio.ensure_future(assert_success_publish_post(pubnub, {"name": "Alex", "online": True})) pubnub.stop() @pytest.mark.asyncio -def test_error_missing_message(event_loop): +async def test_error_missing_message(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - yield from assert_client_side_error(pubnub.publish().channel(ch).message(None), "Message missing") + await assert_client_side_error(pubnub.publish().channel(ch).message(None), "Message missing") pubnub.stop() @pytest.mark.asyncio -def test_error_missing_channel(event_loop): +async def test_error_missing_channel(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - yield from assert_client_side_error(pubnub.publish().channel("").message("hey"), "Channel missing") + await assert_client_side_error(pubnub.publish().channel("").message("hey"), "Channel missing") pubnub.stop() @pytest.mark.asyncio -def test_error_non_serializable(event_loop): +async def test_error_non_serializable(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) def method(): pass - yield from assert_client_side_error(pubnub.publish().channel(ch).message(method), "not JSON serializable") + await assert_client_side_error(pubnub.publish().channel(ch).message(method), "not JSON serializable") pubnub.stop() @@ -189,10 +194,10 @@ def method(): filter_query_parameters=['uuid', 'seqn', 'pnsdk'], match_on=['host', 'method', 'path', 'meta_object_in_query']) @pytest.mark.asyncio -def test_publish_with_meta(event_loop): +async def test_publish_with_meta(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - yield from assert_success_await(pubnub.publish().channel(ch).message("hey").meta({'a': 2, 'b': 'qwer'})) + await assert_success_await(pubnub.publish().channel(ch).message("hey").meta({'a': 2, 'b': 'qwer'})) pubnub.stop() @@ -200,17 +205,17 @@ def test_publish_with_meta(event_loop): 'tests/integrational/fixtures/asyncio/publish/do_not_store.yaml', filter_query_parameters=['uuid', 'seqn', 'pnsdk']) @pytest.mark.asyncio -def test_publish_do_not_store(event_loop): +async def test_publish_do_not_store(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) - yield from assert_success_await(pubnub.publish().channel(ch).message("hey").should_store(False)) + await assert_success_await(pubnub.publish().channel(ch).message("hey").should_store(False)) pubnub.stop() @pytest.mark.asyncio -def assert_server_side_error_yield(pub, expected_err_msg): +async def assert_server_side_error_yield(pub, expected_err_msg): try: - yield from pub.future() + await pub.future() except PubNubAsyncioException as e: assert expected_err_msg in str(e) @@ -219,7 +224,7 @@ def assert_server_side_error_yield(pub, expected_err_msg): 'tests/integrational/fixtures/asyncio/publish/invalid_key.yaml', filter_query_parameters=['uuid', 'seqn', 'pnsdk']) @pytest.mark.asyncio -def test_error_invalid_key(event_loop): +async def test_error_invalid_key(event_loop): conf = PNConfiguration() conf.publish_key = "fake" conf.subscribe_key = "demo" @@ -227,7 +232,7 @@ def test_error_invalid_key(event_loop): pubnub = PubNubAsyncio(conf, custom_event_loop=event_loop) - yield from assert_server_side_error_yield(pubnub.publish().channel(ch).message("hey"), "Invalid Key") + await assert_server_side_error_yield(pubnub.publish().channel(ch).message("hey"), "Invalid Key") pubnub.stop() @@ -235,21 +240,21 @@ def test_error_invalid_key(event_loop): 'tests/integrational/fixtures/asyncio/publish/not_permitted.yaml', filter_query_parameters=['uuid', 'seqn', 'signature', 'timestamp', 'pnsdk']) @pytest.mark.asyncio -def test_not_permitted(event_loop): +async def test_not_permitted(event_loop): pnconf = pnconf_pam_copy() pnconf.secret_key = None pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop) - yield from assert_server_side_error_yield(pubnub.publish().channel(ch).message("hey"), "HTTP Client Error (403") + await assert_server_side_error_yield(pubnub.publish().channel(ch).message("hey"), "HTTP Client Error (403") pubnub.stop() @pytest.mark.asyncio -def test_publish_super_admin_call(event_loop): +async def test_publish_super_admin_call(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) - yield from pubnub.publish().channel(ch).message("hey").future() - yield from pubnub.publish().channel("f#!|oo.bar").message("hey^&#$").should_store(True).meta({ + await pubnub.publish().channel(ch).message("hey").future() + await pubnub.publish().channel("f#!|oo.bar").message("hey^&#$").should_store(True).meta({ 'name': 'alex' }).future() diff --git a/tests/integrational/asyncio/test_signal.py b/tests/integrational/asyncio/test_signal.py index d7704bc6..dab4284e 100644 --- a/tests/integrational/asyncio/test_signal.py +++ b/tests/integrational/asyncio/test_signal.py @@ -16,15 +16,17 @@ def pnconf(): return pnconf -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/signal/single.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/signal/single.yaml', + filter_query_parameters=['uuid', 'seqn', 'pnsdk'] +) @pytest.mark.asyncio -def test_single_channel(pnconf, event_loop): +async def test_single_channel(pnconf, event_loop): pn = PubNubAsyncio(pnconf, custom_event_loop=event_loop) chan = 'unique_sync' - envelope = yield from pn.signal().channel(chan).message('test').future() + envelope = await pn.signal().channel(chan).message('test').future() - assert(isinstance(envelope, AsyncioEnvelope)) + assert isinstance(envelope, AsyncioEnvelope) assert not envelope.status.is_error() assert envelope.result.timetoken == '15640051159323676' assert isinstance(envelope.result, PNSignalResult) diff --git a/tests/integrational/asyncio/test_ssl.py b/tests/integrational/asyncio/test_ssl.py index 8da8c6ea..c67f7ef3 100644 --- a/tests/integrational/asyncio/test_ssl.py +++ b/tests/integrational/asyncio/test_ssl.py @@ -12,12 +12,14 @@ ch = "asyncio-int-publish" -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/secure/ssl.yaml', - filter_query_parameters=['uuid', 'pnsdk']) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/secure/ssl.yaml', + filter_query_parameters=['uuid', 'pnsdk'] +) @pytest.mark.asyncio -def test_publish_string_via_get_encrypted(event_loop): +async def test_publish_string_via_get_encrypted(event_loop): pubnub = PubNubAsyncio(pnconf_ssl_copy(), custom_event_loop=event_loop) - res = yield from pubnub.publish().channel(ch).message("hey").future() + res = await pubnub.publish().channel(ch).message("hey").future() assert res.result.timetoken > 0 pubnub.stop() diff --git a/tests/integrational/asyncio/test_state.py b/tests/integrational/asyncio/test_state.py index 296a4cac..affac111 100644 --- a/tests/integrational/asyncio/test_state.py +++ b/tests/integrational/asyncio/test_state.py @@ -18,13 +18,13 @@ filter_query_parameters=['uuid', 'pnsdk'], match_on=['method', 'host', 'path', 'state_object_in_query']) @pytest.mark.asyncio -def test_single_channelx(event_loop): +async def test_single_channelx(event_loop): pubnub = PubNubAsyncio(pnconf_copy(), custom_event_loop=event_loop) ch = 'test-state-asyncio-ch' pubnub.config.uuid = 'test-state-asyncio-uuid' state = {"name": "Alex", "count": 5} - env = yield from pubnub.set_state() \ + env = await pubnub.set_state() \ .channels(ch) \ .state(state) \ .future() @@ -32,7 +32,7 @@ def test_single_channelx(event_loop): assert env.result.state['name'] == "Alex" assert env.result.state['count'] == 5 - env = yield from pubnub.get_state() \ + env = await pubnub.get_state() \ .channels(ch) \ .future() @@ -48,7 +48,7 @@ def test_single_channelx(event_loop): filter_query_parameters=['uuid', 'pnsdk'], match_on=['method', 'host', 'path', 'state_object_in_query']) @pytest.mark.asyncio -def test_single_channel_with_subscription(event_loop, sleeper=asyncio.sleep): +async def test_single_channel_with_subscription(event_loop, sleeper=asyncio.sleep): pnconf = pnconf_sub_copy() pnconf.set_presence_timeout(12) pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop) @@ -60,10 +60,10 @@ def test_single_channel_with_subscription(event_loop, sleeper=asyncio.sleep): pubnub.add_listener(callback) pubnub.subscribe().channels(ch).execute() - yield from callback.wait_for_connect() - yield from sleeper(20) + await callback.wait_for_connect() + await sleeper(20) - env = yield from pubnub.set_state() \ + env = await pubnub.set_state() \ .channels(ch) \ .state(state) \ .future() @@ -71,7 +71,7 @@ def test_single_channel_with_subscription(event_loop, sleeper=asyncio.sleep): assert env.result.state['name'] == "Alex" assert env.result.state['count'] == 5 - env = yield from pubnub.get_state() \ + env = await pubnub.get_state() \ .channels(ch) \ .future() @@ -79,7 +79,7 @@ def test_single_channel_with_subscription(event_loop, sleeper=asyncio.sleep): assert env.result.channels[ch]['count'] == 5 pubnub.unsubscribe().channels(ch).execute() - yield from callback.wait_for_disconnect() + await callback.wait_for_disconnect() pubnub.stop() @@ -89,14 +89,14 @@ def test_single_channel_with_subscription(event_loop, sleeper=asyncio.sleep): filter_query_parameters=['uuid', 'pnsdk'], match_on=['method', 'host', 'path', 'state_object_in_query']) @pytest.mark.asyncio -def test_multiple_channels(event_loop): +async def test_multiple_channels(event_loop): pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop) ch1 = 'test-state-asyncio-ch1' ch2 = 'test-state-asyncio-ch2' pubnub.config.uuid = 'test-state-asyncio-uuid' state = {"name": "Alex", "count": 5} - env = yield from pubnub.set_state() \ + env = await pubnub.set_state() \ .channels([ch1, ch2]) \ .state(state) \ .future() @@ -104,7 +104,7 @@ def test_multiple_channels(event_loop): assert env.result.state['name'] == "Alex" assert env.result.state['count'] == 5 - env = yield from pubnub.get_state() \ + env = await pubnub.get_state() \ .channels([ch1, ch2]) \ .future() @@ -117,7 +117,7 @@ def test_multiple_channels(event_loop): @pytest.mark.asyncio -def test_state_super_admin_call(event_loop): +async def test_state_super_admin_call(event_loop): pnconf = pnconf_pam_copy() pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop) ch1 = 'test-state-asyncio-ch1' @@ -125,13 +125,13 @@ def test_state_super_admin_call(event_loop): pubnub.config.uuid = 'test-state-asyncio-uuid-|.*$' state = {"name": "Alex", "count": 5} - env = yield from pubnub.set_state() \ + env = await pubnub.set_state() \ .channels([ch1, ch2]) \ .state(state) \ .future() assert isinstance(env.result, PNSetStateResult) - env = yield from pubnub.get_state() \ + env = await pubnub.get_state() \ .channels([ch1, ch2]) \ .future() assert isinstance(env.result, PNGetStateResult) diff --git a/tests/integrational/asyncio/test_subscribe.py b/tests/integrational/asyncio/test_subscribe.py index 07b93830..cb8856da 100644 --- a/tests/integrational/asyncio/test_subscribe.py +++ b/tests/integrational/asyncio/test_subscribe.py @@ -12,14 +12,14 @@ pn.set_stream_logger('pubnub', logging.DEBUG) -def patch_pubnub(pubnub): +async def patch_pubnub(pubnub): pubnub._subscription_manager._reconnection_manager = VCR599ReconnectionManager(pubnub) @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/subscription/sub_unsub.yaml', filter_query_parameters=['uuid', 'pnsdk']) @pytest.mark.asyncio -def test_subscribe_unsubscribe(event_loop): +async def test_subscribe_unsubscribe(event_loop): channel = "test-subscribe-asyncio-ch" pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) @@ -31,7 +31,7 @@ def test_subscribe_unsubscribe(event_loop): assert channel in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 1 - yield from callback.wait_for_connect() + await callback.wait_for_connect() assert channel in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 1 @@ -39,7 +39,7 @@ def test_subscribe_unsubscribe(event_loop): assert channel not in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 0 - yield from callback.wait_for_disconnect() + # await callback.wait_for_disconnect() assert channel not in pubnub.get_subscribed_channels() assert len(pubnub.get_subscribed_channels()) == 0 @@ -49,7 +49,7 @@ def test_subscribe_unsubscribe(event_loop): @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/subscription/sub_pub_unsub.yaml', filter_query_parameters=['pnsdk']) @pytest.mark.asyncio -def test_subscribe_publish_unsubscribe(event_loop): +async def test_subscribe_publish_unsubscribe(event_loop): pubnub_sub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) pubnub_pub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) @@ -65,12 +65,12 @@ def test_subscribe_publish_unsubscribe(event_loop): pubnub_sub.add_listener(callback) pubnub_sub.subscribe().channels(channel).execute() - yield from callback.wait_for_connect() + await callback.wait_for_connect() publish_future = asyncio.ensure_future(pubnub_pub.publish().channel(channel).message(message).future()) subscribe_message_future = asyncio.ensure_future(callback.wait_for_message_on(channel)) - yield from asyncio.wait([ + await asyncio.wait([ publish_future, subscribe_message_future ]) @@ -89,7 +89,7 @@ def test_subscribe_publish_unsubscribe(event_loop): assert publish_envelope.status.original_response[0] == 1 pubnub_sub.unsubscribe().channels(channel).execute() - yield from callback.wait_for_disconnect() + # await callback.wait_for_disconnect() pubnub_pub.stop() pubnub_sub.stop() @@ -98,7 +98,7 @@ def test_subscribe_publish_unsubscribe(event_loop): @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/subscription/sub_pub_unsub_enc.yaml', filter_query_parameters=['pnsdk']) @pytest.mark.asyncio -def test_encrypted_subscribe_publish_unsubscribe(event_loop): +async def test_encrypted_subscribe_publish_unsubscribe(event_loop): pubnub = PubNubAsyncio(pnconf_enc_sub_copy(), custom_event_loop=event_loop) pubnub.config.uuid = 'test-subscribe-asyncio-uuid' @@ -108,12 +108,12 @@ def test_encrypted_subscribe_publish_unsubscribe(event_loop): pubnub.add_listener(callback) pubnub.subscribe().channels(channel).execute() - yield from callback.wait_for_connect() + await callback.wait_for_connect() publish_future = asyncio.ensure_future(pubnub.publish().channel(channel).message(message).future()) subscribe_message_future = asyncio.ensure_future(callback.wait_for_message_on(channel)) - yield from asyncio.wait([ + await asyncio.wait([ publish_future, subscribe_message_future ]) @@ -132,7 +132,7 @@ def test_encrypted_subscribe_publish_unsubscribe(event_loop): assert publish_envelope.status.original_response[0] == 1 pubnub.unsubscribe().channels(channel).execute() - yield from callback.wait_for_disconnect() + await callback.wait_for_disconnect() pubnub.stop() @@ -140,7 +140,7 @@ def test_encrypted_subscribe_publish_unsubscribe(event_loop): @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/subscription/join_leave.yaml', filter_query_parameters=['pnsdk', 'l_cg']) @pytest.mark.asyncio -def test_join_leave(event_loop): +async def test_join_leave(event_loop): channel = "test-subscribe-asyncio-join-leave-ch" pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) @@ -158,33 +158,33 @@ def test_join_leave(event_loop): pubnub_listener.add_listener(callback_presence) pubnub_listener.subscribe().channels(channel).with_presence().execute() - yield from callback_presence.wait_for_connect() + await callback_presence.wait_for_connect() - envelope = yield from callback_presence.wait_for_presence_on(channel) + envelope = await callback_presence.wait_for_presence_on(channel) assert envelope.channel == channel assert envelope.event == 'join' assert envelope.uuid == pubnub_listener.uuid pubnub.add_listener(callback_messages) pubnub.subscribe().channels(channel).execute() - yield from callback_messages.wait_for_connect() + await callback_messages.wait_for_connect() - envelope = yield from callback_presence.wait_for_presence_on(channel) + envelope = await callback_presence.wait_for_presence_on(channel) assert envelope.channel == channel assert envelope.event == 'join' assert envelope.uuid == pubnub.uuid pubnub.unsubscribe().channels(channel).execute() - yield from callback_messages.wait_for_disconnect() + await callback_messages.wait_for_disconnect() - envelope = yield from callback_presence.wait_for_presence_on(channel) + envelope = await callback_presence.wait_for_presence_on(channel) assert envelope.channel == channel assert envelope.event == 'leave' assert envelope.uuid == pubnub.uuid pubnub_listener.unsubscribe().channels(channel).execute() - yield from callback_presence.wait_for_disconnect() + await callback_presence.wait_for_disconnect() pubnub.stop() pubnub_listener.stop() @@ -194,26 +194,26 @@ def test_join_leave(event_loop): @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/subscription/cg_sub_unsub.yaml', filter_query_parameters=['uuid', 'pnsdk', 'l_cg', 'l_pres']) @pytest.mark.asyncio -def test_cg_subscribe_unsubscribe(event_loop, sleeper=asyncio.sleep): +async def test_cg_subscribe_unsubscribe(event_loop, sleeper=asyncio.sleep): ch = "test-subscribe-asyncio-channel" gr = "test-subscribe-asyncio-group" pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) - envelope = yield from pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() + envelope = await pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() assert envelope.status.original_response['status'] == 200 - yield from sleeper(3) + await sleeper(3) callback_messages = SubscribeListener() pubnub.add_listener(callback_messages) pubnub.subscribe().channel_groups(gr).execute() - yield from callback_messages.wait_for_connect() + await callback_messages.wait_for_connect() pubnub.unsubscribe().channel_groups(gr).execute() - yield from callback_messages.wait_for_disconnect() + await callback_messages.wait_for_disconnect() - envelope = yield from pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() + envelope = await pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() assert envelope.status.original_response['status'] == 200 pubnub.stop() @@ -223,26 +223,26 @@ def test_cg_subscribe_unsubscribe(event_loop, sleeper=asyncio.sleep): @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/subscription/cg_sub_pub_unsub.yaml', filter_query_parameters=['uuid', 'pnsdk', 'l_cg', 'l_pres', 'l_pub']) @pytest.mark.asyncio -def test_cg_subscribe_publish_unsubscribe(event_loop, sleeper=asyncio.sleep): +async def test_cg_subscribe_publish_unsubscribe(event_loop, sleeper=asyncio.sleep): ch = "test-subscribe-asyncio-channel" gr = "test-subscribe-asyncio-group" message = "hey" pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) - envelope = yield from pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() + envelope = await pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() assert envelope.status.original_response['status'] == 200 - yield from sleeper(1) + await sleeper(1) callback_messages = VCR599Listener(1) pubnub.add_listener(callback_messages) pubnub.subscribe().channel_groups(gr).execute() - yield from callback_messages.wait_for_connect() + await callback_messages.wait_for_connect() subscribe_future = asyncio.ensure_future(callback_messages.wait_for_message_on(ch)) publish_future = asyncio.ensure_future(pubnub.publish().channel(ch).message(message).future()) - yield from asyncio.wait([subscribe_future, publish_future]) + await asyncio.wait([subscribe_future, publish_future]) sub_envelope = subscribe_future.result() pub_envelope = publish_future.result() @@ -255,9 +255,9 @@ def test_cg_subscribe_publish_unsubscribe(event_loop, sleeper=asyncio.sleep): assert sub_envelope.message == message pubnub.unsubscribe().channel_groups(gr).execute() - yield from callback_messages.wait_for_disconnect() + await callback_messages.wait_for_disconnect() - envelope = yield from pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() + envelope = await pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() assert envelope.status.original_response['status'] == 200 pubnub.stop() @@ -267,7 +267,7 @@ def test_cg_subscribe_publish_unsubscribe(event_loop, sleeper=asyncio.sleep): @pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/subscription/cg_join_leave.yaml', filter_query_parameters=['pnsdk', 'l_cg', 'l_pres']) @pytest.mark.asyncio -def test_cg_join_leave(event_loop, sleeper=asyncio.sleep): +async def test_cg_join_leave(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) pubnub_listener = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) @@ -277,19 +277,19 @@ def test_cg_join_leave(event_loop, sleeper=asyncio.sleep): ch = "test-subscribe-asyncio-join-leave-cg-channel" gr = "test-subscribe-asyncio-join-leave-cg-group" - envelope = yield from pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() + envelope = await pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() assert envelope.status.original_response['status'] == 200 - yield from sleeper(1) + await sleeper(1) callback_messages = VCR599Listener(1) callback_presence = VCR599Listener(1) pubnub_listener.add_listener(callback_presence) pubnub_listener.subscribe().channel_groups(gr).with_presence().execute() - yield from callback_presence.wait_for_connect() + await callback_presence.wait_for_connect() - prs_envelope = yield from callback_presence.wait_for_presence_on(ch) + prs_envelope = await callback_presence.wait_for_presence_on(ch) assert prs_envelope.event == 'join' assert prs_envelope.uuid == pubnub_listener.uuid assert prs_envelope.channel == ch @@ -300,7 +300,7 @@ def test_cg_join_leave(event_loop, sleeper=asyncio.sleep): callback_messages_future = asyncio.ensure_future(callback_messages.wait_for_connect()) presence_messages_future = asyncio.ensure_future(callback_presence.wait_for_presence_on(ch)) - yield from asyncio.wait([callback_messages_future, presence_messages_future]) + await asyncio.wait([callback_messages_future, presence_messages_future]) prs_envelope = presence_messages_future.result() assert prs_envelope.event == 'join' @@ -312,7 +312,7 @@ def test_cg_join_leave(event_loop, sleeper=asyncio.sleep): callback_messages_future = asyncio.ensure_future(callback_messages.wait_for_disconnect()) presence_messages_future = asyncio.ensure_future(callback_presence.wait_for_presence_on(ch)) - yield from asyncio.wait([callback_messages_future, presence_messages_future]) + await asyncio.wait([callback_messages_future, presence_messages_future]) prs_envelope = presence_messages_future.result() assert prs_envelope.event == 'leave' @@ -321,9 +321,9 @@ def test_cg_join_leave(event_loop, sleeper=asyncio.sleep): assert prs_envelope.subscription == gr pubnub_listener.unsubscribe().channel_groups(gr).execute() - yield from callback_presence.wait_for_disconnect() + await callback_presence.wait_for_disconnect() - envelope = yield from pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() + envelope = await pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() assert envelope.status.original_response['status'] == 200 pubnub.stop() @@ -331,20 +331,13 @@ def test_cg_join_leave(event_loop, sleeper=asyncio.sleep): @get_sleeper('tests/integrational/fixtures/asyncio/subscription/unsubscribe_all.yaml') -@pn_vcr.use_cassette('tests/integrational/fixtures/asyncio/subscription/unsubscribe_all.yaml', - filter_query_parameters=['pnsdk', 'l_cg', 'l_pres'], - match_on=['method', 'scheme', 'host', 'port', 'string_list_in_path', 'string_list_in_query'], - match_on_kwargs={ - 'string_list_in_path': { - 'positions': [4, 6] - }, - 'string_list_in_query': { - 'list_keys': ['channel-group'] - } - } - ) +@pn_vcr.use_cassette( + 'tests/integrational/fixtures/asyncio/subscription/unsubscribe_all.yaml', + filter_query_parameters=['pnsdk', 'l_cg', 'l_pres'], + match_on=['method', 'scheme', 'host', 'port', 'string_list_in_path', 'string_list_in_query'], +) @pytest.mark.asyncio -def test_unsubscribe_all(event_loop, sleeper=asyncio.sleep): +async def test_unsubscribe_all(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) pubnub.config.uuid = "test-subscribe-asyncio-messenger" @@ -356,32 +349,32 @@ def test_unsubscribe_all(event_loop, sleeper=asyncio.sleep): gr1 = "test-subscribe-asyncio-unsubscribe-all-gr1" gr2 = "test-subscribe-asyncio-unsubscribe-all-gr2" - envelope = yield from pubnub.add_channel_to_channel_group().channel_group(gr1).channels(ch).future() + envelope = await pubnub.add_channel_to_channel_group().channel_group(gr1).channels(ch).future() assert envelope.status.original_response['status'] == 200 - envelope = yield from pubnub.add_channel_to_channel_group().channel_group(gr2).channels(ch).future() + envelope = await pubnub.add_channel_to_channel_group().channel_group(gr2).channels(ch).future() assert envelope.status.original_response['status'] == 200 - yield from sleeper(1) + await sleeper(1) callback_messages = VCR599Listener(1) pubnub.add_listener(callback_messages) pubnub.subscribe().channels([ch1, ch2, ch3]).channel_groups([gr1, gr2]).execute() - yield from callback_messages.wait_for_connect() + await callback_messages.wait_for_connect() assert len(pubnub.get_subscribed_channels()) == 3 assert len(pubnub.get_subscribed_channel_groups()) == 2 pubnub.unsubscribe_all() - yield from callback_messages.wait_for_disconnect() + await callback_messages.wait_for_disconnect() assert len(pubnub.get_subscribed_channels()) == 0 assert len(pubnub.get_subscribed_channel_groups()) == 0 - envelope = yield from pubnub.remove_channel_from_channel_group().channel_group(gr1).channels(ch).future() + envelope = await pubnub.remove_channel_from_channel_group().channel_group(gr1).channels(ch).future() assert envelope.status.original_response['status'] == 200 - envelope = yield from pubnub.remove_channel_from_channel_group().channel_group(gr2).channels(ch).future() + envelope = await pubnub.remove_channel_from_channel_group().channel_group(gr2).channels(ch).future() assert envelope.status.original_response['status'] == 200 pubnub.stop() diff --git a/tests/integrational/asyncio/test_time.py b/tests/integrational/asyncio/test_time.py index d4765181..a7026246 100644 --- a/tests/integrational/asyncio/test_time.py +++ b/tests/integrational/asyncio/test_time.py @@ -10,10 +10,10 @@ 'tests/integrational/fixtures/asyncio/time/get.yaml', filter_query_parameters=['uuid', 'pnsdk']) @pytest.mark.asyncio -def test_time(event_loop): +async def test_time(event_loop): pubnub = PubNubAsyncio(pnconf, custom_event_loop=event_loop) - res = yield from pubnub.time().result() + res = await pubnub.time().result() assert int(res) > 0 assert isinstance(res.date_time(), date) diff --git a/tests/integrational/asyncio/test_where_now.py b/tests/integrational/asyncio/test_where_now.py index ea69a941..a3e1c5f2 100644 --- a/tests/integrational/asyncio/test_where_now.py +++ b/tests/integrational/asyncio/test_where_now.py @@ -13,7 +13,7 @@ 'tests/integrational/fixtures/asyncio/where_now/single_channel.yaml', filter_query_parameters=['uuid', 'pnsdk']) @pytest.mark.asyncio -def test_single_channel(event_loop, sleeper=asyncio.sleep): +async def test_single_channel(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) ch = 'test-where-now-asyncio-ch' uuid = 'test-where-now-asyncio-uuid' @@ -23,11 +23,11 @@ def test_single_channel(event_loop, sleeper=asyncio.sleep): pubnub.add_listener(callback) pubnub.subscribe().channels(ch).execute() - yield from callback.wait_for_connect() + await callback.wait_for_connect() - yield from sleeper(2) + await sleeper(2) - env = yield from pubnub.where_now() \ + env = await pubnub.where_now() \ .uuid(uuid) \ .future() @@ -37,7 +37,7 @@ def test_single_channel(event_loop, sleeper=asyncio.sleep): assert channels[0] == ch pubnub.unsubscribe().channels(ch).execute() - yield from callback.wait_for_disconnect() + await callback.wait_for_disconnect() pubnub.stop() @@ -47,13 +47,9 @@ def test_single_channel(event_loop, sleeper=asyncio.sleep): 'tests/integrational/fixtures/asyncio/where_now/multiple_channels.yaml', filter_query_parameters=['pnsdk'], match_on=['method', 'scheme', 'host', 'port', 'string_list_in_path', 'query'], - match_on_kwargs={ - 'string_list_in_path': { - 'positions': [4] - } - }) +) @pytest.mark.asyncio -def test_multiple_channels(event_loop, sleeper=asyncio.sleep): +async def test_multiple_channels(event_loop, sleeper=asyncio.sleep): pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) ch1 = 'test-where-now-asyncio-ch1' @@ -65,11 +61,11 @@ def test_multiple_channels(event_loop, sleeper=asyncio.sleep): pubnub.add_listener(callback) pubnub.subscribe().channels([ch1, ch2]).execute() - yield from callback.wait_for_connect() + await callback.wait_for_connect() - yield from sleeper(7) + await sleeper(7) - env = yield from pubnub.where_now() \ + env = await pubnub.where_now() \ .uuid(uuid) \ .future() @@ -80,19 +76,19 @@ def test_multiple_channels(event_loop, sleeper=asyncio.sleep): assert ch2 in channels pubnub.unsubscribe().channels([ch1, ch2]).execute() - yield from callback.wait_for_disconnect() + await callback.wait_for_disconnect() pubnub.stop() @pytest.mark.asyncio -def test_where_now_super_admin_call(event_loop): +async def test_where_now_super_admin_call(event_loop): pubnub = PubNubAsyncio(pnconf_pam_copy(), custom_event_loop=event_loop) uuid = 'test-where-now-asyncio-uuid-.*|@' pubnub.config.uuid = uuid - res = yield from pubnub.where_now() \ + res = await pubnub.where_now() \ .uuid(uuid) \ .result() assert isinstance(res, PNWhereNowResult) diff --git a/tests/integrational/fixtures/asyncio/file_upload/send_and_download_encrypted_file.yaml b/tests/integrational/fixtures/asyncio/file_upload/send_and_download_encrypted_file.yaml index ee5bb687..81b671f7 100644 --- a/tests/integrational/fixtures/asyncio/file_upload/send_and_download_encrypted_file.yaml +++ b/tests/integrational/fixtures/asyncio/file_upload/send_and_download_encrypted_file.yaml @@ -8,27 +8,27 @@ interactions: uri: https://ps.pndsn.com/v1/files/sub-c-mock-key/channels/files_asyncio_ch/generate-upload-url response: body: - string: '{"status":200,"data":{"id":"8c3a0729-b209-4d3a-9674-5b2e4a66f76d","name":"king_arthur.txt"},"file_upload_request":{"url":"https://pubnub-mnemosyne-files-eu-central-1-prd.s3.amazonaws.com/","method":"POST","expiration_date":"2020-11-25T13:49:45Z","form_fields":[{"key":"tagging","value":"\u003cTagging\u003e\u003cTagSet\u003e\u003cTag\u003e\u003cKey\u003eObjectTTLInDays\u003c/Key\u003e\u003cValue\u003e1\u003c/Value\u003e\u003c/Tag\u003e\u003c/TagSet\u003e\u003c/Tagging\u003e"},{"key":"key","value":"sub-c-mock-key/0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0/8c3a0729-b209-4d3a-9674-5b2e4a66f76d/king_arthur.txt"},{"key":"Content-Type","value":"text/plain; - charset=utf-8"},{"key":"X-Amz-Credential","value":"AKIAY7AU6GQD5KWBS3FG/20201125/eu-central-1/s3/aws4_request"},{"key":"X-Amz-Security-Token","value":""},{"key":"X-Amz-Algorithm","value":"AWS4-HMAC-SHA256"},{"key":"X-Amz-Date","value":"20201125T134945Z"},{"key":"Policy","value":"CnsKCSJleHBpcmF0aW9uIjogIjIwMjAtMTEtMjVUMTM6NDk6NDVaIiwKCSJjb25kaXRpb25zIjogWwoJCXsiYnVja2V0IjogInB1Ym51Yi1tbmVtb3N5bmUtZmlsZXMtZXUtY2VudHJhbC0xLXByZCJ9LAoJCVsiZXEiLCAiJHRhZ2dpbmciLCAiPFRhZ2dpbmc+PFRhZ1NldD48VGFnPjxLZXk+T2JqZWN0VFRMSW5EYXlzPC9LZXk+PFZhbHVlPjE8L1ZhbHVlPjwvVGFnPjwvVGFnU2V0PjwvVGFnZ2luZz4iXSwKCQlbImVxIiwgIiRrZXkiLCAic3ViLWMtYzg4MjQyZmEtMTNhZS0xMWViLWJjMzQtY2U2ZmQ5NjdhZjk1LzBNUjEtejJ3MG5TSll4d0V5NzRwNVFqVjg1VG1nTkJLUHJWNzF0NTVOVDAvOGMzYTA3MjktYjIwOS00ZDNhLTk2NzQtNWIyZTRhNjZmNzZkL2tpbmdfYXJ0aHVyLnR4dCJdLAoJCVsiY29udGVudC1sZW5ndGgtcmFuZ2UiLCAwLCA1MjQyODgwXSwKCQlbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiIl0sCgkJeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFZN0FVNkdRRDVLV0JTM0ZHLzIwMjAxMTI1L2V1LWNlbnRyYWwtMS9zMy9hd3M0X3JlcXVlc3QifSwKCQl7IngtYW16LXNlY3VyaXR5LXRva2VuIjogIiJ9LAoJCXsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwKCQl7IngtYW16LWRhdGUiOiAiMjAyMDExMjVUMTM0OTQ1WiIgfQoJXQp9Cg=="},{"key":"X-Amz-Signature","value":"98c25c9d14208702c4bee91a57e7d162b81f843119b188f46817b86217233f13"}]}}' + string: '{"status":200,"data":{"id":"e818082d-f0da-435f-bd17-70f0807150c4","name":"king_arthur.txt"},"file_upload_request":{"url":"https://pubnub-mnemosyne-files-eu-central-1-prd.s3.amazonaws.com/","method":"POST","expiration_date":"2020-12-09T16:41:05Z","form_fields":[{"key":"tagging","value":"\u003cTagging\u003e\u003cTagSet\u003e\u003cTag\u003e\u003cKey\u003eObjectTTLInDays\u003c/Key\u003e\u003cValue\u003e1\u003c/Value\u003e\u003c/Tag\u003e\u003c/TagSet\u003e\u003c/Tagging\u003e"},{"key":"key","value":"sub-c-mock-key/0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0/e818082d-f0da-435f-bd17-70f0807150c4/king_arthur.txt"},{"key":"Content-Type","value":"text/plain; + charset=utf-8"},{"key":"X-Amz-Credential","value":"AKIAY7AU6GQD5KWBS3FG/20201209/eu-central-1/s3/aws4_request"},{"key":"X-Amz-Security-Token","value":""},{"key":"X-Amz-Algorithm","value":"AWS4-HMAC-SHA256"},{"key":"X-Amz-Date","value":"20201209T164105Z"},{"key":"Policy","value":"CnsKCSJleHBpcmF0aW9uIjogIjIwMjAtMTItMDlUMTY6NDE6MDVaIiwKCSJjb25kaXRpb25zIjogWwoJCXsiYnVja2V0IjogInB1Ym51Yi1tbmVtb3N5bmUtZmlsZXMtZXUtY2VudHJhbC0xLXByZCJ9LAoJCVsiZXEiLCAiJHRhZ2dpbmciLCAiPFRhZ2dpbmc+PFRhZ1NldD48VGFnPjxLZXk+T2JqZWN0VFRMSW5EYXlzPC9LZXk+PFZhbHVlPjE8L1ZhbHVlPjwvVGFnPjwvVGFnU2V0PjwvVGFnZ2luZz4iXSwKCQlbImVxIiwgIiRrZXkiLCAic3ViLWMtYzg4MjQyZmEtMTNhZS0xMWViLWJjMzQtY2U2ZmQ5NjdhZjk1LzBNUjEtejJ3MG5TSll4d0V5NzRwNVFqVjg1VG1nTkJLUHJWNzF0NTVOVDAvZTgxODA4MmQtZjBkYS00MzVmLWJkMTctNzBmMDgwNzE1MGM0L2tpbmdfYXJ0aHVyLnR4dCJdLAoJCVsiY29udGVudC1sZW5ndGgtcmFuZ2UiLCAwLCA1MjQyODgwXSwKCQlbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiIl0sCgkJeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFZN0FVNkdRRDVLV0JTM0ZHLzIwMjAxMjA5L2V1LWNlbnRyYWwtMS9zMy9hd3M0X3JlcXVlc3QifSwKCQl7IngtYW16LXNlY3VyaXR5LXRva2VuIjogIiJ9LAoJCXsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwKCQl7IngtYW16LWRhdGUiOiAiMjAyMDEyMDlUMTY0MTA1WiIgfQoJXQp9Cg=="},{"key":"X-Amz-Signature","value":"ee002907feaafc2140855b38a2f98461bc1fe828c77aa0ffc1f5ae1a5d3985d0"}]}}' headers: - Access-Control-Allow-Origin: '*' - Connection: keep-alive - Content-Encoding: gzip - Content-Type: application/json - Date: Wed, 25 Nov 2020 13:48:45 GMT - Transfer-Encoding: chunked - Vary: Accept-Encoding + Access-Control-Allow-Origin: + - '*' + Connection: + - keep-alive + Content-Encoding: + - gzip + Content-Type: + - application/json + Date: + - Wed, 09 Dec 2020 16:40:05 GMT + Transfer-Encoding: + - chunked + Vary: + - Accept-Encoding status: code: 200 message: OK - url: !!python/object/new:yarl.URL - state: !!python/tuple - - !!python/object/new:urllib.parse.SplitResult - - https - - ps.pndsn.com - - /v1/files/sub-c-mock-key/channels/files_asyncio_ch/generate-upload-url - - pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=671a0ccb-d502-49f7-8467-45fe505c7090 - - '' + url: https://ps.pndsn.com/v1/files/sub-c-mock-key/channels/files_asyncio_ch/generate-upload-url?pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=b2ad5a21-4f37-4b44-a514-8b7971c57f08 - request: body: !!python/object:aiohttp.formdata.FormData _charset: null @@ -39,7 +39,7 @@ interactions: - name - tagging - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - ObjectTTLInDays1 - !!python/tuple @@ -48,16 +48,16 @@ interactions: - name - key - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - - sub-c-mock-key/0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0/8c3a0729-b209-4d3a-9674-5b2e4a66f76d/king_arthur.txt + - sub-c-mock-key/0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0/e818082d-f0da-435f-bd17-70f0807150c4/king_arthur.txt - !!python/tuple - !!python/object/apply:multidict._multidict.MultiDict - - !!python/tuple - name - Content-Type - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - text/plain; charset=utf-8 - !!python/tuple @@ -66,16 +66,16 @@ interactions: - name - X-Amz-Credential - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - - AKIAY7AU6GQD5KWBS3FG/20201125/eu-central-1/s3/aws4_request + - AKIAY7AU6GQD5KWBS3FG/20201209/eu-central-1/s3/aws4_request - !!python/tuple - !!python/object/apply:multidict._multidict.MultiDict - - !!python/tuple - name - X-Amz-Security-Token - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - '' - !!python/tuple @@ -84,7 +84,7 @@ interactions: - name - X-Amz-Algorithm - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - AWS4-HMAC-SHA256 - !!python/tuple @@ -93,27 +93,27 @@ interactions: - name - X-Amz-Date - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - - 20201125T134945Z + - 20201209T164105Z - !!python/tuple - !!python/object/apply:multidict._multidict.MultiDict - - !!python/tuple - name - Policy - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - - CnsKCSJleHBpcmF0aW9uIjogIjIwMjAtMTEtMjVUMTM6NDk6NDVaIiwKCSJjb25kaXRpb25zIjogWwoJCXsiYnVja2V0IjogInB1Ym51Yi1tbmVtb3N5bmUtZmlsZXMtZXUtY2VudHJhbC0xLXByZCJ9LAoJCVsiZXEiLCAiJHRhZ2dpbmciLCAiPFRhZ2dpbmc+PFRhZ1NldD48VGFnPjxLZXk+T2JqZWN0VFRMSW5EYXlzPC9LZXk+PFZhbHVlPjE8L1ZhbHVlPjwvVGFnPjwvVGFnU2V0PjwvVGFnZ2luZz4iXSwKCQlbImVxIiwgIiRrZXkiLCAic3ViLWMtYzg4MjQyZmEtMTNhZS0xMWViLWJjMzQtY2U2ZmQ5NjdhZjk1LzBNUjEtejJ3MG5TSll4d0V5NzRwNVFqVjg1VG1nTkJLUHJWNzF0NTVOVDAvOGMzYTA3MjktYjIwOS00ZDNhLTk2NzQtNWIyZTRhNjZmNzZkL2tpbmdfYXJ0aHVyLnR4dCJdLAoJCVsiY29udGVudC1sZW5ndGgtcmFuZ2UiLCAwLCA1MjQyODgwXSwKCQlbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiIl0sCgkJeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFZN0FVNkdRRDVLV0JTM0ZHLzIwMjAxMTI1L2V1LWNlbnRyYWwtMS9zMy9hd3M0X3JlcXVlc3QifSwKCQl7IngtYW16LXNlY3VyaXR5LXRva2VuIjogIiJ9LAoJCXsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwKCQl7IngtYW16LWRhdGUiOiAiMjAyMDExMjVUMTM0OTQ1WiIgfQoJXQp9Cg== + - CnsKCSJleHBpcmF0aW9uIjogIjIwMjAtMTItMDlUMTY6NDE6MDVaIiwKCSJjb25kaXRpb25zIjogWwoJCXsiYnVja2V0IjogInB1Ym51Yi1tbmVtb3N5bmUtZmlsZXMtZXUtY2VudHJhbC0xLXByZCJ9LAoJCVsiZXEiLCAiJHRhZ2dpbmciLCAiPFRhZ2dpbmc+PFRhZ1NldD48VGFnPjxLZXk+T2JqZWN0VFRMSW5EYXlzPC9LZXk+PFZhbHVlPjE8L1ZhbHVlPjwvVGFnPjwvVGFnU2V0PjwvVGFnZ2luZz4iXSwKCQlbImVxIiwgIiRrZXkiLCAic3ViLWMtYzg4MjQyZmEtMTNhZS0xMWViLWJjMzQtY2U2ZmQ5NjdhZjk1LzBNUjEtejJ3MG5TSll4d0V5NzRwNVFqVjg1VG1nTkJLUHJWNzF0NTVOVDAvZTgxODA4MmQtZjBkYS00MzVmLWJkMTctNzBmMDgwNzE1MGM0L2tpbmdfYXJ0aHVyLnR4dCJdLAoJCVsiY29udGVudC1sZW5ndGgtcmFuZ2UiLCAwLCA1MjQyODgwXSwKCQlbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiIl0sCgkJeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFZN0FVNkdRRDVLV0JTM0ZHLzIwMjAxMjA5L2V1LWNlbnRyYWwtMS9zMy9hd3M0X3JlcXVlc3QifSwKCQl7IngtYW16LXNlY3VyaXR5LXRva2VuIjogIiJ9LAoJCXsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwKCQl7IngtYW16LWRhdGUiOiAiMjAyMDEyMDlUMTY0MTA1WiIgfQoJXQp9Cg== - !!python/tuple - !!python/object/apply:multidict._multidict.MultiDict - - !!python/tuple - name - X-Amz-Signature - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : multipart/form-data - - 98c25c9d14208702c4bee91a57e7d162b81f843119b188f46817b86217233f13 + - ee002907feaafc2140855b38a2f98461bc1fe828c77aa0ffc1f5ae1a5d3985d0 - !!python/tuple - !!python/object/apply:multidict._multidict.MultiDict - - !!python/tuple @@ -123,303 +123,261 @@ interactions: - filename - king_arthur.txt - ? !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type : application/octet-stream - !!binary | - NzI5MDIxNDU1NTI4MzYyMlzWghtnw6/lb3bsxaHn3zxjtWYMe/c09khfaRu09pHy + MzE1NzcwMTk5MjU1ODExOdgTJiVV1Q1ICoLmCSD1E5Rmql+gmXdArv9kM41mZZsE _is_multipart: true + _is_processed: true _quote_fields: true _writer: !!python/object:aiohttp.multipart.MultipartWriter _boundary: !!binary | - YzMzYjk0NDYzZGZiNDFkYzg3OTY5NzUwMzNiNDM0NTc= - _content_type: multipart/form-data; boundary="c33b94463dfb41dc8796975033b43457" + ZjU4NDdkNTdlNjRhNDVlZDg2ZjNhYzQzZGVmMWY2NzI= _encoding: null _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE - - multipart/form-data; boundary="c33b94463dfb41dc8796975033b43457" + - Content-Type + - multipart/form-data; boundary=f5847d57e64a45ed86f3ac43def1f672 _parts: - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="tagging" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '89' _size: 89 _value: !!binary | PFRhZ2dpbmc+PFRhZ1NldD48VGFnPjxLZXk+T2JqZWN0VFRMSW5EYXlzPC9LZXk+PFZhbHVlPjE8 L1ZhbHVlPjwvVGFnPjwvVGFnU2V0PjwvVGFnZ2luZz4= - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9InRhZ2dpbmciDQpDT05URU5ULUxFTkdUSDogODkNCg0K - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="key" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '139' _size: 139 _value: !!binary | c3ViLWMtYzg4MjQyZmEtMTNhZS0xMWViLWJjMzQtY2U2ZmQ5NjdhZjk1LzBNUjEtejJ3MG5TSll4 - d0V5NzRwNVFqVjg1VG1nTkJLUHJWNzF0NTVOVDAvOGMzYTA3MjktYjIwOS00ZDNhLTk2NzQtNWIy - ZTRhNjZmNzZkL2tpbmdfYXJ0aHVyLnR4dA== - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9ImtleSINCkNPTlRFTlQtTEVOR1RIOiAxMzkNCg0K + d0V5NzRwNVFqVjg1VG1nTkJLUHJWNzF0NTVOVDAvZTgxODA4MmQtZjBkYS00MzVmLWJkMTctNzBm + MDgwNzE1MGM0L2tpbmdfYXJ0aHVyLnR4dA== - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="Content-Type" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '25' _size: 25 _value: !!binary | dGV4dC9wbGFpbjsgY2hhcnNldD11dGYtOA== - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9IkNvbnRlbnQtVHlwZSINCkNPTlRFTlQtTEVOR1RIOiAyNQ0KDQo= - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="X-Amz-Credential" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '58' _size: 58 _value: !!binary | - QUtJQVk3QVU2R1FENUtXQlMzRkcvMjAyMDExMjUvZXUtY2VudHJhbC0xL3MzL2F3czRfcmVxdWVz + QUtJQVk3QVU2R1FENUtXQlMzRkcvMjAyMDEyMDkvZXUtY2VudHJhbC0xL3MzL2F3czRfcmVxdWVz dA== - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9IlgtQW16LUNyZWRlbnRpYWwiDQpDT05URU5ULUxFTkdUSDogNTgNCg0K - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="X-Amz-Security-Token" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '0' _size: 0 _value: !!binary "" - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9IlgtQW16LVNlY3VyaXR5LVRva2VuIg0KQ09OVEVOVC1MRU5HVEg6IDAN - Cg0K - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="X-Amz-Algorithm" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '16' _size: 16 _value: !!binary | QVdTNC1ITUFDLVNIQTI1Ng== - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9IlgtQW16LUFsZ29yaXRobSINCkNPTlRFTlQtTEVOR1RIOiAxNg0KDQo= - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="X-Amz-Date" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '16' _size: 16 _value: !!binary | - MjAyMDExMjVUMTM0OTQ1Wg== - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9IlgtQW16LURhdGUiDQpDT05URU5ULUxFTkdUSDogMTYNCg0K + MjAyMDEyMDlUMTY0MTA1Wg== - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="Policy" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '904' _size: 904 _value: !!binary | - Q25zS0NTSmxlSEJwY21GMGFXOXVJam9nSWpJd01qQXRNVEV0TWpWVU1UTTZORGs2TkRWYUlpd0tD + Q25zS0NTSmxlSEJwY21GMGFXOXVJam9nSWpJd01qQXRNVEl0TURsVU1UWTZOREU2TURWYUlpd0tD U0pqYjI1a2FYUnBiMjV6SWpvZ1d3b0pDWHNpWW5WamEyVjBJam9nSW5CMVltNTFZaTF0Ym1WdGIz TjVibVV0Wm1sc1pYTXRaWFV0WTJWdWRISmhiQzB4TFhCeVpDSjlMQW9KQ1ZzaVpYRWlMQ0FpSkhS aFoyZHBibWNpTENBaVBGUmhaMmRwYm1jK1BGUmhaMU5sZEQ0OFZHRm5QanhMWlhrK1QySnFaV04w VkZSTVNXNUVZWGx6UEM5TFpYaytQRlpoYkhWbFBqRThMMVpoYkhWbFBqd3ZWR0ZuUGp3dlZHRm5V MlYwUGp3dlZHRm5aMmx1Wno0aVhTd0tDUWxiSW1WeElpd2dJaVJyWlhraUxDQWljM1ZpTFdNdFl6 ZzRNalF5Wm1FdE1UTmhaUzB4TVdWaUxXSmpNelF0WTJVMlptUTVOamRoWmprMUx6Qk5VakV0ZWpK - M01HNVRTbGw0ZDBWNU56UndOVkZxVmpnMVZHMW5Ua0pMVUhKV056RjBOVFZPVkRBdk9HTXpZVEEz - TWprdFlqSXdPUzAwWkROaExUazJOelF0TldJeVpUUmhOalptTnpaa0wydHBibWRmWVhKMGFIVnlM + M01HNVRTbGw0ZDBWNU56UndOVkZxVmpnMVZHMW5Ua0pMVUhKV056RjBOVFZPVkRBdlpUZ3hPREE0 + TW1RdFpqQmtZUzAwTXpWbUxXSmtNVGN0TnpCbU1EZ3dOekUxTUdNMEwydHBibWRmWVhKMGFIVnlM blI0ZENKZExBb0pDVnNpWTI5dWRHVnVkQzFzWlc1bmRHZ3RjbUZ1WjJVaUxDQXdMQ0ExTWpReU9E Z3dYU3dLQ1FsYkluTjBZWEowY3kxM2FYUm9JaXdnSWlSRGIyNTBaVzUwTFZSNWNHVWlMQ0FpSWww c0Nna0pleUo0TFdGdGVpMWpjbVZrWlc1MGFXRnNJam9nSWtGTFNVRlpOMEZWTmtkUlJEVkxWMEpU - TTBaSEx6SXdNakF4TVRJMUwyVjFMV05sYm5SeVlXd3RNUzl6TXk5aGQzTTBYM0psY1hWbGMzUWlm + TTBaSEx6SXdNakF4TWpBNUwyVjFMV05sYm5SeVlXd3RNUzl6TXk5aGQzTTBYM0psY1hWbGMzUWlm U3dLQ1FsN0luZ3RZVzE2TFhObFkzVnlhWFI1TFhSdmEyVnVJam9nSWlKOUxBb0pDWHNpZUMxaGJY b3RZV3huYjNKcGRHaHRJam9nSWtGWFV6UXRTRTFCUXkxVFNFRXlOVFlpZlN3S0NRbDdJbmd0WVcx - NkxXUmhkR1VpT2lBaU1qQXlNREV4TWpWVU1UTTBPVFExV2lJZ2ZRb0pYUXA5Q2c9PQ== - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9IlBvbGljeSINCkNPTlRFTlQtTEVOR1RIOiA5MDQNCg0K + NkxXUmhkR1VpT2lBaU1qQXlNREV5TURsVU1UWTBNVEExV2lJZ2ZRb0pYUXA5Q2c9PQ== - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.StringPayload - _content_type: multipart/form-data _encoding: utf-8 _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - multipart/form-data - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="X-Amz-Signature" - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '64' _size: 64 _value: !!binary | - OThjMjVjOWQxNDIwODcwMmM0YmVlOTFhNTdlN2QxNjJiODFmODQzMTE5YjE4OGY0NjgxN2I4NjIx - NzIzM2YxMw== - - !!binary | - Q09OVEVOVC1UWVBFOiBtdWx0aXBhcnQvZm9ybS1kYXRhDQpDT05URU5ULURJU1BPU0lUSU9OOiBm - b3JtLWRhdGE7IG5hbWU9IlgtQW16LVNpZ25hdHVyZSINCkNPTlRFTlQtTEVOR1RIOiA2NA0KDQo= + ZWUwMDI5MDdmZWFhZmMyMTQwODU1YjM4YTJmOTg0NjFiYzFmZTgyOGM3N2FhMGZmYzFmNWFlMWE1 + ZDM5ODVkMA== - '' - '' - !!python/tuple - !!python/object:aiohttp.payload.BytesPayload - _content_type: application/octet-stream _encoding: null _filename: null _headers: !!python/object/apply:multidict._multidict.CIMultiDict - - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-TYPE + - Content-Type - application/octet-stream - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-DISPOSITION + - Content-Disposition - form-data; name="file"; filename="king_arthur.txt"; filename*=utf-8''king_arthur.txt - !!python/tuple - !!python/object/new:multidict._multidict.istr - - CONTENT-LENGTH + - Content-Length - '48' _size: 48 _value: !!binary | - NzI5MDIxNDU1NTI4MzYyMlzWghtnw6/lb3bsxaHn3zxjtWYMe/c09khfaRu09pHy - - !!binary | - Q09OVEVOVC1UWVBFOiBhcHBsaWNhdGlvbi9vY3RldC1zdHJlYW0NCkNPTlRFTlQtRElTUE9TSVRJ - T046IGZvcm0tZGF0YTsgbmFtZT0iZmlsZSI7IGZpbGVuYW1lPSJraW5nX2FydGh1ci50eHQiOyBm - aWxlbmFtZSo9dXRmLTgnJ2tpbmdfYXJ0aHVyLnR4dA0KQ09OVEVOVC1MRU5HVEg6IDQ4DQoNCg== + MzE1NzcwMTk5MjU1ODExOdgTJiVV1Q1ICoLmCSD1E5Rmql+gmXdArv9kM41mZZsE - '' - '' _value: null @@ -432,81 +390,126 @@ interactions: body: string: '' headers: - Date: Wed, 25 Nov 2020 13:48:47 GMT - ETag: '"a32d87a8535b697e9fadad662af432ae"' - Location: https://pubnub-mnemosyne-files-eu-central-1-prd.s3.amazonaws.com/sub-c-mock-key%2F0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0%2F8c3a0729-b209-4d3a-9674-5b2e4a66f76d%2Fking_arthur.txt - Server: AmazonS3 - x-amz-expiration: expiry-date="Fri, 27 Nov 2020 00:00:00 GMT", rule-id="Archive - file 1 day after creation" - x-amz-id-2: YjU4oUbEm8ieYKYEG4h0WZE9HMcdtvW92XhafqD5GCsFYWoNDecsivrX+Luvj55JFEJxvoXZgok= - x-amz-request-id: 951D0CAB0EC59F06 - x-amz-server-side-encryption: AES256 + Date: + - Wed, 09 Dec 2020 16:40:07 GMT + Etag: + - '"6e9bb1045cac244dfa218593748ee183"' + Location: + - https://pubnub-mnemosyne-files-eu-central-1-prd.s3.amazonaws.com/sub-c-mock-key%2F0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0%2Fe818082d-f0da-435f-bd17-70f0807150c4%2Fking_arthur.txt + Server: + - AmazonS3 + x-amz-expiration: + - expiry-date="Fri, 11 Dec 2020 00:00:00 GMT", rule-id="Archive file 1 day after + creation" + x-amz-id-2: + - GfB/TSUZRb4Vi87uZrOyBB45GQiWLA9IwWEEhGBa+U77ybMxsBHGYMrD/2YkYRnRSo50oQxqSxw= + x-amz-request-id: + - 3E3A2E6D63F7DE13 + x-amz-server-side-encryption: + - AES256 status: code: 204 message: No Content - url: !!python/object/new:yarl.URL - state: !!python/tuple - - !!python/object/new:urllib.parse.SplitResult - - https - - pubnub-mnemosyne-files-eu-central-1-prd.s3.amazonaws.com - - / - - '' - - '' + url: https://pubnub-mnemosyne-files-eu-central-1-prd.s3.amazonaws.com/ - request: body: null headers: User-Agent: - PubNub-Python-Asyncio/4.7.0 method: GET - uri: https://ps.pndsn.com/v1/files/publish-file/pub-c-mock-key/sub-c-mock-key/0/files_asyncio_ch/0/%22y3LoIxh%2FhzntHbmJXXPQR%2FcsvR1VWNQHJfPt09gQKtLFCKUis6sfMWit1GDAQjCVLfNMMrt44fWKMoDQmeFtg9OaR72c8vyTXmu9MgUHqNqhSPyp5A65AYieu3ym%2BtavxMz%2FQQSvKPHIlj6wT%2Bj3mUZwiEdbJsZPJWyVW4mxVAE%3D%22?meta=null&store=1&ttl=222 + uri: https://ps.pndsn.com/v1/files/publish-file/pub-c-mock-key/sub-c-mock-key/0/files_asyncio_ch/0/%22y3LoIxh%2FhzntHbmJXXPQR%2FcsvR1VWNQHJfPt09gQKtLFCKUis6sfMWit1GDAQjCV8Xb%2FM7nFqDRDsxR61ecxvHUYrgHwDKYjCa2gd7FKSkSx%2BvgykAgMoUnGNKLkydHWJ0QJAtEO3jt4trtUtiUm8IYJSRy04UNOU2IXPyr2yIs%3D%22?meta=null&store=1&ttl=222 response: body: - string: '[1,"Sent","16063121262045303"]' + string: '[1,"Sent","16075320062053898"]' headers: - Access-Control-Allow-Methods: GET - Access-Control-Allow-Origin: '*' - Cache-Control: no-cache - Connection: keep-alive - Content-Length: '30' - Content-Type: text/javascript; charset="UTF-8" - Date: Wed, 25 Nov 2020 13:48:46 GMT + Access-Control-Allow-Methods: + - GET + Access-Control-Allow-Origin: + - '*' + Cache-Control: + - no-cache + Connection: + - keep-alive + Content-Length: + - '30' + Content-Type: + - text/javascript; charset="UTF-8" + Date: + - Wed, 09 Dec 2020 16:40:06 GMT status: code: 200 message: OK - url: !!python/object/new:yarl.URL - state: !!python/tuple - - !!python/object/new:urllib.parse.SplitResult - - https - - ps.pndsn.com - - /v1/files/publish-file/pub-c-mock-key/sub-c-mock-key/0/files_asyncio_ch/0/%22y3LoIxh%2FhzntHbmJXXPQR%2FcsvR1VWNQHJfPt09gQKtLFCKUis6sfMWit1GDAQjCVLfNMMrt44fWKMoDQmeFtg9OaR72c8vyTXmu9MgUHqNqhSPyp5A65AYieu3ym%2BtavxMz%2FQQSvKPHIlj6wT%2Bj3mUZwiEdbJsZPJWyVW4mxVAE%3D%22 - - meta=null&ttl=222&store=1&pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=671a0ccb-d502-49f7-8467-45fe505c7090&l_file=0.23801088333129883 - - '' + url: https://ps.pndsn.com/v1/files/publish-file/pub-c-mock-key/sub-c-mock-key/0/files_asyncio_ch/0/%22y3LoIxh%2FhzntHbmJXXPQR%2FcsvR1VWNQHJfPt09gQKtLFCKUis6sfMWit1GDAQjCV8Xb%2FM7nFqDRDsxR61ecxvHUYrgHwDKYjCa2gd7FKSkSx%2BvgykAgMoUnGNKLkydHWJ0QJAtEO3jt4trtUtiUm8IYJSRy04UNOU2IXPyr2yIs%3D%22?meta=null&ttl=222&store=1&pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=b2ad5a21-4f37-4b44-a514-8b7971c57f08&l_file=0.2024080753326416 - request: body: null headers: User-Agent: - PubNub-Python-Asyncio/4.7.0 method: GET - uri: https://ps.pndsn.com/v1/files/sub-c-mock-key/channels/files_asyncio_ch/files/8c3a0729-b209-4d3a-9674-5b2e4a66f76d/king_arthur.txt + uri: https://ps.pndsn.com/v1/files/sub-c-mock-key/channels/files_asyncio_ch/files/e818082d-f0da-435f-bd17-70f0807150c4/king_arthur.txt response: body: string: '' headers: - Access-Control-Allow-Origin: '*' - Cache-Control: public, max-age=914, immutable - Connection: keep-alive - Content-Length: '0' - Date: Wed, 25 Nov 2020 13:48:46 GMT - Location: https://files-eu-central-1.pndsn.com/sub-c-mock-key/0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0/8c3a0729-b209-4d3a-9674-5b2e4a66f76d/king_arthur.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAY7AU6GQD5KWBS3FG%2F20201125%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Date=20201125T130000Z&X-Amz-Expires=3900&X-Amz-SignedHeaders=host&X-Amz-Signature=2c7df2bcb50409be0346f2ce35a58248bab7131265ed3debc16800ff647298c8 + Access-Control-Allow-Origin: + - '*' + Cache-Control: + - public, max-age=1434, immutable + Connection: + - keep-alive + Content-Length: + - '0' + Date: + - Wed, 09 Dec 2020 16:40:06 GMT + Location: + - https://files-eu-central-1.pndsn.com/sub-c-mock-key/0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0/e818082d-f0da-435f-bd17-70f0807150c4/king_arthur.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAY7AU6GQD5KWBS3FG%2F20201209%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Date=20201209T160000Z&X-Amz-Expires=3900&X-Amz-SignedHeaders=host&X-Amz-Signature=6d7034a4f0b199a62d2c11fb1ba3872bdb438b7adc2bc259b8e92b9668a9cceb status: code: 307 message: Temporary Redirect - url: !!python/object/new:yarl.URL - state: !!python/tuple - - !!python/object/new:urllib.parse.SplitResult - - https - - ps.pndsn.com - - /v1/files/sub-c-mock-key/channels/files_asyncio_ch/files/8c3a0729-b209-4d3a-9674-5b2e4a66f76d/king_arthur.txt - - pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=671a0ccb-d502-49f7-8467-45fe505c7090&l_file=0.17087499300638834 - - '' + url: https://ps.pndsn.com/v1/files/sub-c-mock-key/channels/files_asyncio_ch/files/e818082d-f0da-435f-bd17-70f0807150c4/king_arthur.txt?pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=b2ad5a21-4f37-4b44-a514-8b7971c57f08&l_file=0.14757903416951498 +- request: + body: null + headers: + User-Agent: + - PubNub-Python-Asyncio/4.7.0 + method: GET + uri: https://files-eu-central-1.pndsn.com/sub-c-mock-key/0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0/e818082d-f0da-435f-bd17-70f0807150c4/king_arthur.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAY7AU6GQD5KWBS3FG%2F20201209%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Date=20201209T160000Z&X-Amz-Expires=3900&X-Amz-Signature=6d7034a4f0b199a62d2c11fb1ba3872bdb438b7adc2bc259b8e92b9668a9cceb&X-Amz-SignedHeaders=host + response: + body: + string: !!binary | + MzE1NzcwMTk5MjU1ODExOdgTJiVV1Q1ICoLmCSD1E5Rmql+gmXdArv9kM41mZZsE + headers: + Accept-Ranges: + - bytes + Connection: + - keep-alive + Content-Length: + - '48' + Content-Type: + - text/plain; charset=utf-8 + Date: + - Wed, 09 Dec 2020 16:40:07 GMT + Etag: + - '"6e9bb1045cac244dfa218593748ee183"' + Last-Modified: + - Wed, 09 Dec 2020 16:40:07 GMT + Server: + - AmazonS3 + Via: + - 1.1 e28c193c96684df9ba36cf3fd8976708.cloudfront.net (CloudFront) + X-Amz-Cf-Id: + - tVhyL_C8dUjkfNT0nWjRxZfya1e2zXID0l3oYlqRRaCj5CBeWVLacg== + X-Amz-Cf-Pop: + - AMS54-C1 + X-Cache: + - Miss from cloudfront + x-amz-expiration: + - expiry-date="Fri, 11 Dec 2020 00:00:00 GMT", rule-id="Archive file 1 day after + creation" + x-amz-server-side-encryption: + - AES256 + status: + code: 200 + message: OK + url: https://files-eu-central-1.pndsn.com/sub-c-mock-key/0MR1-z2w0nSJYxwEy74p5QjV85TmgNBKPrV71t55NT0/e818082d-f0da-435f-bd17-70f0807150c4/king_arthur.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAY7AU6GQD5KWBS3FG%2F20201209%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Date=20201209T160000Z&X-Amz-Expires=3900&X-Amz-SignedHeaders=host&X-Amz-Signature=6d7034a4f0b199a62d2c11fb1ba3872bdb438b7adc2bc259b8e92b9668a9cceb version: 1 diff --git a/tests/integrational/fixtures/asyncio/subscription/unsubscribe_all.yaml b/tests/integrational/fixtures/asyncio/subscription/unsubscribe_all.yaml index 9bcebd25..2bf51469 100644 --- a/tests/integrational/fixtures/asyncio/subscription/unsubscribe_all.yaml +++ b/tests/integrational/fixtures/asyncio/subscription/unsubscribe_all.yaml @@ -2,89 +2,209 @@ interactions: - request: body: null headers: - USER-AGENT: [PubNub-Python-Asyncio/4.0.4] + User-Agent: + - PubNub-Python-Asyncio/4.7.0 method: GET uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr1?add=test-subscribe-asyncio-unsubscribe-all-ch&uuid=test-subscribe-asyncio-messenger response: - body: {string: '{"status": 200, "message": "OK", "service": "channel-registry", - "error": false}'} - headers: {ACCEPT-RANGES: bytes, ACCESS-CONTROL-ALLOW-METHODS: GET, ACCESS-CONTROL-ALLOW-ORIGIN: '*', - AGE: '0', CACHE-CONTROL: no-cache, CONNECTION: keep-alive, CONTENT-LENGTH: '79', - CONTENT-TYPE: text/javascript; charset="UTF-8", DATE: 'Fri, 16 Dec 2016 13:52:48 - GMT', SERVER: Pubnub} - status: {code: 200, message: OK} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr1?add=test-subscribe-asyncio-unsubscribe-all-ch&pnsdk=PubNub-Python-Asyncio%2F4.0.4&uuid=test-subscribe-asyncio-messenger + body: + string: '{"status": 200, "message": "OK", "service": "channel-registry", "error": + false}' + headers: + Accept-Ranges: + - bytes + Access-Control-Allow-Methods: + - GET, POST, DELETE, OPTIONS + Access-Control-Allow-Origin: + - '*' + Age: + - '0' + Cache-Control: + - no-cache + Connection: + - keep-alive + Content-Length: + - '79' + Content-Type: + - text/javascript; charset="UTF-8" + Date: + - Mon, 14 Dec 2020 15:30:51 GMT + Server: + - Pubnub + status: + code: 200 + message: OK + url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr1?add=test-subscribe-asyncio-unsubscribe-all-ch&pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=test-subscribe-asyncio-messenger - request: body: null headers: - USER-AGENT: [PubNub-Python-Asyncio/4.0.4] + User-Agent: + - PubNub-Python-Asyncio/4.7.0 method: GET uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr2?add=test-subscribe-asyncio-unsubscribe-all-ch&uuid=test-subscribe-asyncio-messenger response: - body: {string: '{"status": 200, "message": "OK", "service": "channel-registry", - "error": false}'} - headers: {ACCEPT-RANGES: bytes, ACCESS-CONTROL-ALLOW-METHODS: GET, ACCESS-CONTROL-ALLOW-ORIGIN: '*', - AGE: '0', CACHE-CONTROL: no-cache, CONNECTION: keep-alive, CONTENT-LENGTH: '79', - CONTENT-TYPE: text/javascript; charset="UTF-8", DATE: 'Fri, 16 Dec 2016 13:52:48 - GMT', SERVER: Pubnub} - status: {code: 200, message: OK} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr2?add=test-subscribe-asyncio-unsubscribe-all-ch&pnsdk=PubNub-Python-Asyncio%2F4.0.4&uuid=test-subscribe-asyncio-messenger + body: + string: '{"status": 200, "message": "OK", "service": "channel-registry", "error": + false}' + headers: + Accept-Ranges: + - bytes + Access-Control-Allow-Methods: + - GET, POST, DELETE, OPTIONS + Access-Control-Allow-Origin: + - '*' + Age: + - '0' + Cache-Control: + - no-cache + Connection: + - keep-alive + Content-Length: + - '79' + Content-Type: + - text/javascript; charset="UTF-8" + Date: + - Mon, 14 Dec 2020 15:30:51 GMT + Server: + - Pubnub + status: + code: 200 + message: OK + url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr2?add=test-subscribe-asyncio-unsubscribe-all-ch&pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=test-subscribe-asyncio-messenger&l_cg=0.17911815643310547 - request: body: null headers: - USER-AGENT: [PubNub-Python-Asyncio/4.0.4] + User-Agent: + - PubNub-Python-Asyncio/4.7.0 method: GET - uri: https://ps.pndsn.com/v2/subscribe/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/test-subscribe-asyncio-unsubscribe-all-ch3,test-subscribe-asyncio-unsubscribe-all-ch1,test-subscribe-asyncio-unsubscribe-all-ch2/0?channel-group=test-subscribe-asyncio-unsubscribe-all-gr2%2Ctest-subscribe-asyncio-unsubscribe-all-gr1&tt=0&uuid=test-subscribe-asyncio-messenger + uri: https://ps.pndsn.com/v2/subscribe/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/test-subscribe-asyncio-unsubscribe-all-ch1,test-subscribe-asyncio-unsubscribe-all-ch2,test-subscribe-asyncio-unsubscribe-all-ch3/0?channel-group=test-subscribe-asyncio-unsubscribe-all-gr1%2Ctest-subscribe-asyncio-unsubscribe-all-gr2&tt=0&uuid=test-subscribe-asyncio-messenger response: - body: {string: '{"t":{"t":"14818963699240141","r":12},"m":[]}'} - headers: {ACCESS-CONTROL-ALLOW-METHODS: GET, ACCESS-CONTROL-ALLOW-ORIGIN: '*', - CACHE-CONTROL: no-cache, CONNECTION: keep-alive, CONTENT-LENGTH: '45', CONTENT-TYPE: text/javascript; - charset="UTF-8", DATE: 'Fri, 16 Dec 2016 13:52:50 GMT'} - status: {code: 200, message: OK} - url: https://ps.pndsn.com/v2/subscribe/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/test-subscribe-asyncio-unsubscribe-all-ch3,test-subscribe-asyncio-unsubscribe-all-ch1,test-subscribe-asyncio-unsubscribe-all-ch2/0?pnsdk=PubNub-Python-Asyncio%2F4.0.4&tt=0&uuid=test-subscribe-asyncio-messenger&channel-group=test-subscribe-asyncio-unsubscribe-all-gr2,test-subscribe-asyncio-unsubscribe-all-gr1 + body: + string: '{"t":{"t":"16079598526833689","r":12},"m":[]}' + headers: + Access-Control-Allow-Methods: + - GET + Access-Control-Allow-Origin: + - '*' + Cache-Control: + - no-cache + Connection: + - keep-alive + Content-Length: + - '45' + Content-Type: + - text/javascript; charset="UTF-8" + Date: + - Mon, 14 Dec 2020 15:30:52 GMT + status: + code: 200 + message: OK + url: https://ps.pndsn.com/v2/subscribe/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/test-subscribe-asyncio-unsubscribe-all-ch1,test-subscribe-asyncio-unsubscribe-all-ch2,test-subscribe-asyncio-unsubscribe-all-ch3/0?channel-group=test-subscribe-asyncio-unsubscribe-all-gr1,test-subscribe-asyncio-unsubscribe-all-gr2&tt=0&pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=test-subscribe-asyncio-messenger&l_cg=0.11011052131652832 - request: body: null headers: - USER-AGENT: [PubNub-Python-Asyncio/4.0.4] + User-Agent: + - PubNub-Python-Asyncio/4.7.0 method: GET - uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/test-subscribe-asyncio-unsubscribe-all-ch3,test-subscribe-asyncio-unsubscribe-all-ch1,test-subscribe-asyncio-unsubscribe-all-ch2/leave?channel-group=test-subscribe-asyncio-unsubscribe-all-gr2%2Ctest-subscribe-asyncio-unsubscribe-all-gr1&uuid=test-subscribe-asyncio-messenger + uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/test-subscribe-asyncio-unsubscribe-all-ch1,test-subscribe-asyncio-unsubscribe-all-ch2,test-subscribe-asyncio-unsubscribe-all-ch3/leave?channel-group=test-subscribe-asyncio-unsubscribe-all-gr1%2Ctest-subscribe-asyncio-unsubscribe-all-gr2&uuid=test-subscribe-asyncio-messenger response: - body: {string: '{"status": 200, "action": "leave", "message": "OK", "service": - "Presence"}'} - headers: {ACCEPT-RANGES: bytes, ACCESS-CONTROL-ALLOW-METHODS: 'OPTIONS, GET, POST', - ACCESS-CONTROL-ALLOW-ORIGIN: '*', AGE: '0', CACHE-CONTROL: no-cache, CONNECTION: keep-alive, - CONTENT-LENGTH: '74', CONTENT-TYPE: text/javascript; charset="UTF-8", DATE: 'Fri, - 16 Dec 2016 13:52:50 GMT', SERVER: Pubnub Presence} - status: {code: 200, message: OK} - url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/test-subscribe-asyncio-unsubscribe-all-ch3,test-subscribe-asyncio-unsubscribe-all-ch1,test-subscribe-asyncio-unsubscribe-all-ch2/leave?pnsdk=PubNub-Python-Asyncio%2F4.0.4&uuid=test-subscribe-asyncio-messenger&channel-group=test-subscribe-asyncio-unsubscribe-all-gr2,test-subscribe-asyncio-unsubscribe-all-gr1 + body: + string: '{"status": 200, "message": "OK", "action": "leave", "service": "Presence"}' + headers: + Accept-Ranges: + - bytes + Access-Control-Allow-Methods: + - OPTIONS, GET, POST + Access-Control-Allow-Origin: + - '*' + Age: + - '0' + Cache-Control: + - no-cache + Connection: + - keep-alive + Content-Length: + - '74' + Content-Type: + - text/javascript; charset="UTF-8" + Date: + - Mon, 14 Dec 2020 15:30:53 GMT + Server: + - Pubnub Presence + status: + code: 200 + message: OK + url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/test-subscribe-asyncio-unsubscribe-all-ch1,test-subscribe-asyncio-unsubscribe-all-ch2,test-subscribe-asyncio-unsubscribe-all-ch3/leave?channel-group=test-subscribe-asyncio-unsubscribe-all-gr1,test-subscribe-asyncio-unsubscribe-all-gr2&pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=test-subscribe-asyncio-messenger&l_cg=0.11011052131652832 - request: body: null headers: - USER-AGENT: [PubNub-Python-Asyncio/4.0.4] + User-Agent: + - PubNub-Python-Asyncio/4.7.0 method: GET uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr1?remove=test-subscribe-asyncio-unsubscribe-all-ch&uuid=test-subscribe-asyncio-messenger response: - body: {string: '{"status": 200, "message": "OK", "service": "channel-registry", - "error": false}'} - headers: {ACCEPT-RANGES: bytes, ACCESS-CONTROL-ALLOW-METHODS: GET, ACCESS-CONTROL-ALLOW-ORIGIN: '*', - AGE: '0', CACHE-CONTROL: no-cache, CONNECTION: keep-alive, CONTENT-LENGTH: '79', - CONTENT-TYPE: text/javascript; charset="UTF-8", DATE: 'Fri, 16 Dec 2016 13:52:50 - GMT', SERVER: Pubnub} - status: {code: 200, message: OK} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr1?remove=test-subscribe-asyncio-unsubscribe-all-ch&pnsdk=PubNub-Python-Asyncio%2F4.0.4&uuid=test-subscribe-asyncio-messenger + body: + string: '{"status": 200, "message": "OK", "service": "channel-registry", "error": + false}' + headers: + Accept-Ranges: + - bytes + Access-Control-Allow-Methods: + - GET, POST, DELETE, OPTIONS + Access-Control-Allow-Origin: + - '*' + Age: + - '0' + Cache-Control: + - no-cache + Connection: + - keep-alive + Content-Length: + - '79' + Content-Type: + - text/javascript; charset="UTF-8" + Date: + - Mon, 14 Dec 2020 15:30:53 GMT + Server: + - Pubnub + status: + code: 200 + message: OK + url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr1?remove=test-subscribe-asyncio-unsubscribe-all-ch&pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=test-subscribe-asyncio-messenger&l_cg=0.11011052131652832&l_pres=0.5682003498077393 - request: body: null headers: - USER-AGENT: [PubNub-Python-Asyncio/4.0.4] + User-Agent: + - PubNub-Python-Asyncio/4.7.0 method: GET uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr2?remove=test-subscribe-asyncio-unsubscribe-all-ch&uuid=test-subscribe-asyncio-messenger response: - body: {string: '{"status": 200, "message": "OK", "service": "channel-registry", - "error": false}'} - headers: {ACCEPT-RANGES: bytes, ACCESS-CONTROL-ALLOW-METHODS: GET, ACCESS-CONTROL-ALLOW-ORIGIN: '*', - AGE: '0', CACHE-CONTROL: no-cache, CONNECTION: keep-alive, CONTENT-LENGTH: '79', - CONTENT-TYPE: text/javascript; charset="UTF-8", DATE: 'Fri, 16 Dec 2016 13:52:50 - GMT', SERVER: Pubnub} - status: {code: 200, message: OK} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr2?remove=test-subscribe-asyncio-unsubscribe-all-ch&pnsdk=PubNub-Python-Asyncio%2F4.0.4&uuid=test-subscribe-asyncio-messenger + body: + string: '{"status": 200, "message": "OK", "service": "channel-registry", "error": + false}' + headers: + Accept-Ranges: + - bytes + Access-Control-Allow-Methods: + - GET, POST, DELETE, OPTIONS + Access-Control-Allow-Origin: + - '*' + Age: + - '0' + Cache-Control: + - no-cache + Connection: + - keep-alive + Content-Length: + - '79' + Content-Type: + - text/javascript; charset="UTF-8" + Date: + - Mon, 14 Dec 2020 15:30:53 GMT + Server: + - Pubnub + status: + code: 200 + message: OK + url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/test-subscribe-asyncio-unsubscribe-all-gr2?remove=test-subscribe-asyncio-unsubscribe-all-ch&pnsdk=PubNub-Python-Asyncio%2F4.7.0&uuid=test-subscribe-asyncio-messenger&l_cg=0.08846743901570638&l_pres=0.5682003498077393 version: 1 diff --git a/tests/integrational/fixtures/twisted/groups/add_channels.yaml b/tests/integrational/fixtures/twisted/groups/add_channels.yaml deleted file mode 100644 index 29379d1c..00000000 --- a/tests/integrational/fixtures/twisted/groups/add_channels.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?add=cgttc0%2Ccgttc1&pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "service": "channel-registry", - "error": false}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?add=cgttc0,cgttc1&pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=a88dfb31-755d-4db4-844e-0b56b0699f92 -version: 1 diff --git a/tests/integrational/fixtures/twisted/groups/add_single_channel.yaml b/tests/integrational/fixtures/twisted/groups/add_single_channel.yaml deleted file mode 100644 index 95741b6c..00000000 --- a/tests/integrational/fixtures/twisted/groups/add_single_channel.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?add=cgttc&pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "service": "channel-registry", - "error": false}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?add=cgttc&pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=a88dfb31-755d-4db4-844e-0b56b0699f92 -version: 1 diff --git a/tests/integrational/fixtures/twisted/groups/list_channels.yaml b/tests/integrational/fixtures/twisted/groups/list_channels.yaml deleted file mode 100644 index 92083a07..00000000 --- a/tests/integrational/fixtures/twisted/groups/list_channels.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '{"status": 200, "payload": {"channels": ["cgttc0", - "cgttc1"], "group": "cgttg"}, "service": "channel-registry", "error": false}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=4b7a6c42-966f-41ad-a395-c9e9ef5919ec -version: 1 diff --git a/tests/integrational/fixtures/twisted/groups/remove_channels.yaml b/tests/integrational/fixtures/twisted/groups/remove_channels.yaml deleted file mode 100644 index 8a458fa7..00000000 --- a/tests/integrational/fixtures/twisted/groups/remove_channels.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?pnsdk=PubNub-Python-Twisted%2F4.0.4&remove=cgttc0%2Ccgttc1 - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "service": "channel-registry", - "error": false}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=a88dfb31-755d-4db4-844e-0b56b0699f92&remove=cgttc0,cgttc1 -version: 1 diff --git a/tests/integrational/fixtures/twisted/groups/remove_single_channel.yaml b/tests/integrational/fixtures/twisted/groups/remove_single_channel.yaml deleted file mode 100644 index e0de69b1..00000000 --- a/tests/integrational/fixtures/twisted/groups/remove_single_channel.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?pnsdk=PubNub-Python-Twisted%2F4.0.4&remove=cgttc - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "service": "channel-registry", - "error": false}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v1/channel-registration/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel-group/cgttg?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=a88dfb31-755d-4db4-844e-0b56b0699f92&remove=cgttc -version: 1 diff --git a/tests/integrational/fixtures/twisted/here_now/global.yaml b/tests/integrational/fixtures/twisted/here_now/global.yaml deleted file mode 100644 index 692af211..00000000 --- a/tests/integrational/fixtures/twisted/here_now/global.yaml +++ /dev/null @@ -1,18 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "payload": {"channels": - {"twisted-test-1": {"uuids": ["00de2586-7ad8-4955-b5f6-87cae3215d02"], "occupancy": - 1}, "twisted-test": {"uuids": ["00de2586-7ad8-4955-b5f6-87cae3215d02"], "occupancy": - 1}}, "total_channels": 2, "total_occupancy": 2}, "service": "Presence"}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=9c7b940a-e5c7-42d5-af9b-c6ddcf58bdc9 -version: 1 diff --git a/tests/integrational/fixtures/twisted/here_now/multiple.yaml b/tests/integrational/fixtures/twisted/here_now/multiple.yaml deleted file mode 100644 index a56d07a8..00000000 --- a/tests/integrational/fixtures/twisted/here_now/multiple.yaml +++ /dev/null @@ -1,17 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/twisted-test-1,twisted-test-1?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "payload": {"channels": - {"twisted-test-1": {"uuids": ["00de2586-7ad8-4955-b5f6-87cae3215d02"], "occupancy": - 1}}, "total_channels": 1, "total_occupancy": 1}, "service": "Presence"}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/twisted-test-1,twisted-test-1?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=9c7b940a-e5c7-42d5-af9b-c6ddcf58bdc9 -version: 1 diff --git a/tests/integrational/fixtures/twisted/here_now/single.yaml b/tests/integrational/fixtures/twisted/here_now/single.yaml deleted file mode 100644 index be7cbbb3..00000000 --- a/tests/integrational/fixtures/twisted/here_now/single.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/twisted-test?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "service": "Presence", - "uuids": ["00de2586-7ad8-4955-b5f6-87cae3215d02"], "occupancy": 1}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/twisted-test?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=9c7b940a-e5c7-42d5-af9b-c6ddcf58bdc9 -version: 1 diff --git a/tests/integrational/fixtures/twisted/publish/do_not_store.yaml b/tests/integrational/fixtures/twisted/publish/do_not_store.yaml deleted file mode 100644 index 4a66ace1..00000000 --- a/tests/integrational/fixtures/twisted/publish/do_not_store.yaml +++ /dev/null @@ -1,15 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22whatever%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&store=0 - response: - body: {string: !!python/unicode '[1,"Sent","14768809388217046"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22whatever%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=359b199b-9f4f-4368-bbc8-33e09b28a280&store=0&seqn=1 -version: 1 diff --git a/tests/integrational/fixtures/twisted/publish/forbidden.yaml b/tests/integrational/fixtures/twisted/publish/forbidden.yaml deleted file mode 100644 index ccbba9c9..00000000 --- a/tests/integrational/fixtures/twisted/publish/forbidden.yaml +++ /dev/null @@ -1,18 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-98863562-19a6-4760-bf0b-d537d1f5c582/sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f/0/not_permitted_channel/0/%22hey%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&signature=oZNiMOxZ6Zg-pAnPpdrQ7rLM2n4Vmk_p8wewWF51wng%3D×tamp=1477397184 - response: - body: {string: '{"message":"Forbidden","payload":{"channels":["not_permitted_channel"]},"error":true,"service":"Access - Manager","status":403} - -'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 403, message: ''} - url: https://ps.pndsn.com/publish/pub-c-98863562-19a6-4760-bf0b-d537d1f5c582/sub-c-7ba2ac4c-4836-11e6-85a4-0619f8945a4f/0/not_permitted_channel/0/%22hey%22?timestamp=1477397184&pnsdk=PubNub-Python-Twisted%2F4.0.4&signature=oZNiMOxZ6Zg-pAnPpdrQ7rLM2n4Vmk_p8wewWF51wng=&seqn=1&uuid=c7accbb8-2606-41bb-9484-7cea7e13817e -version: 1 diff --git a/tests/integrational/fixtures/twisted/publish/invalid_key.yaml b/tests/integrational/fixtures/twisted/publish/invalid_key.yaml deleted file mode 100644 index 05830059..00000000 --- a/tests/integrational/fixtures/twisted/publish/invalid_key.yaml +++ /dev/null @@ -1,15 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/fake/demo/0/twisted-test/0/%22hey%22?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[0,"Invalid Key","14767989321048626"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 400, message: ''} - url: https://ps.pndsn.com/publish/fake/demo/0/twisted-test/0/%22hey%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=7b9b30d1-27b5-4764-bbee-60c7c584b04d&seqn=1 -version: 1 diff --git a/tests/integrational/fixtures/twisted/publish/meta_object.yaml b/tests/integrational/fixtures/twisted/publish/meta_object.yaml deleted file mode 100644 index 7c700b1f..00000000 --- a/tests/integrational/fixtures/twisted/publish/meta_object.yaml +++ /dev/null @@ -1,15 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22hi%22?meta=%7B%22a%22%3A+2%2C+%22b%22%3A+true%7D&pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14768802793338041"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22hi%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&meta=%7B%22a%22%3A%202%2C%20%22b%22%3A%20true%7D&uuid=b299acc9-2b04-46ff-aab2-945c0c7f0678&seqn=1 -version: 1 diff --git a/tests/integrational/fixtures/twisted/publish/mixed_encrypted_via_get.yaml b/tests/integrational/fixtures/twisted/publish/mixed_encrypted_via_get.yaml deleted file mode 100644 index 49ff9abd..00000000 --- a/tests/integrational/fixtures/twisted/publish/mixed_encrypted_via_get.yaml +++ /dev/null @@ -1,54 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22Dt7qBesIhJT2DweUJc2HRQ%3D%3D%22?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14768059311032132"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22Dt7qBesIhJT2DweUJc2HRQ%3D%3D%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=16bfed08-6b5a-4d83-ac10-a37b800d5f3a&seqn=1 -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22Vx8Hk6iVjiV%2BQae1bfMq2w%3D%3D%22?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14768059313886330"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22Vx8Hk6iVjiV%2BQae1bfMq2w%3D%3D%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=00072bd8-45b7-42ac-9f54-f238c4af89b4&seqn=1 -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22jw%2FKAwQAoKtQfHyYrROqSQ%3D%3D%22?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14768059316467095"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22jw%2FKAwQAoKtQfHyYrROqSQ%3D%3D%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=192154f7-3211-4677-8d8a-92b8bf25aff4&seqn=1 -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%226uNMePrQmuhzydmUEs6KAl8teZTZfCbG27ApFSKyfr8%3D%22?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14768059389216173"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%226uNMePrQmuhzydmUEs6KAl8teZTZfCbG27ApFSKyfr8%3D%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=014b69e9-2481-47cb-8239-a8cc56b24502&seqn=1 -version: 1 diff --git a/tests/integrational/fixtures/twisted/publish/mixed_via_get.yaml b/tests/integrational/fixtures/twisted/publish/mixed_via_get.yaml deleted file mode 100644 index 04f03e81..00000000 --- a/tests/integrational/fixtures/twisted/publish/mixed_via_get.yaml +++ /dev/null @@ -1,54 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22hi%22?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14767908153114904"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%22hi%22?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=1ae81865-e92f-4c23-8e21-684a7bcdbe8a&seqn=1 -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/5?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14767908155795869"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/5?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=1ae81865-e92f-4c23-8e21-684a7bcdbe8a&seqn=2 -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/true?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14767908158387685"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/true?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=1ae81865-e92f-4c23-8e21-684a7bcdbe8a&seqn=3 -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%5B%22hi%22%2C%20%22hi2%22%2C%20%22hi3%22%5D?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14767908161061457"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%5B%22hi%22%2C%20%22hi2%22%2C%20%22hi3%22%5D?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=1ae81865-e92f-4c23-8e21-684a7bcdbe8a&seqn=4 -version: 1 diff --git a/tests/integrational/fixtures/twisted/publish/object_via_get.yaml b/tests/integrational/fixtures/twisted/publish/object_via_get.yaml deleted file mode 100644 index a3f311d8..00000000 --- a/tests/integrational/fixtures/twisted/publish/object_via_get.yaml +++ /dev/null @@ -1,15 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%7B%22three%22%3A%20true%2C%20%22one%22%3A%202%7D?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '[1,"Sent","14767908163698950"]'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/publish/pub-c-739aa0fc-3ed5-472b-af26-aca1b333ec52/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/0/twisted-test/0/%7B%22three%22%3A%20true%2C%20%22one%22%3A%202%7D?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=1ae81865-e92f-4c23-8e21-684a7bcdbe8a&seqn=1 -version: 1 diff --git a/tests/integrational/fixtures/twisted/state/multiple_channels.yaml b/tests/integrational/fixtures/twisted/state/multiple_channels.yaml deleted file mode 100644 index d7b6d48a..00000000 --- a/tests/integrational/fixtures/twisted/state/multiple_channels.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/twisted-test-0,twisted-test-1/uuid/someuuid/data?pnsdk=PubNub-Python-Twisted%2F4.0.4&state=%7B%22whatever%22%3A+%22something%22%7D - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "payload": {"whatever": - "something"}, "service": "Presence"}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/twisted-test-0,twisted-test-1/uuid/someuuid/data?state=%7B%22whatever%22%3A%20%22something%22%7D&pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=someuuid -version: 1 diff --git a/tests/integrational/fixtures/twisted/state/single_channel.yaml b/tests/integrational/fixtures/twisted/state/single_channel.yaml deleted file mode 100644 index 8fec25d9..00000000 --- a/tests/integrational/fixtures/twisted/state/single_channel.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/twisted-test/uuid/someuuid/data?pnsdk=PubNub-Python-Twisted%2F4.0.4&state=%7B%22whatever%22%3A+%22something%22%7D - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "payload": {"whatever": - "something"}, "service": "Presence"}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/channel/twisted-test/uuid/someuuid/data?state=%7B%22whatever%22%3A%20%22something%22%7D&pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=someuuid -version: 1 diff --git a/tests/integrational/fixtures/twisted/where_now/multiple.yaml b/tests/integrational/fixtures/twisted/where_now/multiple.yaml deleted file mode 100644 index 67094d2b..00000000 --- a/tests/integrational/fixtures/twisted/where_now/multiple.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/uuid/00de2586-7ad8-4955-b5f6-87cae3215d02?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "payload": {"channels": - ["twisted-test-2", "twisted-test-1"]}, "service": "Presence"}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/uuid/00de2586-7ad8-4955-b5f6-87cae3215d02?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=d8f596f2-dc2c-4015-af8a-73374f770590 -version: 1 diff --git a/tests/integrational/fixtures/twisted/where_now/single.yaml b/tests/integrational/fixtures/twisted/where_now/single.yaml deleted file mode 100644 index ec66eb40..00000000 --- a/tests/integrational/fixtures/twisted/where_now/single.yaml +++ /dev/null @@ -1,16 +0,0 @@ -interactions: -- request: - body: !!python/unicode - headers: - user-agent: [PubNub-Python-Twisted/4.0.4] - method: GET - uri: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/uuid/00de2586-7ad8-4955-b5f6-87cae3215d02?pnsdk=PubNub-Python-Twisted%2F4.0.4 - response: - body: {string: !!python/unicode '{"status": 200, "message": "OK", "payload": {"channels": - ["twisted-test-1"]}, "service": "Presence"}'} - headers: !!python/object:twisted.web.http_headers.Headers - _rawHeaders: - user-agent: [PubNub-Python-Twisted/4.0.4] - status: {code: 200, message: ''} - url: https://ps.pndsn.com/v2/presence/sub-key/sub-c-33f55052-190b-11e6-bfbc-02ee2ddab7fe/uuid/00de2586-7ad8-4955-b5f6-87cae3215d02?pnsdk=PubNub-Python-Twisted%2F4.0.4&uuid=16de4bd1-c7a2-4913-9617-5ea0f624be4f -version: 1 diff --git a/tests/integrational/native_sync/test_file_upload.py b/tests/integrational/native_sync/test_file_upload.py index 315e1d4f..bdcc3c8e 100644 --- a/tests/integrational/native_sync/test_file_upload.py +++ b/tests/integrational/native_sync/test_file_upload.py @@ -1,4 +1,3 @@ -import sys import pytest from pubnub.exceptions import PubNubException @@ -12,11 +11,6 @@ PNPublishFileMessageResult ) -if sys.version_info > (3, 0): - py_v = 3 -else: - py_v = 2 - CHANNEL = "files_native_sync_ch" pubnub = PubNub(pnconf_file_copy()) @@ -75,11 +69,7 @@ def test_send_and_download_file_using_bytes_object(file_for_upload, file_upload_ assert isinstance(download_envelope.result, PNDownloadFileResult) data = download_envelope.result.data - - if py_v == 3: - assert data == bytes(file_upload_test_data["FILE_CONTENT"], "utf-8") - else: - assert data == file_upload_test_data["FILE_CONTENT"] + assert data == bytes(file_upload_test_data["FILE_CONTENT"], "utf-8") @pn_vcr.use_cassette( @@ -98,11 +88,7 @@ def test_send_and_download_encrypted_file(file_for_upload, file_upload_test_data assert isinstance(download_envelope.result, PNDownloadFileResult) data = download_envelope.result.data - - if py_v == 3: - assert data == bytes(file_upload_test_data["FILE_CONTENT"], "utf-8") - else: - assert data == file_upload_test_data["FILE_CONTENT"] + assert data == bytes(file_upload_test_data["FILE_CONTENT"], "utf-8") @pn_vcr_with_empty_body_request.use_cassette( diff --git a/tests/integrational/python_v35/__init__.py b/tests/integrational/python_v35/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/integrational/python_v35/test_asyncio_async_await_syntax.py b/tests/integrational/python_v35/test_asyncio_async_await_syntax.py deleted file mode 100644 index 7c5481d1..00000000 --- a/tests/integrational/python_v35/test_asyncio_async_await_syntax.py +++ /dev/null @@ -1,50 +0,0 @@ -import asyncio -import logging -import pytest # noqa: F401 -import pubnub as pn - -from pubnub.models.consumer.pubsub import PNMessageResult -from pubnub.pubnub_asyncio import PubNubAsyncio, AsyncioEnvelope, SubscribeListener -from tests import helper -from tests.helper import pnconf_sub_copy - -pn.set_stream_logger('pubnub', logging.DEBUG) - - -@pytest.mark.asyncio -async def test_subscribe_publish_unsubscribe(event_loop): - pubnub = PubNubAsyncio(pnconf_sub_copy(), custom_event_loop=event_loop) - - callback = SubscribeListener() - channel = helper.gen_channel("test-sub-pub-unsub") - message = "hey" - pubnub.add_listener(callback) - pubnub.subscribe().channels(channel).execute() - - await callback.wait_for_connect() - - publish_future = asyncio.ensure_future(pubnub.publish().channel(channel).message(message).future()) - subscribe_message_future = asyncio.ensure_future(callback.wait_for_message_on(channel)) - - await asyncio.wait([ - publish_future, - subscribe_message_future - ]) - - publish_envelope = publish_future.result() - subscribe_envelope = subscribe_message_future.result() - - assert isinstance(subscribe_envelope, PNMessageResult) - assert subscribe_envelope.channel == channel - assert subscribe_envelope.subscription is None - assert subscribe_envelope.message == message - assert subscribe_envelope.timetoken > 0 - - assert isinstance(publish_envelope, AsyncioEnvelope) - assert publish_envelope.result.timetoken > 0 - assert publish_envelope.status.original_response[0] == 1 - - pubnub.unsubscribe().channels(channel).execute() - await callback.wait_for_disconnect() - - pubnub.stop() diff --git a/tests/integrational/python_v35/test_tornado_async_await_syntax.py b/tests/integrational/python_v35/test_tornado_async_await_syntax.py deleted file mode 100644 index cf742d16..00000000 --- a/tests/integrational/python_v35/test_tornado_async_await_syntax.py +++ /dev/null @@ -1,48 +0,0 @@ -import logging -import tornado -import pubnub as pn - -from tornado.testing import AsyncTestCase -from pubnub.pubnub_tornado import PubNubTornado, SubscribeListener -from tests import helper -from tests.helper import pnconf_sub_copy - -pn.set_stream_logger('pubnub', logging.DEBUG) - - -class SubscriptionTest(object): - def __init__(self): - super(SubscriptionTest, self).__init__() - self.pubnub = None - self.pubnub_listener = None - - -class TestChannelSubscription(AsyncTestCase, SubscriptionTest): - def setUp(self): - super(TestChannelSubscription, self).setUp() - self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - self.pubnub_listener = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - - @tornado.testing.gen_test - async def test_subscribe_publish_unsubscribe(self): - ch = helper.gen_channel("subscribe-test") - message = "hey" - - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channels(ch).execute() - await callback_messages.wait_for_connect() - - sub_env, pub_env = await tornado.gen.multi([ - callback_messages.wait_for_message_on(ch), - self.pubnub.publish().channel(ch).message(message).future()]) - - assert pub_env.status.original_response[0] == 1 - assert pub_env.status.original_response[1] == 'Sent' - - assert sub_env.channel == ch - assert sub_env.subscription is None - assert sub_env.message == message - - self.pubnub.unsubscribe().channels(ch).execute() - await callback_messages.wait_for_disconnect() diff --git a/tests/integrational/tornado/__init__.py b/tests/integrational/tornado/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/integrational/tornado/test_channel_groups.py b/tests/integrational/tornado/test_channel_groups.py deleted file mode 100644 index 1b542c88..00000000 --- a/tests/integrational/tornado/test_channel_groups.py +++ /dev/null @@ -1,131 +0,0 @@ -import tornado -from tornado import gen -from tornado.testing import AsyncTestCase - -from pubnub.models.consumer.channel_group import PNChannelGroupsAddChannelResult, PNChannelGroupsListResult, \ - PNChannelGroupsRemoveChannelResult, PNChannelGroupsRemoveGroupResult -from pubnub.pubnub_tornado import PubNubTornado -from tests.helper import pnconf -from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep - - -class TestChannelGroups(AsyncTestCase): - def setUp(self): - super(TestChannelGroups, self).setUp() - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/groups/add_remove_single_channel.yaml', - filter_query_parameters=['uuid', 'pnsdk', 'l_cg']) - @tornado.testing.gen_test - def test_add_remove_single_channel(self): - ch = "channel-groups-tornado-ch" - gr = "channel-groups-tornado-cg" - - # add - env = yield self.pubnub.add_channel_to_channel_group() \ - .channels(ch).channel_group(gr).future() - - assert isinstance(env.result, PNChannelGroupsAddChannelResult) - - yield gen.sleep(1) - - # list - env = yield self.pubnub.list_channels_in_channel_group().channel_group(gr).future() - - assert isinstance(env.result, PNChannelGroupsListResult) - assert len(env.result.channels) == 1 - assert env.result.channels[0] == ch - - # remove - env = yield self.pubnub.remove_channel_from_channel_group() \ - .channels(ch).channel_group(gr).future() - - assert isinstance(env.result, PNChannelGroupsRemoveChannelResult) - - yield gen.sleep(1) - - # list - env = yield self.pubnub.list_channels_in_channel_group().channel_group(gr).future() - assert isinstance(env.result, PNChannelGroupsListResult) - assert len(env.result.channels) == 0 - - self.pubnub.stop() - self.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/groups/add_remove_multiple_channel.yaml', - filter_query_parameters=['uuid', 'pnsdk', 'l_cg']) - @tornado.testing.gen_test - def test_add_remove_multiple_channels(self): - ch1 = "channel-groups-tornado-ch1" - ch2 = "channel-groups-tornado-ch2" - gr = "channel-groups-tornado-cg" - - # add - env = yield self.pubnub.add_channel_to_channel_group() \ - .channels([ch1, ch2]).channel_group(gr).future() - - assert isinstance(env.result, PNChannelGroupsAddChannelResult) - - yield gen.sleep(1) - - # list - env = yield self.pubnub.list_channels_in_channel_group().channel_group(gr).future() - assert isinstance(env.result, PNChannelGroupsListResult) - assert len(env.result.channels) == 2 - assert ch1 in env.result.channels - assert ch2 in env.result.channels - - # remove - env = yield self.pubnub.remove_channel_from_channel_group() \ - .channels([ch1, ch2]).channel_group(gr).future() - - assert isinstance(env.result, PNChannelGroupsRemoveChannelResult) - - yield gen.sleep(1) - - # list - env = yield self.pubnub.list_channels_in_channel_group().channel_group(gr).future() - assert isinstance(env.result, PNChannelGroupsListResult) - assert len(env.result.channels) == 0 - - self.pubnub.stop() - self.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/groups/add_channel_remove_group.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg']) - @tornado.testing.gen_test - def test_add_channel_remove_group(self): - ch = "channel-groups-tornado-ch" - gr = "channel-groups-tornado-cg" - - # add - env = yield self.pubnub.add_channel_to_channel_group() \ - .channels(ch).channel_group(gr).future() - - assert isinstance(env.result, PNChannelGroupsAddChannelResult) - - yield gen.sleep(1) - - # list - env = yield self.pubnub.list_channels_in_channel_group().channel_group(gr).future() - assert isinstance(env.result, PNChannelGroupsListResult) - assert len(env.result.channels) == 1 - assert env.result.channels[0] == ch - - # remove group - env = yield self.pubnub.remove_channel_group().channel_group(gr).future() - - assert isinstance(env.result, PNChannelGroupsRemoveGroupResult) - - yield gen.sleep(1) - - # list - env = yield self.pubnub.list_channels_in_channel_group().channel_group(gr).future() - assert isinstance(env.result, PNChannelGroupsListResult) - assert len(env.result.channels) == 0 - - self.pubnub.stop() - self.stop() diff --git a/tests/integrational/tornado/test_fire.py b/tests/integrational/tornado/test_fire.py deleted file mode 100644 index a9eb3f9a..00000000 --- a/tests/integrational/tornado/test_fire.py +++ /dev/null @@ -1,28 +0,0 @@ -import tornado -from tornado.testing import AsyncTestCase - -from pubnub.pubnub_tornado import PubNubTornado, TornadoEnvelope -from pubnub.models.consumer.pubsub import PNFireResult -from pubnub.models.consumer.common import PNStatus -from tests.helper import pnconf_copy -from tests.integrational.vcr_helper import pn_vcr - - -class TestMessageCount(AsyncTestCase): - def setUp(self): - AsyncTestCase.setUp(self) - config = pnconf_copy() - self.pn = PubNubTornado(config, custom_ioloop=self.io_loop) - - @pn_vcr.use_cassette('tests/integrational/fixtures/tornado/publish/fire_get.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) - @tornado.testing.gen_test - def test_single_channel(self): - chan = 'unique_sync' - envelope = yield self.pn.fire().channel(chan).message('bla').future() - - assert(isinstance(envelope, TornadoEnvelope)) - assert not envelope.status.is_error() - assert isinstance(envelope.result, PNFireResult) - assert isinstance(envelope.status, PNStatus) - self.pn.stop() diff --git a/tests/integrational/tornado/test_heartbeat.py b/tests/integrational/tornado/test_heartbeat.py deleted file mode 100644 index 630db880..00000000 --- a/tests/integrational/tornado/test_heartbeat.py +++ /dev/null @@ -1,86 +0,0 @@ -import logging -import tornado.testing -import pubnub as pn - -from tornado.testing import AsyncTestCase -from tornado import gen -from pubnub.pubnub_tornado import PubNubTornado, SubscribeListener -from tests.helper import pnconf_sub_copy -from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep - -pn.set_stream_logger('pubnub', logging.DEBUG) - - -class SubscriptionTest(object): - def __init__(self): - super(SubscriptionTest, self).__init__() - self.pubnub = None - self.pubnub_listener = None - - -class TestChannelSubscription(AsyncTestCase, SubscriptionTest): - def setUp(self): - super(TestChannelSubscription, self).setUp() - - messenger_config = pnconf_sub_copy() - messenger_config.set_presence_timeout(8) - messenger_config.uuid = "heartbeat-tornado-messenger" - - listener_config = pnconf_sub_copy() - listener_config.uuid = "heartbeat-tornado-listener" - - self.pubnub = PubNubTornado(messenger_config, custom_ioloop=self.io_loop) - self.pubnub_listener = PubNubTornado(listener_config, custom_ioloop=self.io_loop) - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/heartbeat/timeout.yaml', - filter_query_parameters=['uuid', 'pnsdk'], - match_on=['method', 'scheme', 'host', 'port', 'string_list_in_path', 'query'], - match_on_kwargs={ - 'string_list_in_path': { - 'positions': [4] - } - }) - @tornado.testing.gen_test(timeout=20) - def test_timeout_event_on_broken_heartbeat(self): - ch = "heartbeat-tornado-ch" - - # - connect to :ch-pnpres - callback_presence = SubscribeListener() - self.pubnub_listener.add_listener(callback_presence) - self.pubnub_listener.subscribe().channels(ch).with_presence().execute() - yield callback_presence.wait_for_connect() - - envelope = yield callback_presence.wait_for_presence_on(ch) - assert ch == envelope.channel - assert 'join' == envelope.event - assert self.pubnub_listener.uuid == envelope.uuid - - # - connect to :ch - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channels(ch).execute() - - # - assert join event - useless, prs_envelope = yield [ - callback_messages.wait_for_connect(), - callback_presence.wait_for_presence_on(ch)] - assert ch == prs_envelope.channel - assert 'join' == prs_envelope.event - assert self.pubnub.uuid == prs_envelope.uuid - - # wait for one heartbeat call - yield gen.sleep(8) - - # - break messenger heartbeat loop - self.pubnub._subscription_manager._stop_heartbeat_timer() - - # - assert for timeout - envelope = yield callback_presence.wait_for_presence_on(ch) - assert ch == envelope.channel - assert 'timeout' == envelope.event - assert self.pubnub.uuid == envelope.uuid - - # - disconnect from :ch-pnpres - self.pubnub_listener.unsubscribe().channels(ch).execute() - yield callback_presence.wait_for_disconnect() diff --git a/tests/integrational/tornado/test_here_now.py b/tests/integrational/tornado/test_here_now.py deleted file mode 100644 index 3f9d15d5..00000000 --- a/tests/integrational/tornado/test_here_now.py +++ /dev/null @@ -1,109 +0,0 @@ -import logging - -import tornado -import tornado.gen -from tornado import gen -from tornado.testing import AsyncTestCase - -import pubnub as pn -from pubnub.pubnub_tornado import PubNubTornado, SubscribeListener -from tests.helper import pnconf_sub_copy -from tests.integrational.tornado.tornado_helper import connect_to_channel, disconnect_from_channel -from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep - -pn.set_stream_logger('pubnub', logging.DEBUG) - - -class TestPubNubAsyncHereNow(AsyncTestCase): - def setUp(self): - super(TestPubNubAsyncHereNow, self).setUp() - self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/here_now/single.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pres']) - @tornado.testing.gen_test(timeout=15) - def test_here_now_single_channel(self): - ch = 'test-here-now-channel' - self.pubnub.config.uuid = 'test-here-now-uuid' - yield connect_to_channel(self.pubnub, ch) - yield tornado.gen.sleep(10) - env = yield self.pubnub.here_now() \ - .channels(ch) \ - .include_uuids(True) \ - .future() - - assert env.result.total_channels == 1 - assert env.result.total_occupancy >= 1 - - channels = env.result.channels - - assert len(channels) == 1 - assert channels[0].occupancy == 1 - assert channels[0].occupants[0].uuid == self.pubnub.uuid - - yield disconnect_from_channel(self.pubnub, ch) - self.pubnub.stop() - self.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/here_now/multiple.yaml', - filter_query_parameters=['uuid', 'tt', 'tr', 'pnsdk', 'l_pres']) - @tornado.testing.gen_test(timeout=120) - def test_here_now_multiple_channels(self): - ch1 = 'test-here-now-channel1' - ch2 = 'test-here-now-channel2' - self.pubnub.config.uuid = 'test-here-now-uuid' - # print("connecting to the first...") - yield connect_to_channel(self.pubnub, ch1) - # print("...connected to the first") - yield gen.sleep(1) - # print("connecting to the second...") - self.pubnub.subscribe().channels(ch2).execute() - # print("...connected to the second") - yield gen.sleep(5) - env = yield self.pubnub.here_now() \ - .channels([ch1, ch2]) \ - .future() - - assert env.result.total_channels == 2 - assert env.result.total_occupancy >= 1 - - channels = env.result.channels - - assert len(channels) == 2 - assert channels[0].occupancy >= 1 - assert channels[0].occupants[0].uuid == self.pubnub.uuid - assert channels[1].occupancy >= 1 - assert channels[1].occupants[0].uuid == self.pubnub.uuid - - yield disconnect_from_channel(self.pubnub, [ch1, ch2]) - self.pubnub.stop() - self.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/here_now/global.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pres']) - @tornado.testing.gen_test(timeout=15) - def test_here_now_global(self): - ch1 = 'test-here-now-channel1' - ch2 = 'test-here-now-channel2' - self.pubnub.config.uuid = 'test-here-now-uuid' - - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channels(ch1).execute() - yield callback_messages.wait_for_connect() - - self.pubnub.subscribe().channels(ch2).execute() - yield gen.sleep(6) - - env = yield self.pubnub.here_now().future() - - assert env.result.total_channels >= 2 - assert env.result.total_occupancy >= 1 - - yield disconnect_from_channel(self.pubnub, [ch1, ch2]) - - self.pubnub.stop() - self.stop() diff --git a/tests/integrational/tornado/test_history_delete.py b/tests/integrational/tornado/test_history_delete.py deleted file mode 100644 index 706e09b8..00000000 --- a/tests/integrational/tornado/test_history_delete.py +++ /dev/null @@ -1,32 +0,0 @@ - -from tornado.testing import AsyncTestCase -from pubnub.pubnub_tornado import PubNubTornado -from tests.helper import pnconf - - -class TestPubNubAsyncPublish(AsyncTestCase): # pylint: disable=W0612 - def setUp(self): - AsyncTestCase.setUp(self) - self.env = None - - def callback(self, tornado_res): - self.env = tornado_res.result() - self.pubnub.stop() - self.stop() - - def assert_success(self, pub): - pub.future().add_done_callback(self.callback) - - self.pubnub.start() - self.wait() - - if self.env.status.error: - raise AssertionError() - - def test_success(self): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - self.assert_success(self.pubnub.delete_messages().channel("my-ch").start(123).end(456)) - - def test_super_call(self): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - self.assert_success(self.pubnub.delete_messages().channel("my-ch- |.* $").start(123).end(456)) diff --git a/tests/integrational/tornado/test_invocations.py b/tests/integrational/tornado/test_invocations.py deleted file mode 100644 index 18383205..00000000 --- a/tests/integrational/tornado/test_invocations.py +++ /dev/null @@ -1,98 +0,0 @@ -import logging -import pytest -import pubnub as pn -import tornado - -from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep - -pn.set_stream_logger('pubnub', logging.DEBUG) - -from tornado.testing import AsyncTestCase -from pubnub.exceptions import PubNubException -from pubnub.models.consumer.pubsub import PNPublishResult -from pubnub.pnconfiguration import PNConfiguration -from pubnub.pubnub_tornado import PubNubTornado, TornadoEnvelope, PubNubTornadoException -from tests.helper import pnconf_sub_copy - -corrupted_keys = PNConfiguration() -corrupted_keys.publish_key = "blah" -corrupted_keys.subscribe_key = "blah" - -pn.set_stream_logger('pubnub', logging.DEBUG) - -ch = "tornado-publish" - - -class TestPubNubTornadoInvocations(AsyncTestCase): - def setUp(self): - super(TestPubNubTornadoInvocations, self).setUp() - - @tornado.testing.gen_test - def test_publish_resultx(self): - pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - result = yield pubnub.publish().message('hey').channel('blah').result() - assert isinstance(result, PNPublishResult) - - pubnub.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/invocations/result_raises.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) - @tornado.testing.gen_test - def test_publish_result_raises_pubnub_error(self): - pubnub = PubNubTornado(corrupted_keys, custom_ioloop=self.io_loop) - with pytest.raises(PubNubException) as exinfo: - yield pubnub.publish().message('hey').channel('blah').result() - - assert 'Invalid Subscribe Key' in str(exinfo.value) - assert 400 == exinfo.value._status_code - - pubnub.stop() - - @tornado.testing.gen_test - def xtest_publish_result_raises_lower_level_error(self): - pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - - # TODO: find a better way ot emulate broken connection - pubnub.http.close() - - with self.assertRaises(Exception) as context: - yield pubnub.publish().message('hey').channel('blah').result() - - assert 'fetch() called on closed AsyncHTTPClient' in str(context.exception.message) - - pubnub.stop() - - @tornado.testing.gen_test - def test_publish_futurex(self): - pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - envelope = yield pubnub.publish().message('hey').channel('blah').future() - assert isinstance(envelope, TornadoEnvelope) - assert not envelope.is_error() - - pubnub.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/invocations/future_raises.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) - @tornado.testing.gen_test - def test_publish_future_raises(self): - pubnub = PubNubTornado(corrupted_keys, custom_ioloop=self.io_loop) - e = yield pubnub.publish().message('hey').channel('blah').future() - assert isinstance(e, PubNubTornadoException) - assert e.is_error() - assert 400 == e.value()._status_code - - pubnub.stop() - - @tornado.testing.gen_test - def xtest_publish_future_raises_lower_level_error(self): - pubnub = PubNubTornado(corrupted_keys, custom_ioloop=self.io_loop) - - pubnub.http.close() - - e = yield pubnub.publish().message('hey').channel('blah').future() - assert isinstance(e, PubNubTornadoException) - assert str(e) == "fetch() called on closed AsyncHTTPClient" - - pubnub.stop() diff --git a/tests/integrational/tornado/test_message_count.py b/tests/integrational/tornado/test_message_count.py deleted file mode 100644 index 98814262..00000000 --- a/tests/integrational/tornado/test_message_count.py +++ /dev/null @@ -1,53 +0,0 @@ -import tornado -from tornado.testing import AsyncTestCase - -from pubnub.pubnub_tornado import PubNubTornado, TornadoEnvelope -from pubnub.models.consumer.message_count import PNMessageCountResult -from pubnub.models.consumer.common import PNStatus -from tests.helper import pnconf_mc_copy -from tests.integrational.vcr_helper import pn_vcr - - -class TestMessageCount(AsyncTestCase): - def setUp(self): - AsyncTestCase.setUp(self) - config = pnconf_mc_copy() - config.enable_subscribe = False - self.pn = PubNubTornado(config, custom_ioloop=self.io_loop) - - @pn_vcr.use_cassette('tests/integrational/fixtures/tornado/message_count/single.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pub']) - @tornado.testing.gen_test - def test_single_channel(self): - chan = 'unique_tornado' - envelope = yield self.pn.publish().channel(chan).message('bla').future() - time = envelope.result.timetoken - 10 - envelope = yield self.pn.message_counts().channel(chan).channel_timetokens([time]).future() - - assert(isinstance(envelope, TornadoEnvelope)) - assert not envelope.status.is_error() - assert envelope.result.channels[chan] == 1 - assert isinstance(envelope.result, PNMessageCountResult) - assert isinstance(envelope.status, PNStatus) - - self.pn.stop() - - @pn_vcr.use_cassette('tests/integrational/fixtures/tornado/message_count/multi.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pub']) - @tornado.testing.gen_test - def test_multiple_channels(self): - chan_1 = 'unique_asyncio_1' - chan_2 = 'unique_asyncio_2' - chans = ','.join([chan_1, chan_2]) - envelope = yield self.pn.publish().channel(chan_1).message('something').future() - time = envelope.result.timetoken - 10 - envelope = yield self.pn.message_counts().channel(chans).channel_timetokens([time, time]).future() - - assert(isinstance(envelope, TornadoEnvelope)) - assert not envelope.status.is_error() - assert envelope.result.channels[chan_1] == 1 - assert envelope.result.channels[chan_2] == 0 - assert isinstance(envelope.result, PNMessageCountResult) - assert isinstance(envelope.status, PNStatus) - - self.pn.stop() diff --git a/tests/integrational/tornado/test_publish.py b/tests/integrational/tornado/test_publish.py deleted file mode 100644 index cc6b292a..00000000 --- a/tests/integrational/tornado/test_publish.py +++ /dev/null @@ -1,251 +0,0 @@ -import logging - -import tornado -from tornado.concurrent import Future -from tornado.testing import AsyncTestCase - -import pubnub as pn -from pubnub.exceptions import PubNubException -from pubnub.models.consumer.common import PNStatus -from pubnub.models.consumer.pubsub import PNPublishResult -from pubnub.pnconfiguration import PNConfiguration -from pubnub.pubnub_tornado import PubNubTornado, TornadoEnvelope -from tests.helper import pnconf, pnconf_enc, gen_decrypt_func, pnconf_pam_copy -from tests.integrational.vcr_helper import pn_vcr - -pn.set_stream_logger('pubnub', logging.DEBUG) - -ch = "tornado-publish" - - -class TestPubNubAsyncPublish(AsyncTestCase): - def setUp(self): - AsyncTestCase.setUp(self) - self.env = None - - def callback(self, tornado_res): - self.env = tornado_res.result() - self.pubnub.stop() - self.stop() - - def assert_success(self, pub): - pub.future().add_done_callback(self.callback) - - self.pubnub.start() - self.wait() - - assert isinstance(self.env, TornadoEnvelope) - assert isinstance(self.env.result, PNPublishResult) - assert isinstance(self.env.status, PNStatus) - assert self.env.result.timetoken > 0 - assert len(self.env.status.original_response) > 0 - - @tornado.testing.gen_test - def assert_success_yield(self, pub): - envelope = yield pub.future() - - assert isinstance(envelope, TornadoEnvelope) - assert isinstance(envelope.result, PNPublishResult) - assert isinstance(envelope.status, PNStatus) - assert envelope.result.timetoken > 0 - assert len(envelope.status.original_response) > 0 - - def assert_success_publish_get(self, msg): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - self.assert_success(self.pubnub.publish().channel(ch).message(msg)) - self.assert_success_yield(self.pubnub.publish().channel(ch).message(msg)) - - def assert_success_publish_post(self, msg): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - self.assert_success(self.pubnub.publish().channel(ch).message(msg).use_post(True)) - self.assert_success_yield(self.pubnub.publish().channel(ch).message(msg).use_post(True)) - - def assert_success_publish_get_encrypted(self, msg): - self.pubnub = PubNubTornado(pnconf_enc, custom_ioloop=self.io_loop) - self.assert_success(self.pubnub.publish().channel(ch).message(msg)) - self.assert_success_yield(self.pubnub.publish().channel(ch).message(msg)) - - def assert_success_publish_post_encrypted(self, msg): - self.pubnub = PubNubTornado(pnconf_enc, custom_ioloop=self.io_loop) - self.assert_success(self.pubnub.publish().channel(ch).message(msg).use_post(True)) - self.assert_success_yield(self.pubnub.publish().channel(ch).message(msg).use_post(True)) - - def assert_client_side_error(self, pub, expected_err_msg): - try: - yield pub.future() - - self.pubnub.start() - self.wait() - except PubNubException as e: - assert expected_err_msg in str(e) - - self.pubnub.stop() - self.stop() - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/mixed_via_get.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub']) - def test_publish_mixed_via_get(self): - self.assert_success_publish_get("hi") - self.assert_success_publish_get(5) - self.assert_success_publish_get(True) - self.assert_success_publish_get(["hi", "hi2", "hi3"]) - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/object_via_get.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub'], - match_on=['method', 'scheme', 'host', 'port', 'object_in_path', 'query']) - def test_publish_object_via_get(self): - self.assert_success_publish_get({"name": "Alex", "online": True}) - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/mixed_via_post.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub'], - match_on=['method', 'scheme', 'host', 'port', 'path', 'query']) - def test_publish_mixed_via_post(self): - self.assert_success_publish_post("hi") - self.assert_success_publish_post(5) - self.assert_success_publish_post(True) - self.assert_success_publish_post(["hi", "hi2", "hi3"]) - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/object_via_post.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub'], - match_on=['host', 'method', 'path', 'query', 'object_in_body']) - def test_publish_object_via_post(self): - self.assert_success_publish_post({"name": "Alex", "online": True}) - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/mixed_via_get_encrypted.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub']) - def test_publish_mixed_via_get_encrypted(self): - self.assert_success_publish_get_encrypted("hi") - self.assert_success_publish_get_encrypted(5) - self.assert_success_publish_get_encrypted(True) - self.assert_success_publish_get_encrypted(["hi", "hi2", "hi3"]) - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/object_via_get_encrypted.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub'], - match_on=['host', 'method', 'query', 'object_in_path'], - match_on_kwargs={'object_in_path': { - 'decrypter': gen_decrypt_func('testKey')}}) - def test_publish_object_via_get_encrypted(self): - self.assert_success_publish_get_encrypted({"name": "Alex", "online": True}) - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/mixed_via_post_encrypted.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub'], - match_on=['method', 'path', 'query', 'body']) - def test_publish_mixed_via_post_encrypted(self): - self.assert_success_publish_post_encrypted("hi") - self.assert_success_publish_post_encrypted(5) - self.assert_success_publish_post_encrypted(True) - self.assert_success_publish_post_encrypted(["hi", "hi2", "hi3"]) - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/object_via_post_encrypted.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub'], - match_on=['method', 'path', 'query', 'object_in_body'], - match_on_kwargs={'object_in_body': { - 'decrypter': gen_decrypt_func('testKey')}}) - def test_publish_object_via_post_encrypted(self): - self.assert_success_publish_post_encrypted({"name": "Alex", "online": True}) - - def test_error_missing_message(self): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - - self.assert_client_side_error(self.pubnub.publish().channel(ch).message(None), "Message missing") - - def test_error_missing_channel(self): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - - self.assert_client_side_error(self.pubnub.publish().channel("").message("hey"), "Channel missing") - - def test_error_non_serializable(self): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - - def method(): - pass - - self.assert_client_side_error(self.pubnub.publish().channel(ch).message(method), "not JSON serializable") - - def sserr_cb(self, env): - assert isinstance(env, Future) - exception = env.exception() - - self.pubnub.stop() - # this kind of assertion will not fail the test if'll be moved below `self.stop()` call - # but also not raises correct exception, timeout exception will be raised on fail instead - assert self.expected_err_msg in str(exception) - self.stop() - - def assert_server_side_error(self, pub, expected_err_msg): - self.expected_err_msg = expected_err_msg - pub.result().add_done_callback(self.sserr_cb) - - self.pubnub.start() - self.wait() - - @tornado.testing.gen_test - def assert_server_side_error_yield(self, pub, expected_err_msg): - - try: - yield pub.result() - - self.pubnub.start() - self.wait() - except PubNubException as e: - assert expected_err_msg in str(e) - - self.pubnub.stop() - self.stop() - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/invalid_key.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub']) - def test_error_invalid_key(self): - conf = PNConfiguration() - conf.publish_key = "fake" - conf.subscribe_key = "demo" - - self.pubnub = PubNubTornado(conf, custom_ioloop=self.io_loop) - - self.assert_server_side_error(self.pubnub.publish().channel(ch).message("hey"), "Invalid Key") - self.assert_server_side_error_yield(self.pubnub.publish().channel(ch).message("hey"), "Invalid Key") - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/not_permitted.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub']) - def test_error_not_permitted_403(self): - my_pnconf = pnconf_pam_copy() - my_pnconf.secret_key = None - self.pubnub = PubNubTornado(my_pnconf, custom_ioloop=self.io_loop) - - self.assert_server_side_error( - self.pubnub.publish().channel("not_permitted_channel").message("hey"), "HTTP Client Error (403)") - self.assert_server_side_error_yield( - self.pubnub.publish().channel("not_permitted_channel").message("hey"), "HTTP Client Error (403)") - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/meta_object.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub'], - match_on=['host', 'method', 'path', 'meta_object_in_query']) - def test_publish_with_meta(self): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - - self.assert_success( - self.pubnub.publish().channel(ch).message("hey").meta({'a': 2, 'b': 'qwer'})) - self.assert_success_yield( - self.pubnub.publish().channel(ch).message("hey").meta({'a': 2, 'b': 'qwer'})) - - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/tornado/publish/do_not_store.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub']) - def test_publish_do_not_store(self): - self.pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - - self.assert_success( - self.pubnub.publish().channel(ch).message("hey").should_store(False)) - self.assert_success_yield( - self.pubnub.publish().channel(ch).message("hey").should_store(False)) diff --git a/tests/integrational/tornado/test_signal.py b/tests/integrational/tornado/test_signal.py deleted file mode 100644 index d4f1d3ee..00000000 --- a/tests/integrational/tornado/test_signal.py +++ /dev/null @@ -1,32 +0,0 @@ -import tornado -from tornado.testing import AsyncTestCase - -from pubnub.pubnub_tornado import PubNubTornado, TornadoEnvelope -from pubnub.models.consumer.signal import PNSignalResult -from pubnub.models.consumer.common import PNStatus -from pubnub.pnconfiguration import PNConfiguration -from tests.integrational.vcr_helper import pn_vcr - - -class TestSignal(AsyncTestCase): - def setUp(self): - AsyncTestCase.setUp(self) - pnconf = PNConfiguration() - pnconf.publish_key = 'demo' - pnconf.subscribe_key = 'demo' - pnconf.enable_subscribe = False - self.pn = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - - @pn_vcr.use_cassette('tests/integrational/fixtures/tornado/signal/single.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) - @tornado.testing.gen_test - def test_single_channel(self): - chan = 'unique_sync' - envelope = yield self.pn.signal().channel(chan).message('test').future() - - assert(isinstance(envelope, TornadoEnvelope)) - assert not envelope.status.is_error() - assert envelope.result.timetoken == '15640051976283377' - assert isinstance(envelope.result, PNSignalResult) - assert isinstance(envelope.status, PNStatus) - self.pn.stop() diff --git a/tests/integrational/tornado/test_ssl.py b/tests/integrational/tornado/test_ssl.py deleted file mode 100644 index 34e002c6..00000000 --- a/tests/integrational/tornado/test_ssl.py +++ /dev/null @@ -1,42 +0,0 @@ -import logging -import pytest -import sys -import tornado -import pubnub as pn - -from tornado.testing import AsyncTestCase -from pubnub.models.consumer.common import PNStatus -from pubnub.models.consumer.pubsub import PNPublishResult -from pubnub.pubnub_tornado import PubNubTornado, TornadoEnvelope -from tests.helper import pnconf_ssl_copy - -try: - import __pypy__ -except ImportError: - __pypy__ = None - -pn.set_stream_logger('pubnub', logging.DEBUG) - -ch = "tornado-int-publish" - - -class TestPubNubAsyncPublish(AsyncTestCase): - # TODO: add vcr - @pytest.mark.skipif(__pypy__ is not None, - reason="TODO: configure SSL certificate to make test pass") - @tornado.testing.gen_test - def test_publish_ssl(self): - print(sys.version_info) - pubnub = PubNubTornado(pnconf_ssl_copy(), custom_ioloop=self.io_loop) - msg = "hey" - pub = pubnub.publish().channel(ch).message(msg) - - envelope = yield pub.future() - - assert isinstance(envelope, TornadoEnvelope) - assert isinstance(envelope.result, PNPublishResult) - assert isinstance(envelope.status, PNStatus) - assert envelope.result.timetoken > 0 - assert len(envelope.status.original_response) > 0 - - pubnub.stop() diff --git a/tests/integrational/tornado/test_state.py b/tests/integrational/tornado/test_state.py deleted file mode 100644 index 95c824c8..00000000 --- a/tests/integrational/tornado/test_state.py +++ /dev/null @@ -1,105 +0,0 @@ -import tornado -import logging -import pubnub as pn - -from tornado.testing import AsyncTestCase -from pubnub.pubnub_tornado import PubNubTornado -from tests.helper import pnconf_copy, pnconf_pam_copy -from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep - - -pn.set_stream_logger('pubnub', logging.DEBUG) - - -class TestPubNubState(AsyncTestCase): - def setUp(self): - super(TestPubNubState, self).setUp() - self.pubnub = PubNubTornado(pnconf_copy(), custom_ioloop=self.io_loop) - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/state/single_channel.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk'], - match_on=['method', 'host', 'path', 'state_object_in_query']) - @tornado.testing.gen_test - def test_state_single_channel(self): - ch = "state-tornado-ch" - self.pubnub.config.uuid = 'state-tornado-uuid' - state = {"name": "Alex", "count": 5} - - env = yield self.pubnub.set_state() \ - .channels(ch) \ - .state(state) \ - .future() - - assert env.result.state['name'] == "Alex" - assert env.result.state['count'] == 5 - - env = yield self.pubnub.get_state() \ - .channels(ch) \ - .future() - - assert env.result.channels[ch]['name'] == "Alex" - assert env.result.channels[ch]['count'] == 5 - - self.pubnub.stop() - self.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/state/multiple_channel.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk'], - match_on=['method', 'host', 'path', 'state_object_in_query']) - @tornado.testing.gen_test - def test_multiple_channels(self): - ch1 = "state-tornado-ch1" - ch2 = "state-tornado-ch2" - self.pubnub.config.uuid = 'state-tornado-uuid' - state = {"name": "Alex", "count": 5} - - env = yield self.pubnub.set_state() \ - .channels([ch1, ch2]) \ - .state(state) \ - .future() - - assert env.result.state['name'] == "Alex" - assert env.result.state['count'] == 5 - - env = yield self.pubnub.get_state() \ - .channels([ch1, ch2]) \ - .future() - - assert env.result.channels[ch1]['name'] == "Alex" - assert env.result.channels[ch2]['name'] == "Alex" - assert env.result.channels[ch1]['count'] == 5 - assert env.result.channels[ch2]['count'] == 5 - - self.pubnub.stop() - self.stop() - - @tornado.testing.gen_test - def test_super_call(self): - ch1 = "state-tornado-ch1" - ch2 = "state-tornado-ch2" - pnconf = pnconf_pam_copy() - pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - pubnub.config.uuid = 'test-state-tornado-uuid-|.*$' - state = {"name": "Alex", "count": 5} - - env = yield pubnub.set_state() \ - .channels([ch1, ch2]) \ - .state(state) \ - .future() - - assert env.result.state['name'] == "Alex" - assert env.result.state['count'] == 5 - - env = yield pubnub.get_state() \ - .channels([ch1, ch2]) \ - .future() - - assert env.result.channels[ch1]['name'] == "Alex" - assert env.result.channels[ch2]['name'] == "Alex" - assert env.result.channels[ch1]['count'] == 5 - assert env.result.channels[ch2]['count'] == 5 - - pubnub.stop() - self.stop() diff --git a/tests/integrational/tornado/test_subscribe.py b/tests/integrational/tornado/test_subscribe.py deleted file mode 100644 index f6eb4d60..00000000 --- a/tests/integrational/tornado/test_subscribe.py +++ /dev/null @@ -1,303 +0,0 @@ -import logging - -import tornado -from tornado import gen -from tornado.testing import AsyncTestCase - -import pubnub as pn -from pubnub.pubnub_tornado import PubNubTornado, SubscribeListener -from tests.helper import pnconf_sub_copy -from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep - -pn.set_stream_logger('pubnub', logging.DEBUG) - - -class SubscriptionTest(object): - def __init__(self): - super(SubscriptionTest, self).__init__() - self.pubnub = None - self.pubnub_listener = None - - -class TestChannelSubscription(AsyncTestCase, SubscriptionTest): - def setUp(self): - super(TestChannelSubscription, self).setUp() - self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - self.pubnub_listener = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/subscribe/sub_unsub.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) - @tornado.testing.gen_test(timeout=300) - def test_subscribe_unsubscribe(self): - ch = "subscribe-tornado-ch" - - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - - self.pubnub.subscribe().channels(ch).execute() - assert ch in self.pubnub.get_subscribed_channels() - assert len(self.pubnub.get_subscribed_channels()) == 1 - - yield callback_messages.wait_for_connect() - assert ch in self.pubnub.get_subscribed_channels() - assert len(self.pubnub.get_subscribed_channels()) == 1 - - self.pubnub.unsubscribe().channels(ch).execute() - assert ch not in self.pubnub.get_subscribed_channels() - assert len(self.pubnub.get_subscribed_channels()) == 0 - - yield callback_messages.wait_for_disconnect() - assert ch not in self.pubnub.get_subscribed_channels() - assert len(self.pubnub.get_subscribed_channels()) == 0 - - self.pubnub.stop() - self.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/subscribe/sub_pub_unsub.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pub']) - @tornado.testing.gen_test(timeout=30) - def test_subscribe_publish_unsubscribe(self): - ch = "subscribe-tornado-ch" - message = "hey" - - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channels(ch).execute() - yield callback_messages.wait_for_connect() - - sub_env, pub_env = yield [ - callback_messages.wait_for_message_on(ch), - self.pubnub.publish().channel(ch).message(message).future()] - - assert pub_env.status.original_response[0] == 1 - assert pub_env.status.original_response[1] == 'Sent' - - assert sub_env.channel == ch - assert sub_env.subscription is None - assert sub_env.message == message - - self.pubnub.unsubscribe().channels(ch).execute() - yield callback_messages.wait_for_disconnect() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/subscribe/join_leave.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk']) - @tornado.testing.gen_test(timeout=30) - def test_join_leave(self): - ch = "subscribe-tornado-ch" - - # HINT: use random generated uuids to test without VCR - # rnd = gen_string(4) - # self.pubnub.config.uuid = "subscribe-tornado-messenger-%s" % rnd - # self.pubnub_listener.config.uuid = "subscribe-tornado-listener-%s" % rnd - - self.pubnub.config.uuid = "subscribe-tornado-messenger-3" - self.pubnub_listener.config.uuid = "subscribe-tornado-listener-3" - - callback_presence = SubscribeListener() - self.pubnub_listener.add_listener(callback_presence) - self.pubnub_listener.subscribe().channels(ch).with_presence().execute() - yield callback_presence.wait_for_connect() - - envelope = yield callback_presence.wait_for_presence_on(ch) - assert envelope.channel == ch - assert envelope.event == 'join' - assert envelope.uuid == self.pubnub_listener.uuid - - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channels(ch).execute() - yield callback_messages.wait_for_connect() - - envelope = yield callback_presence.wait_for_presence_on(ch) - assert envelope.channel == ch - assert envelope.event == 'join' - assert envelope.uuid == self.pubnub.uuid - - self.pubnub.unsubscribe().channels(ch).execute() - yield callback_messages.wait_for_disconnect() - - envelope = yield callback_presence.wait_for_presence_on(ch) - assert envelope.channel == ch - assert envelope.event == 'leave' - assert envelope.uuid == self.pubnub.uuid - - self.pubnub_listener.unsubscribe().channels(ch).execute() - yield callback_presence.wait_for_disconnect() - self.pubnub.stop() - self.stop() - - -class TestChannelGroupSubscription(AsyncTestCase, SubscriptionTest): - def setUp(self): - super(TestChannelGroupSubscription, self).setUp() - self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - self.pubnub_listener = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/subscribe/group_sub_unsub.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pres']) - @tornado.testing.gen_test(timeout=60) - def test_group_subscribe_unsubscribe(self): - ch = "subscribe-unsubscribe-channel" - gr = "subscribe-unsubscribe-group" - - envelope = yield self.pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() - assert envelope.status.original_response['status'] == 200 - - yield gen.sleep(1) - - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channel_groups(gr).execute() - yield callback_messages.wait_for_connect() - - self.pubnub.unsubscribe().channel_groups(gr).execute() - yield callback_messages.wait_for_disconnect() - - envelope = yield self.pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() - assert envelope.status.original_response['status'] == 200 - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/subscribe/group_sub_pub_unsub.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pub', 'l_pres']) - @tornado.testing.gen_test(timeout=60) - def test_group_subscribe_publish_unsubscribe(self): - ch = "subscribe-unsubscribe-channel" - gr = "subscribe-unsubscribe-group" - message = "hey" - - envelope = yield self.pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() - assert envelope.status.original_response['status'] == 200 - - yield gen.sleep(1) - - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channel_groups(gr).execute() - yield callback_messages.wait_for_connect() - - sub_envelope, pub_envelope = yield [ - callback_messages.wait_for_message_on(ch), - self.pubnub.publish().channel(ch).message(message).future()] - - assert pub_envelope.status.original_response[0] == 1 - assert pub_envelope.status.original_response[1] == 'Sent' - - assert sub_envelope.channel == ch - assert sub_envelope.subscription == gr - assert sub_envelope.message == message - - self.pubnub.unsubscribe().channel_groups(gr).execute() - yield callback_messages.wait_for_disconnect() - - envelope = yield self.pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() - assert envelope.status.original_response['status'] == 200 - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/subscribe/group_join_leave.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_cg', 'l_pres']) - @tornado.testing.gen_test(timeout=60) - def test_group_join_leave(self): - self.pubnub.config.uuid = "test-subscribe-messenger" - self.pubnub_listener.config.uuid = "test-subscribe-listener" - - ch = "subscribe-test-channel" - gr = "subscribe-test-group" - - envelope = yield self.pubnub.add_channel_to_channel_group().channel_group(gr).channels(ch).future() - assert envelope.status.original_response['status'] == 200 - - yield gen.sleep(1) - - callback_messages = SubscribeListener() - callback_presence = SubscribeListener() - - self.pubnub_listener.add_listener(callback_presence) - self.pubnub_listener.subscribe().channel_groups(gr).with_presence().execute() - yield callback_presence.wait_for_connect() - - prs_envelope = yield callback_presence.wait_for_presence_on(ch) - assert prs_envelope.event == 'join' - assert prs_envelope.uuid == self.pubnub_listener.uuid - assert prs_envelope.channel == ch - assert prs_envelope.subscription == gr - - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channel_groups(gr).execute() - - useless, prs_envelope = yield [ - callback_messages.wait_for_connect(), - callback_presence.wait_for_presence_on(ch) - ] - - assert prs_envelope.event == 'join' - assert prs_envelope.uuid == self.pubnub.uuid - assert prs_envelope.channel == ch - assert prs_envelope.subscription == gr - - self.pubnub.unsubscribe().channel_groups(gr).execute() - - useless, prs_envelope = yield [ - callback_messages.wait_for_disconnect(), - callback_presence.wait_for_presence_on(ch) - ] - - assert prs_envelope.event == 'leave' - assert prs_envelope.uuid == self.pubnub.uuid - assert prs_envelope.channel == ch - assert prs_envelope.subscription == gr - - self.pubnub_listener.unsubscribe().channel_groups(gr).execute() - yield callback_presence.wait_for_disconnect() - - envelope = yield self.pubnub.remove_channel_from_channel_group().channel_group(gr).channels(ch).future() - assert envelope.status.original_response['status'] == 200 - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/subscribe/subscribe_tep_by_step.yaml', - filter_query_parameters=['uuid', 'seqn', 'pnsdk', 'l_pres']) - @tornado.testing.gen_test(timeout=30) - def test_subscribe_step_by_step(self): - ch1 = 'test-here-now-channel1' - ch2 = 'test-here-now-channel2' - ch3 = 'test-here-now-channel3' - self.pubnub.config.uuid = 'test-here-now-uuid' - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - print("connecting to the first...") - self.pubnub.subscribe().channels(ch1).execute() - yield callback_messages.wait_for_connect() - print("...connected to the first") - yield gen.sleep(1) - print("connecting to the second...") - self.pubnub.subscribe().channels(ch2).execute() - self.pubnub.subscribe().channels(ch3).execute() - self.pubnub.subscribe().channels(ch3).execute() - self.pubnub.subscribe().channels(ch2).execute() - print("...connected to the second") - yield gen.sleep(5) - env = yield self.pubnub.here_now() \ - .channels([ch1, ch2]) \ - .future() - - assert env.result.total_channels == 2 - assert env.result.total_occupancy >= 1 - - channels = env.result.channels - - assert len(channels) == 2 - assert channels[0].occupancy >= 1 - assert channels[0].occupants[0].uuid == self.pubnub.uuid - assert channels[1].occupancy >= 1 - assert channels[1].occupants[0].uuid == self.pubnub.uuid - - self.pubnub.unsubscribe().channels([ch1, ch2]).execute() - yield callback_messages.wait_for_disconnect() - - self.pubnub.unsubscribe().channels(ch3).execute() - - self.pubnub.stop() - self.stop() diff --git a/tests/integrational/tornado/test_where_now.py b/tests/integrational/tornado/test_where_now.py deleted file mode 100644 index 089365f1..00000000 --- a/tests/integrational/tornado/test_where_now.py +++ /dev/null @@ -1,70 +0,0 @@ -import tornado -from tornado import gen -from tornado.testing import AsyncTestCase - -from pubnub.pubnub_tornado import PubNubTornado, SubscribeListener -from tests.helper import pnconf_sub_copy -from tests.integrational.tornado.tornado_helper import connect_to_channel, disconnect_from_channel -from tests.integrational.tornado.vcr_tornado_decorator import use_cassette_and_stub_time_sleep - - -class TestPubNubAsyncWhereNow(AsyncTestCase): - def setUp(self): - super(TestPubNubAsyncWhereNow, self).setUp() - self.pubnub = PubNubTornado(pnconf_sub_copy(), custom_ioloop=self.io_loop) - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/where_now/single_channel.yaml', - filter_query_parameters=['uuid', 'pnsdk', 'l_pres']) - @tornado.testing.gen_test(timeout=15) - def test_where_now_single_channel(self): - ch = "where-now-tornado-ch" - uuid = "where-now-tornado-uuid" - self.pubnub.config.uuid = uuid - - yield connect_to_channel(self.pubnub, ch) - yield gen.sleep(10) - env = yield self.pubnub.where_now() \ - .uuid(uuid) \ - .future() - - channels = env.result.channels - - assert len(channels) == 1 - assert channels[0] == ch - - yield disconnect_from_channel(self.pubnub, ch) - self.pubnub.stop() - self.stop() - - @use_cassette_and_stub_time_sleep( - 'tests/integrational/fixtures/tornado/where_now/multiple_channels.yaml', - filter_query_parameters=['uuid', 'pnsdk', 'l_pres']) - @tornado.testing.gen_test(timeout=15) - def test_multiple_channels(self): - ch1 = "where-now-tornado-ch1" - ch2 = "where-now-tornado-ch2" - uuid = "where-now-tornado-uuid" - self.pubnub.config.uuid = uuid - - callback_messages = SubscribeListener() - self.pubnub.add_listener(callback_messages) - self.pubnub.subscribe().channels(ch1).execute() - yield callback_messages.wait_for_connect() - - self.pubnub.subscribe().channels(ch2).execute() - yield gen.sleep(5) - - env = yield self.pubnub.where_now() \ - .uuid(uuid) \ - .future() - - channels = env.result.channels - - assert len(channels) == 2 - assert ch1 in channels - assert ch2 in channels - - yield disconnect_from_channel(self.pubnub, [ch1, ch2]) - self.pubnub.stop() - self.stop() diff --git a/tests/integrational/tornado/tornado_helper.py b/tests/integrational/tornado/tornado_helper.py deleted file mode 100644 index 96d6ea7b..00000000 --- a/tests/integrational/tornado/tornado_helper.py +++ /dev/null @@ -1,39 +0,0 @@ -from tornado.locks import Event -from tornado import gen - -from pubnub import utils -from pubnub.callbacks import SubscribeCallback - - -class ConnectionEvent(SubscribeCallback): - def __init__(self, event, expected_status_checker): - self.event = event - self.expected_status_checker = expected_status_checker - - def status(self, pubnub, status): - if self.expected_status_checker(status): - self.event.set() - - def presence(self, pubnub, presence): - pass - - def message(self, pubnub, message): - pass - - -@gen.coroutine -def connect_to_channel(pubnub, channel): - event = Event() - callback = ConnectionEvent(event, utils.is_subscribed_event) - pubnub.add_listener(callback) - pubnub.subscribe().channels(channel).execute() - yield event.wait() - - -@gen.coroutine -def disconnect_from_channel(pubnub, channel): - event = Event() - callback = ConnectionEvent(event, utils.is_unsubscribed_event) - pubnub.add_listener(callback) - pubnub.unsubscribe().channels(channel).execute() - yield event.wait() diff --git a/tests/integrational/tornado/vcr_tornado_decorator.py b/tests/integrational/tornado/vcr_tornado_decorator.py deleted file mode 100644 index 8b5cc94c..00000000 --- a/tests/integrational/tornado/vcr_tornado_decorator.py +++ /dev/null @@ -1,42 +0,0 @@ -import six - -from tests.integrational.vcr_helper import pn_vcr - -try: - from mock import patch -except ImportError: - from unittest.mock import patch - - -def use_cassette_and_stub_time_sleep(cassette_name, **kwargs): - context = pn_vcr.use_cassette(cassette_name, **kwargs) - full_path = "{}/{}".format(pn_vcr.cassette_library_dir, cassette_name) - cs = context.cls(path=full_path).load(path=full_path) - - if 'filter_query_parameters' in kwargs: - kwargs['filter_query_parameters'].append('pnsdk') - - import tornado.gen - - @tornado.gen.coroutine - def returner(): - return - - def _inner(f): - @patch('tornado.gen.sleep', return_value=returner()) - @six.wraps(f) - def stubbed(*args, **kwargs): - with context: - largs = list(args) - # 1 - index - largs.pop(1) - return f(*largs, **kwargs) - - @six.wraps(f) - def original(*args): - with context: - return f(*args) - - return stubbed if len(cs) > 0 else original - - return _inner diff --git a/tests/integrational/twisted/__init__.py b/tests/integrational/twisted/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/integrational/twisted/test_cg.py b/tests/integrational/twisted/test_cg.py deleted file mode 100644 index 6aa94e08..00000000 --- a/tests/integrational/twisted/test_cg.py +++ /dev/null @@ -1,101 +0,0 @@ -import twisted - -from twisted.internet import reactor -from twisted.internet.defer import inlineCallbacks, returnValue -from twisted.trial import unittest -from twisted.web.client import HTTPConnectionPool - -from pubnub.models.consumer.channel_group import PNChannelGroupsAddChannelResult, PNChannelGroupsListResult, \ - PNChannelGroupsRemoveChannelResult -from pubnub.pubnub_twisted import PubNubTwisted - -from tests.helper import pnconf -from tests.integrational.vcr_helper import pn_vcr - -twisted.internet.base.DelayedCall.debug = True - - -class CGTestCase(unittest.TestCase): - def setUp(self): - self.pool = HTTPConnectionPool(reactor, persistent=False) - self.pubnub = PubNubTwisted(pnconf, reactor=reactor, pool=self.pool) - - def tearDown(self): - return self.pool.closeCachedConnections() - - def assert_valid_cg_envelope(self, envelope, type): - self.assertIsInstance(envelope.result, type) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/groups/add_single_channel.yaml', - filter_query_parameters=['uuid']) - def test_adding_channel(self): - channel = 'cgttc' - group = 'cgttg' - - envelope = yield self.pubnub.add_channel_to_channel_group() \ - .channels(channel).channel_group(group).deferred() - - self.assert_valid_cg_envelope(envelope, PNChannelGroupsAddChannelResult) - - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/groups/remove_single_channel.yaml', - filter_query_parameters=['uuid']) - def test_removing_channel(self): - channel = 'cgttc' - group = 'cgttg' - - envelope = yield self.pubnub.remove_channel_from_channel_group() \ - .channels(channel).channel_group(group).deferred() - - self.assert_valid_cg_envelope(envelope, PNChannelGroupsRemoveChannelResult) - - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/groups/add_channels.yaml', - filter_query_parameters=['uuid']) - def test_adding_channels(self): - channel = ['cgttc0', 'cgttc1'] - group = 'cgttg' - - envelope = yield self.pubnub.add_channel_to_channel_group() \ - .channels(channel).channel_group(group).deferred() - - self.assert_valid_cg_envelope(envelope, PNChannelGroupsAddChannelResult) - - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/groups/remove_channels.yaml', - filter_query_parameters=['uuid']) - def test_removing_channels(self): - channel = ['cgttc0', 'cgttc1'] - group = 'cgttg' - - envelope = yield self.pubnub.remove_channel_from_channel_group() \ - .channels(channel).channel_group(group).deferred() - - self.assert_valid_cg_envelope(envelope, PNChannelGroupsRemoveChannelResult) - - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/groups/list_channels.yaml', - filter_query_parameters=['uuid']) - def test_list_channels(self): - group = 'cgttg' - - envelope = yield self.pubnub.list_channels_in_channel_group() \ - .channel_group(group).deferred() - - self.assert_valid_cg_envelope(envelope, PNChannelGroupsListResult) - - returnValue(envelope) diff --git a/tests/integrational/twisted/test_here_now.py b/tests/integrational/twisted/test_here_now.py deleted file mode 100644 index 0b38133d..00000000 --- a/tests/integrational/twisted/test_here_now.py +++ /dev/null @@ -1,84 +0,0 @@ -import twisted - -from twisted.internet import reactor -from twisted.internet.defer import inlineCallbacks, returnValue -from twisted.trial import unittest -from twisted.web.client import HTTPConnectionPool - -from pubnub.models.consumer.presence import PNHereNowResult - -from pubnub.pubnub_twisted import PubNubTwisted, TwistedEnvelope - -from tests.helper import pnconf -from tests.integrational.vcr_helper import pn_vcr - -twisted.internet.base.DelayedCall.debug = True - -channel = 'twisted-test' -channels = 'twisted-test-1', 'twisted-test-1' - - -class HereNowTest(unittest.TestCase): - def setUp(self): - self.pool = HTTPConnectionPool(reactor, persistent=False) - self.pubnub = PubNubTwisted(pnconf, reactor=reactor, pool=self.pool) - - def tearDown(self): - return self.pool.closeCachedConnections() - - class PNHereNowChannelData(object): - def __init__(self, channel_name, occupancy, occupants): - self.channel_name = channel_name - self.occupancy = occupancy - self.occupants = occupants - - def assert_valid_here_now_envelope(self, envelope, result_channels): - def get_uuids(here_now_channel_data): - return [here_now_channel_data.channel_name, - here_now_channel_data.occupancy, - map(lambda x: x.uuid, here_now_channel_data.occupants)] - - self.assertIsInstance(envelope, TwistedEnvelope) - self.assertIsInstance(envelope.result, PNHereNowResult) - self.assertEqual(map(get_uuids, envelope.result.channels), result_channels) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/here_now/global.yaml', - filter_query_parameters=['uuid']) - def test_global_here_now(self): - envelope = yield self.pubnub.here_now() \ - .include_uuids(True) \ - .deferred() - - self.assert_valid_here_now_envelope(envelope, - [[u'twisted-test-1', 1, [u'00de2586-7ad8-4955-b5f6-87cae3215d02']], - [u'twisted-test', 1, [u'00de2586-7ad8-4955-b5f6-87cae3215d02']]]) - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/here_now/single.yaml', - filter_query_parameters=['uuid']) - def test_here_now_single_channel(self): - envelope = yield self.pubnub.here_now() \ - .channels(channel) \ - .include_uuids(True) \ - .deferred() - - self.assert_valid_here_now_envelope(envelope, [['twisted-test', 1, [u'00de2586-7ad8-4955-b5f6-87cae3215d02']]]) - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/here_now/multiple.yaml', - filter_query_parameters=['uuid']) - def test_here_now_multiple_channels(self): - envelope = yield self.pubnub.here_now() \ - .channels(channels) \ - .include_uuids(True) \ - .deferred() - - self.assert_valid_here_now_envelope(envelope, - [[u'twisted-test-1', 1, [u'00de2586-7ad8-4955-b5f6-87cae3215d02']]]) - returnValue(envelope) diff --git a/tests/integrational/twisted/test_publish.py b/tests/integrational/twisted/test_publish.py deleted file mode 100644 index 77cee7ec..00000000 --- a/tests/integrational/twisted/test_publish.py +++ /dev/null @@ -1,183 +0,0 @@ -import twisted -import pytest - -from twisted.internet import reactor -from twisted.internet.defer import inlineCallbacks, returnValue -from twisted.trial import unittest -from twisted.web.client import HTTPConnectionPool - -from pubnub.exceptions import PubNubException -from pubnub.errors import PNERR_MESSAGE_MISSING, PNERR_CHANNEL_MISSING - -from pubnub.models.consumer.common import PNStatus -from pubnub.models.consumer.pubsub import PNPublishResult -from pubnub.pnconfiguration import PNConfiguration - -from pubnub.pubnub_twisted import PubNubTwisted, TwistedEnvelope, PubNubTwistedException - -from tests.helper import pnconf, pnconf_pam_copy, pnconf_enc_copy -from tests.integrational.vcr_helper import pn_vcr - -twisted.internet.base.DelayedCall.debug = True - -channel = 'twisted-test' - - -class PublishTestCase(unittest.TestCase): - def setUp(self): - self.pool = HTTPConnectionPool(reactor, persistent=False) - self.pubnub = PubNubTwisted(pnconf, reactor=reactor, pool=self.pool) - - def tearDown(self): - return self.pool.closeCachedConnections() - - # for async - def error_envelope_asserter(self, expected_err_msg): - def assert_error_message(envelope): - assert envelope.status.error_data.information == expected_err_msg - - return assert_error_message - - def assert_client_error(self, publish, message): - try: - publish.deferred() - except PubNubException as exception: - self.assertTrue(message in exception.message) - else: - self.fail('Expected PubNubException not raised') - - def assert_client_side_error(self, envelope, expected_err_msg): - assert envelope.status.error_data.information == expected_err_msg - - def assert_valid_publish_envelope(self, envelope): - assert isinstance(envelope, TwistedEnvelope) - assert isinstance(envelope.result, PNPublishResult) - assert isinstance(envelope.status, PNStatus) - assert envelope.result.timetoken > 0 - - @inlineCallbacks - def deferred(self, event): - envelope = yield event.deferred() - returnValue(envelope) - - @inlineCallbacks - def assert_success_publish_get(self, message, meta=None): - publish = self.pubnub.publish().channel(channel).message(message).meta(meta) - envelope = yield self.deferred(publish) - self.assert_valid_publish_envelope(envelope) - returnValue(envelope) - - @inlineCallbacks - def assert_success_encrypted_publish_get(self, message): - pubnub = PubNubTwisted(pnconf_enc_copy()) - publish = pubnub.publish().channel(channel).message(message) - envelope = yield self.deferred(publish) - self.assert_valid_publish_envelope(envelope) - returnValue(envelope) - - @inlineCallbacks - def assert_success_publish_post(self, message): - publish = self.pubnub.publish().channel(channel).message(message).use_post(True) - envelope = yield self.deferred(publish) - self.assert_valid_publish_envelope(envelope) - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/publish/mixed_via_get.yaml', - filter_query_parameters=['uuid', 'seqn']) - def test_publish_mixed_via_get(self): - d0 = yield self.assert_success_publish_get("hi") - d1 = yield self.assert_success_publish_get(5) - d2 = yield self.assert_success_publish_get(True) - d3 = yield self.assert_success_publish_get(["hi", "hi2", "hi3"]) - returnValue([d0, d1, d2, d3]) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/publish/mixed_encrypted_via_get.yaml', - filter_query_parameters=['uuid', 'seqn']) - def test_publish_mixed_encrypted_via_get(self): - d0 = yield self.assert_success_encrypted_publish_get("hi") - d1 = yield self.assert_success_encrypted_publish_get(5) - d2 = yield self.assert_success_encrypted_publish_get(True) - d3 = yield self.assert_success_encrypted_publish_get(["hi", "hi2", "hi3"]) - returnValue([d0, d1, d2, d3]) - - # TODO: uncomment this when vcr for post is fixed - # @inlineCallbacks - # @pn_vcr.use_cassette( - # 'tests/integrational/fixtures/twisted/publish/mixed_via_post.yaml', - # filter_query_parameters=['uuid', 'seqn']) - # def test_publish_mixed_via_post(self): - # d0 = yield self.assert_success_publish_post("hi") - # d1 = yield self.assert_success_publish_post(5) - # d2 = yield self.assert_success_publish_post(True) - # d3 = yield self.assert_success_publish_post(["hi", "hi2", "hi3"]) - # returnValue([d0, d1, d2, d3]) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/publish/object_via_get.yaml', - filter_query_parameters=['uuid', 'seqn']) - def test_publish_object_via_get(self): - d0 = yield self.assert_success_publish_get({"one": 2, "three": True}) - returnValue(d0) - - def test_error_missing_message(self): - self.assert_client_error( - self.pubnub.publish().channel(channel).message(None), - PNERR_MESSAGE_MISSING - ) - - def test_error_missing_channel(self): - self.assert_client_error( - self.pubnub.publish().channel('').message('whatever'), - PNERR_CHANNEL_MISSING - ) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/publish/invalid_key.yaml', - filter_query_parameters=['uuid', 'seqn']) - def test_error_invalid_key(self): - conf = PNConfiguration() - conf.publish_key = "fake" - conf.subscribe_key = "demo" - pubnub = PubNubTwisted(conf) - with pytest.raises(PubNubTwistedException) as exception: - yield pubnub.publish().channel(channel).message("hey").deferred() - - self.assertEqual(exception.value.status.error_data.information, - "HTTP Client Error (400): [0, u'Invalid Key', u'14767989321048626']") - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/publish/forbidden.yaml', - filter_query_parameters=['uuid', 'seqn', 'timestamp', 'signature']) - def test_error_forbidden(self): - pubnub = PubNubTwisted(pnconf_pam_copy()) - with pytest.raises(PubNubTwistedException) as exception: - yield pubnub.publish().channel("not_permitted_channel").message("hey").deferred() - - self.assertEqual(exception.value.status.error_data.information, - "HTTP Client Error (403): {u'status': 403, u'message': u'Forbidden', u'payload':" - " {u'channels': [u'not_permitted_channel']}, u'service': u'Access Manager', u'error': True}") - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/publish/meta_object.yaml', - filter_query_parameters=['uuid', 'seqn'], - match_on=['host', 'method', 'path', 'meta_object_in_query']) - def test_publish_with_meta(self): - yield self.assert_success_publish_get('hi', {'a': 2, 'b': True}) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/publish/do_not_store.yaml', - filter_query_parameters=['uuid', 'seqn']) - def test_publish_do_not_store(self): - publish = self.pubnub.publish().channel(channel).message('whatever').should_store(False) - envelope = yield self.deferred(publish) - self.assert_valid_publish_envelope(envelope) - returnValue(envelope) diff --git a/tests/integrational/twisted/test_state.py b/tests/integrational/twisted/test_state.py deleted file mode 100644 index 2c0c6402..00000000 --- a/tests/integrational/twisted/test_state.py +++ /dev/null @@ -1,55 +0,0 @@ -from copy import copy - -import twisted - -from twisted.internet import reactor -from twisted.internet.defer import inlineCallbacks, returnValue -from twisted.trial import unittest -from twisted.web.client import HTTPConnectionPool - -from pubnub.models.consumer.presence import PNSetStateResult - -from pubnub.pubnub_twisted import PubNubTwisted, TwistedEnvelope - -from tests.helper import pnconf -from tests.integrational.vcr_helper import pn_vcr - -twisted.internet.base.DelayedCall.debug = True - -channel = 'twisted-test' -channels = ['twisted-test-0', 'twisted-test-1'] -state = {'whatever': 'something'} - - -class StateTestCase(unittest.TestCase): - def setUp(self): - pnconf_uuid_set = copy(pnconf) - pnconf_uuid_set.uuid = 'someuuid' - self.pool = HTTPConnectionPool(reactor, persistent=False) - self.pubnub = PubNubTwisted(pnconf_uuid_set, reactor=reactor, pool=self.pool) - - def tearDown(self): - return self.pool.closeCachedConnections() - - def assert_valid_state_envelope(self, envelope): - self.assertIsInstance(envelope, TwistedEnvelope) - self.assertIsInstance(envelope.result, PNSetStateResult) - self.assertEqual(envelope.result.state, state) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/state/single_channel.yaml', - filter_query_parameters=['uuid']) - def test_state_single_channel(self): - envelope = yield self.pubnub.set_state().channels(channel).state(state).deferred() - self.assert_valid_state_envelope(envelope) - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/state/multiple_channels.yaml', - filter_query_parameters=['uuid']) - def test_state_multiple_channels(self): - envelope = yield self.pubnub.set_state().channels(channels).state(state).deferred() - self.assert_valid_state_envelope(envelope) - returnValue(envelope) diff --git a/tests/integrational/twisted/test_where_now.py b/tests/integrational/twisted/test_where_now.py deleted file mode 100644 index dea8d971..00000000 --- a/tests/integrational/twisted/test_where_now.py +++ /dev/null @@ -1,49 +0,0 @@ -import twisted - -from twisted.internet import reactor -from twisted.internet.defer import inlineCallbacks, returnValue -from twisted.trial import unittest -from twisted.web.client import HTTPConnectionPool - -from pubnub.models.consumer.presence import PNWhereNowResult - -from pubnub.pubnub_twisted import PubNubTwisted, TwistedEnvelope - -from tests.helper import pnconf -from tests.integrational.vcr_helper import pn_vcr - -twisted.internet.base.DelayedCall.debug = True - -uuid_looking_for = '00de2586-7ad8-4955-b5f6-87cae3215d02' - - -class WhereNowTestCase(unittest.TestCase): - def setUp(self): - self.pool = HTTPConnectionPool(reactor, persistent=False) - self.pubnub = PubNubTwisted(pnconf, reactor=reactor, pool=self.pool) - - def tearDown(self): - return self.pool.closeCachedConnections() - - def assert_valid_where_now_envelope(self, envelope, channels): - self.assertIsInstance(envelope, TwistedEnvelope) - self.assertIsInstance(envelope.result, PNWhereNowResult) - self.assertEqual(envelope.result.channels, channels) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/where_now/single.yaml', - filter_query_parameters=['uuid']) - def test_where_now_single_channel(self): - envelope = yield self.pubnub.where_now().uuid(uuid_looking_for).deferred() - self.assert_valid_where_now_envelope(envelope, [u'twisted-test-1']) - returnValue(envelope) - - @inlineCallbacks - @pn_vcr.use_cassette( - 'tests/integrational/fixtures/twisted/where_now/multiple.yaml', - filter_query_parameters=['uuid']) - def test_where_now_multiple_channels(self): - envelope = yield self.pubnub.where_now().uuid(uuid_looking_for).deferred() - self.assert_valid_where_now_envelope(envelope, [u'twisted-test-2', u'twisted-test-1']) - returnValue(envelope) diff --git a/tests/integrational/vcr_asyncio_sleeper.py b/tests/integrational/vcr_asyncio_sleeper.py index 0068f745..48cd98da 100644 --- a/tests/integrational/vcr_asyncio_sleeper.py +++ b/tests/integrational/vcr_asyncio_sleeper.py @@ -1,9 +1,5 @@ -""" -Placed into the separate file to avoid python <3.4 tests using it -""" -import six - -from pubnub.exceptions import PubNubException +from functools import wraps +from vcr.errors import CannotOverwriteExistingCassetteException from pubnub.pubnub_asyncio import SubscribeListener, AsyncioReconnectionManager from tests.integrational.vcr_helper import pn_vcr @@ -19,14 +15,13 @@ def get_sleeper(cassette_name): import asyncio - @asyncio.coroutine - def fake_sleeper(v): - yield from asyncio.sleep(0) + async def fake_sleeper(v): + await asyncio.sleep(0) def decorate(f): - @six.wraps(f) - def call(*args, event_loop=None): - yield from f(*args, sleeper=(fake_sleeper if (len(cs) > 0) else asyncio.sleep), event_loop=event_loop) + @wraps(f) + async def call(*args, event_loop=None): + await f(*args, sleeper=(fake_sleeper if (len(cs) > 0) else asyncio.sleep), event_loop=event_loop) return call return decorate @@ -45,22 +40,18 @@ class VCR599Listener(SubscribeListener): This means if you use this listener you should determine the amount of 599 errors can be raised by you own and explicitly pass it to constructor. """ - - import asyncio - def __init__(self, raise_times): self.silent_limit = raise_times self.raised_times = 0 super(VCR599Listener, self).__init__() - @asyncio.coroutine - def _wait_for(self, coro): + async def _wait_for(self, coro): try: - res = yield from super(VCR599Listener, self)._wait_for(coro) + res = await super(VCR599Listener, self)._wait_for(coro) return res - except PubNubException as e: - if 'HTTP Server Error (599)' in str(e): + except CannotOverwriteExistingCassetteException as e: + if "Can't overwrite existing cassette" in str(e): self.raised_times += 1 if self.raised_times > self.silent_limit: raise e diff --git a/tests/integrational/vcr_helper.py b/tests/integrational/vcr_helper.py index 36e2feb9..f93be945 100644 --- a/tests/integrational/vcr_helper.py +++ b/tests/integrational/vcr_helper.py @@ -1,11 +1,10 @@ import json import os -import six import vcr -try: - from mock import patch -except ImportError: - from unittest.mock import patch + +from tests.helper import gen_decrypt_func +from unittest.mock import patch +from functools import wraps from tests.helper import url_decode @@ -53,6 +52,10 @@ def assert_request_equal_with_object_in_query(r1, r2, query_field_name): return True +def object_in_path_with_decrypt_matcher(r1, r2): + return object_in_path_matcher(r1, r2, decrypter=gen_decrypt_func()) + + def object_in_path_matcher(r1, r2, decrypter=None): try: path1 = r1.path.split('/') @@ -60,7 +63,7 @@ def object_in_path_matcher(r1, r2, decrypter=None): for k, v in enumerate(path1): if k == (len(path1) - 1): - if decrypter is not None: + if decrypter: assert decrypter(url_decode(v)) == decrypter(url_decode(path2[k])) else: assert json.loads(url_decode(v)) == json.loads(url_decode(path2[k])) @@ -73,6 +76,10 @@ def object_in_path_matcher(r1, r2, decrypter=None): return True +def object_in_body_with_decrypt_matcher(r1, r2): + return object_in_body_matcher(r1, r2, decrypter=gen_decrypt_func()) + + def object_in_body_matcher(r1, r2, decrypter=None): try: if decrypter is not None: @@ -95,7 +102,7 @@ def string_list_in_path_matcher(r1, r2, positions=None): if positions is None: positions = [] - elif isinstance(positions, six.integer_types): + elif isinstance(positions, int): positions = [positions] try: @@ -134,12 +141,12 @@ def string_list_in_query_matcher(r1, r2, list_keys=None, filter_keys=None): if list_keys is None: list_keys = [] - elif isinstance(list_keys, six.string_types): + elif isinstance(list_keys, str): list_keys = [list_keys] if filter_keys is None: filter_keys = [] - elif isinstance(filter_keys, six.string_types): + elif isinstance(filter_keys, str): filter_keys = [filter_keys] try: @@ -192,6 +199,8 @@ def check_the_difference_matcher(r1, r2): pn_vcr.register_matcher('meta_object_in_query', meta_object_in_query_matcher) pn_vcr.register_matcher('state_object_in_query', state_object_in_query_matcher) pn_vcr.register_matcher('object_in_path', object_in_path_matcher) +pn_vcr.register_matcher('object_in_path_with_decrypt', object_in_path_with_decrypt_matcher) +pn_vcr.register_matcher('object_in_body_with_decrypt', object_in_body_with_decrypt_matcher) pn_vcr.register_matcher('object_in_body', object_in_body_matcher) pn_vcr.register_matcher('check_the_difference', check_the_difference_matcher) pn_vcr.register_matcher('string_list_in_path', string_list_in_path_matcher) @@ -205,7 +214,7 @@ def use_cassette_and_stub_time_sleep_native(cassette_name, **kwargs): def _inner(f): @patch('time.sleep', return_value=None) - @six.wraps(f) + @wraps(f) def stubbed(*args, **kwargs): with context: largs = list(args) @@ -213,7 +222,7 @@ def stubbed(*args, **kwargs): largs.pop(1) return f(*largs, **kwargs) - @six.wraps(f) + @wraps(f) def original(*args): with context: return f(*args) diff --git a/tests/manual/asyncio/test_reconnections.py b/tests/manual/asyncio/test_reconnections.py index 6a8fa456..ad10eebc 100644 --- a/tests/manual/asyncio/test_reconnections.py +++ b/tests/manual/asyncio/test_reconnections.py @@ -26,28 +26,25 @@ def presence(self, pubnub, presence): @pytest.mark.asyncio -def test_blah(): +async def test_blah(): pnconf = pnconf_sub_copy() assert isinstance(pnconf, PNConfiguration) pnconf.reconnect_policy = PNReconnectionPolicy.EXPONENTIAL pubnub = PubNubAsyncio(pnconf) time_until_open_again = 8 - @asyncio.coroutine - def close_soon(): - yield from asyncio.sleep(2) + async def close_soon(): + await asyncio.sleep(2) pubnub._connector.close() print(">>> connection is broken") - @asyncio.coroutine - def open_again(): - yield from asyncio.sleep(time_until_open_again) + async def open_again(): + await asyncio.sleep(time_until_open_again) pubnub.set_connector(aiohttp.TCPConnector(conn_timeout=pubnub.config.connect_timeout, verify_ssl=True)) print(">>> connection is open again") - @asyncio.coroutine - def countdown(): - asyncio.sleep(2) + async def countdown(): + await asyncio.sleep(2) opened = False count = time_until_open_again @@ -56,7 +53,7 @@ def countdown(): count -= 1 if count <= 0: break - yield from asyncio.sleep(1) + await asyncio.sleep(1) my_listener = MySubscribeCallback() pubnub.add_listener(my_listener) @@ -66,4 +63,4 @@ def countdown(): asyncio.ensure_future(open_again()) asyncio.ensure_future(countdown()) - yield from asyncio.sleep(1000) + await asyncio.sleep(1000) diff --git a/tests/manual/tornado/__init__.py b/tests/manual/tornado/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/manual/tornado/subscribe_stub.py b/tests/manual/tornado/subscribe_stub.py deleted file mode 100644 index 901e87f0..00000000 --- a/tests/manual/tornado/subscribe_stub.py +++ /dev/null @@ -1,66 +0,0 @@ -import time -import tornado - -from tornado import web -from tornado import gen - -# pn.set_stream_logger('pubnub', logging.DEBUG) - -ioloop = tornado.ioloop.IOLoop.current() - - -class SubscribeHandler(web.RequestHandler): - def timestamp(self): - return int(time.time() * 10000000) - - @gen.coroutine - def get(self): - tt = self.get_argument('tt') - - if tt is None: - raise gen.Return(self.send_error(500, message={ - "error": "Channel missing" - })) - - tt = int(tt) - - if tt > 0: - yield gen.sleep(5000) - - self.write('{"t":{"t":"%d","r":12},"m":[]}' % self.timestamp()) - - -class HeartbeatHandler(web.RequestHandler): - def timestamp(self): - return int(time.time() * 10000000) - - @gen.coroutine - def get(self): - self.write('{"status": 200, "message": "OK", "service": "Presence"}') - - -class TimeHandler(web.RequestHandler): - def timestamp(self): - return int(time.time() * 10000000) - - @gen.coroutine - def get(self): - self.write('[%d]' % self.timestamp()) - - -def main(): - app = web.Application( - [ - (r"/v2/subscribe/demo/my_channel/0", SubscribeHandler), - (r"/v2/presence/sub-key/demo/channel/my_channel/heartbeat", HeartbeatHandler), - (r"/time/0", TimeHandler), - ], - cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__", - xsrf_cookies=True, - ) - app.listen(8089) - ioloop.start() - - -if __name__ == "__main__": - main() diff --git a/tests/manual/tornado/test_reconnections.py b/tests/manual/tornado/test_reconnections.py deleted file mode 100644 index 847b5379..00000000 --- a/tests/manual/tornado/test_reconnections.py +++ /dev/null @@ -1,73 +0,0 @@ -import tornado -import logging -from tornado import gen -from tornado.testing import AsyncTestCase -import pubnub as pn - -from pubnub.callbacks import SubscribeCallback -from pubnub.enums import PNReconnectionPolicy -from pubnub.pnconfiguration import PNConfiguration -from pubnub.pubnub_tornado import PubNubTornado - - -pn.set_stream_logger('pubnub', logging.DEBUG) - - -class MySubscribeCallback(SubscribeCallback): - def status(self, pubnub, status): - pass - - def message(self, pubnub, message): - pass - - def presence(self, pubnub, presence): - pass - - -class TestPubNubReconnection(AsyncTestCase): - """ - Tornado Reconnection Manager test design to be invoked alongside with 'subscribe_stub.py' - helper to start and drop a connection. - """ - @tornado.testing.gen_test(timeout=300) - def test_reconnection(self): - pnconf = PNConfiguration() - pnconf.publish_key = "demo" - pnconf.subscribe_key = "demo" - pnconf.origin = "localhost:8089" - pnconf.subscribe_request_timeout = 10 - pnconf.reconnect_policy = PNReconnectionPolicy.LINEAR - pubnub = PubNubTornado(pnconf, custom_ioloop=self.io_loop) - time_until_open_again = 10 - - @gen.coroutine - def close_soon(): - yield gen.sleep(3) - pubnub.http.close() - pubnub.http = None - print(">>> connection is broken") - - @gen.coroutine - def open_again(): - yield gen.sleep(time_until_open_again) - pubnub.http = tornado.httpclient.AsyncHTTPClient(max_clients=PubNubTornado.MAX_CLIENTS) - print(">>> connection is open again") - - @gen.coroutine - def countdown(): - yield gen.sleep(2) - opened = False - count = time_until_open_again - - while not opened: - print(">>> %ds to open again" % count) - count -= 1 - if count <= 0: - break - yield gen.sleep(1) - - my_listener = MySubscribeCallback() - pubnub.add_listener(my_listener) - pubnub.subscribe().channels('my_channel').execute() - - yield gen.sleep(1000) diff --git a/tests/unit/test_crypto.py b/tests/unit/test_crypto.py index 0d2abe21..9c0a9073 100644 --- a/tests/unit/test_crypto.py +++ b/tests/unit/test_crypto.py @@ -1,5 +1,3 @@ -import sys - from pubnub.pubnub import PubNub from pubnub.crypto import PubNubCryptodome from tests.helper import gen_decrypt_func @@ -10,11 +8,6 @@ plaintext_message = "hey-0" KEY = 'testKey' -if sys.version_info > (3, 0): - v = 3 -else: - v = 2 - class TestPubNubCryptodome: def test_decode_aes(self): @@ -33,7 +26,7 @@ def test_vc_body_decoder(self): input = b'"9P/7+NNs54o7Go41yh+3rIn8BW0H0ad+mKlKTKGw2i1eoQP1ddHrnIzkRUPEC3ko"' # print(json.loads(input.decode('utf-8'))) assert {"name": "Alex", "online": True} == \ - gen_decrypt_func('testKey')(input.decode('utf-8')) + gen_decrypt_func()(input.decode('utf-8')) def test_message_encryption_with_random_iv(self, pn_crypto=crypto): encrypted = pn_crypto.encrypt(KEY, plaintext_message, use_random_iv=True) @@ -69,8 +62,4 @@ def test_encrypt_and_decrypt_file(self, file_for_upload, file_upload_test_data): encrypted_file = pubnub.encrypt(KEY, fd.read()) decrypted_file = pubnub.decrypt(KEY, encrypted_file) - - if v == 3: - assert file_upload_test_data["FILE_CONTENT"] == decrypted_file.decode("utf-8") - else: - assert file_upload_test_data["FILE_CONTENT"] == decrypted_file + assert file_upload_test_data["FILE_CONTENT"] == decrypted_file.decode("utf-8")