Пример #1
0
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)
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)
Пример #3
0
    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}")
Пример #4
0
    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']")
Пример #5
0
    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}"
        )
Пример #6
0
    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']"
        )
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()
Пример #8
0
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()
Пример #9
0
 def setUp(self):
     self.pool = HTTPConnectionPool(reactor, persistent=False)
     self.pubnub = PubNubTwisted(pnconf, reactor=reactor, pool=self.pool)
Пример #10
0
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)
Пример #11
0
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)
Пример #12
0
 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)
Пример #13
0
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)
Пример #14
0
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)
Пример #15
0
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()
Пример #16
0
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)
Пример #17
0
 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)
Пример #18
0
 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)
Пример #19
0
 def setUp(self):
     self.pool = HTTPConnectionPool(reactor, persistent=False)
     self.pubnub = PubNubTwisted(pnconf, reactor=reactor, pool=self.pool)
Пример #20
0
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()
Пример #21
0
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)