Exemple #1
0
    def test_time_without_key_or_token(self):
        ably = AblyRest(Options(host=test_vars["host"],
                port=test_vars["port"],
                tls_port=test_vars["tls_port"],
                tls=test_vars["tls"]))

        ably.time()
Exemple #2
0
    async def test_timeout(self):
        # Timeout
        timeout = 0.000001
        ably = AblyRest(token="foo", http_request_timeout=timeout)
        assert ably.http.http_request_timeout == timeout
        with pytest.raises(httpx.ReadTimeout):
            await ably.request('GET', '/time')
        await ably.close()

        # Bad host, use fallback
        ably = AblyRest(key=self.test_vars["keys"][0]["key_str"],
                        rest_host='some.other.host',
                        port=self.test_vars["port"],
                        tls_port=self.test_vars["tls_port"],
                        tls=self.test_vars["tls"],
                        fallback_hosts_use_default=True)
        result = await ably.request('GET', '/time')
        assert isinstance(result, HttpPaginatedResponse)
        assert len(result.items) == 1
        assert isinstance(result.items[0], int)
        await ably.close()

        # Bad host, no Fallback
        ably = AblyRest(key=self.test_vars["keys"][0]["key_str"],
                        rest_host='some.other.host',
                        port=self.test_vars["port"],
                        tls_port=self.test_vars["tls_port"],
                        tls=self.test_vars["tls"])
        with pytest.raises(httpx.ConnectError):
            await ably.request('GET', '/time')
        await ably.close()
Exemple #3
0
    def test_auth_init_with_token_callback(self):
        callback_called = []

        def token_callback(**params):
            callback_called.append(True)
            return "this_is_not_really_a_token_request"

        options = Options()
        options.key_id = test_vars["keys"][0]["key_id"]
        options.host = test_vars["host"]
        options.port = test_vars["port"]
        options.tls_port = test_vars["tls_port"]
        options.tls = test_vars["tls"]
        options.auth_callback = token_callback

        ably = AblyRest(options)

        try:
            ably.stats(None)
        except:
            pass

        self.assertTrue(callback_called, msg="Token callback not called")
        self.assertEqual(Auth.Method.TOKEN, ably.auth.auth_method,
                msg="Unexpected Auth method mismatch")
Exemple #4
0
 def __init__(self, args, ably_auth_url=None, post_reporter=None):
     self.args = args
     self.post_reporter = post_reporter
     channel_name = u'com.openagua.update_s{}n{}'.format(
         args.source_id, args.network_id)
     if ably_auth_url:
         logging.getLogger('ably').setLevel(logging.CRITICAL)
         logger = logging.getLogger('ably')
         logger.addHandler(logging.StreamHandler())
         client_id = args.hydra_username
         model_secret = environ.get('MODEL_SECRET')
         rest = AblyRest(auth_url=ably_auth_url,
                         auth_params={
                             'client_id': client_id,
                             'model_secret': model_secret
                         })
     # elif ably_token_request:
     #     rest = AblyRest(token=ably_token_request)
     else:
         ably_api_key = environ.get('ABLY_API_KEY')
         if ably_api_key:
             rest = AblyRest(key=environ.get('ABLY_API_KEY'))
         else:
             self.channel = None
             return
     self.channel = rest.channels.get(channel_name)
     self.updater = None
Exemple #5
0
    def test_rest_host_and_environment(self):
        # rest host
        ably = AblyRest(token='foo', rest_host="some.other.host")
        self.assertEqual("some.other.host",
                         ably.options.rest_host,
                         msg="Unexpected host mismatch")

        # environment: production
        ably = AblyRest(token='foo', environment="production")
        host = ably.options.get_rest_host()
        self.assertEqual("rest.ably.io",
                         host,
                         msg="Unexpected host mismatch %s" % host)

        # environment: other
        ably = AblyRest(token='foo', environment="sandbox")
        host = ably.options.get_rest_host()
        self.assertEqual("sandbox-rest.ably.io",
                         host,
                         msg="Unexpected host mismatch %s" % host)

        # both, as per #TO3k2
        with self.assertRaises(ValueError):
            ably = AblyRest(token='foo',
                            rest_host="some.other.host",
                            environment="some.other.environment")
    def test_fallback_hosts(self):
        # Specify the fallback_hosts (RSC15a)
        fallback_hosts = [
            ['fallback1.com', 'fallback2.com'],
            [],
        ]

        for aux in fallback_hosts:
            ably = AblyRest(token='foo', fallback_hosts=aux)
            assert sorted(aux) == sorted(
                ably.options.get_fallback_rest_hosts())

        # Specify environment
        ably = AblyRest(token='foo', environment='sandbox')
        assert [] == sorted(ably.options.get_fallback_rest_hosts())

        # Specify environment and fallback_hosts_use_default
        # We specify http_max_retry_count=10 so all the fallback hosts get in the list
        ably = AblyRest(token='foo',
                        environment='sandbox',
                        fallback_hosts_use_default=True,
                        http_max_retry_count=10)
        assert sorted(Defaults.fallback_hosts) == sorted(
            ably.options.get_fallback_rest_hosts())

        # RSC15f
        ably = AblyRest(token='foo')
        assert 600000 == ably.options.fallback_retry_timeout
        ably = AblyRest(token='foo', fallback_retry_timeout=1000)
        assert 1000 == ably.options.fallback_retry_timeout
 def setUp(self):
     options = {
         "key": test_vars["keys"][0]["key_str"],
         "rest_host": test_vars["host"],
         "port": test_vars["port"],
         "tls_port": test_vars["tls_port"],
         "tls": test_vars["tls"],
     }
     self.ably = AblyRest(**options)
     self.ably2 = AblyRest(**options)
 def test_enviroment(self):
     ably = AblyRest(token='token', environment='custom')
     with patch.object(Session, 'prepare_request',
                       wraps=ably.http._Http__session.prepare_request) as get_mock:
         try:
             ably.time()
         except AblyException:
             pass
         request = get_mock.call_args_list[0][0][0]
         self.assertEquals(request.url, 'https://custom-rest.ably.io:443/time')
Exemple #9
0
    def test_time_accuracy(self):
        ably = AblyRest(Options.with_key(test_vars["keys"][0]["key_str"],
                host=test_vars["host"],
                port=test_vars["port"],
                tls_port=test_vars["tls_port"],
                tls=test_vars["tls"]))

        reported_time = ably.time()
        actual_time = time.time() * 1000.0

        self.assertLess(abs(actual_time - reported_time), 2000,
                msg="Time is not within 2 seconds")
Exemple #10
0
 def test_enviroment(self):
     ably = AblyRest(token='token', environment='custom')
     with patch.object(
             Session,
             'prepare_request',
             wraps=ably.http._Http__session.prepare_request) as get_mock:
         try:
             ably.time()
         except AblyException:
             pass
         request = get_mock.call_args_list[0][0][0]
         assert request.url == 'https://custom-rest.ably.io:443/time'
Exemple #11
0
 def setUp(self):
     self.ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                          rest_host=test_vars["host"],
                          port=test_vars["port"],
                          tls_port=test_vars["tls_port"],
                          tls=test_vars["tls"])
     self.ably_with_client_id = AblyRest(
         key=test_vars["keys"][0]["key_str"],
         rest_host=test_vars["host"],
         port=test_vars["port"],
         tls_port=test_vars["tls_port"],
         tls=test_vars["tls"],
         client_id=uuid.uuid4().hex)
    def test_time_without_key_or_token(self):
        ably = AblyRest(token='foo',
                        rest_host=test_vars["host"],
                        port=test_vars["port"],
                        tls_port=test_vars["tls_port"],
                        tls=test_vars["tls"],
                        use_binary_protocol=self.use_binary_protocol)

        reported_time = ably.time()
        actual_time = time.time() * 1000.0

        self.assertLess(abs(actual_time - reported_time), 2000,
                msg="Time is not within 2 seconds")
    def test_time_accuracy(self):
        ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                        rest_host=test_vars["host"],
                        port=test_vars["port"],
                        tls_port=test_vars["tls_port"],
                        tls=test_vars["tls"],
                        use_binary_protocol=self.use_binary_protocol)

        reported_time = ably.time()
        actual_time = time.time() * 1000.0

        self.assertLess(abs(actual_time - reported_time), 2000,
                msg="Time is not within 2 seconds")
Exemple #14
0
    def test_timeout(self):
        # Timeout
        timeout = 0.000001
        ably = AblyRest(token="foo", http_request_timeout=timeout)
        assert ably.http.http_request_timeout == timeout
        with pytest.raises(requests.exceptions.ReadTimeout):
            ably.request('GET', '/time')

        # Bad host, use fallback
        ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                        rest_host='some.other.host',
                        port=test_vars["port"],
                        tls_port=test_vars["tls_port"],
                        tls=test_vars["tls"],
                        fallback_hosts_use_default=True)
        result = ably.request('GET', '/time')
        assert isinstance(result, HttpPaginatedResponse)
        assert len(result.items) == 1
        assert isinstance(result.items[0], int)

        # Bad host, no Fallback
        ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                        rest_host='some.other.host',
                        port=test_vars["port"],
                        tls_port=test_vars["tls_port"],
                        tls=test_vars["tls"])
        with pytest.raises(requests.exceptions.ConnectionError):
            ably.request('GET', '/time')
    def test_time_without_key_or_token(self):
        ably = AblyRest(token='foo',
                        rest_host=test_vars["host"],
                        port=test_vars["port"],
                        tls_port=test_vars["tls_port"],
                        tls=test_vars["tls"],
                        use_binary_protocol=self.use_binary_protocol)

        reported_time = ably.time()
        actual_time = time.time() * 1000.0

        self.assertLess(abs(actual_time - reported_time),
                        2000,
                        msg="Time is not within 2 seconds")
    def test_time_accuracy(self):
        ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                        rest_host=test_vars["host"],
                        port=test_vars["port"],
                        tls_port=test_vars["tls_port"],
                        tls=test_vars["tls"],
                        use_binary_protocol=self.use_binary_protocol)

        reported_time = ably.time()
        actual_time = time.time() * 1000.0

        self.assertLess(abs(actual_time - reported_time),
                        2000,
                        msg="Time is not within 2 seconds")
Exemple #17
0
 def test_auth_init_key_only(self):
     ably = AblyRest(key=test_vars["keys"][0]["key_str"])
     assert Auth.Method.BASIC == ably.auth.auth_mechanism, "Unexpected Auth method mismatch"
     assert ably.auth.auth_options.key_name == test_vars["keys"][0][
         'key_name']
     assert ably.auth.auth_options.key_secret == test_vars["keys"][0][
         'key_secret']
    def test_time_fails_without_valid_host(self):
        ably = AblyRest(token='foo',
                        rest_host="this.host.does.not.exist",
                        port=test_vars["port"],
                        tls_port=test_vars["tls_port"])

        self.assertRaises(AblyException, ably.time)
 def test_requests_over_http_production(self):
     ably = AblyRest(token='token', tls=False)
     self.assertEquals(
         'http://rest.ably.io',
         '{0}://{1}'.format(ably.http.preferred_scheme,
                            ably.http.preferred_host))
     self.assertEqual(ably.http.preferred_port, 80)
 def test_tls_can_be_disabled(self):
     ably = AblyRest(token='foo', tls=False)
     self.assertFalse(ably.options.tls,
                      msg="Expected encryption to be False")
     self.assertEqual(Defaults.port,
                      Defaults.get_port(ably.options),
                      msg="Unexpected port mismatch")
 def test_tls_defaults_to_true(self):
     ably = AblyRest(token='foo')
     self.assertTrue(ably.options.tls,
                     msg="Expected encryption to default to true")
     self.assertEqual(Defaults.tls_port,
                      Defaults.get_port(ably.options),
                      msg="Unexpected port mismatch")
    def test_no_retry_if_not_500_to_599_http_code(self):
        default_host = Defaults.get_rest_host(Options())
        ably = AblyRest(token="foo")
        self.assertIn('http_max_retry_count',
                      ably.http.CONNECTION_RETRY_DEFAULTS)

        default_url = "%s://%s:%d/" % (ably.http.preferred_scheme,
                                       default_host, ably.http.preferred_port)

        def raise_ably_exception(*args, **kwagrs):
            raise AblyException(message="", status_code=600, code=50500)

        with mock.patch('requests.Request',
                        wraps=requests.Request) as request_mock:
            with mock.patch(
                    'ably.util.exceptions.AblyException.raise_for_response',
                    side_effect=raise_ably_exception) as send_mock:
                with self.assertRaises(AblyException):
                    ably.http.make_request('GET', '/', skip_auth=True)

                self.assertEqual(send_mock.call_count, 1)
                self.assertEqual(
                    request_mock.call_args,
                    mock.call(mock.ANY,
                              default_url,
                              data=mock.ANY,
                              headers=mock.ANY))
Exemple #23
0
    async def test_host_fallback(self):
        ably = AblyRest(token="foo")

        def make_url(host):
            base_url = "%s://%s:%d" % (ably.http.preferred_scheme, host,
                                       ably.http.preferred_port)
            return urljoin(base_url, '/')

        with mock.patch('httpx.Request', wraps=httpx.Request) as request_mock:
            with mock.patch('httpx.AsyncClient.send',
                            side_effect=httpx.RequestError('')) as send_mock:
                with pytest.raises(httpx.RequestError):
                    await ably.http.make_request('GET', '/', skip_auth=True)

                assert send_mock.call_count == Defaults.http_max_retry_count

                expected_urls_set = {
                    make_url(host)
                    for host in Options(
                        http_max_retry_count=10).get_rest_hosts()
                }
                for ((_, url), _) in request_mock.call_args_list:
                    assert url in expected_urls_set
                    expected_urls_set.remove(url)

                expected_hosts_set = set(
                    Options(http_max_retry_count=10).get_rest_hosts())
                for (prep_request_tuple, _) in send_mock.call_args_list:
                    assert prep_request_tuple[0].headers.get(
                        'host') in expected_hosts_set
                    expected_hosts_set.remove(
                        prep_request_tuple[0].headers.get('host'))
        await ably.close()
Exemple #24
0
    def test_with_auth_url_headers_and_params_GET(self):

        url = 'http://www.example.com'
        headers = {'foo': 'bar'}
        self.ably = AblyRest(auth_url=url,
                             rest_host=test_vars["host"],
                             port=test_vars["port"],
                             tls_port=test_vars["tls_port"],
                             tls=test_vars["tls"],
                             auth_headers={'this': 'will_not_be_used'},
                             auth_params={'this': 'will_not_be_used'})

        auth_params = {'foo': 'auth', 'spam': 'eggs'}
        token_params = {'foo': 'token'}

        responses.add(responses.GET, url, json={'issued': 1, 'token':
                                                'another_token_string'})
        token_details = self.ably.auth.request_token(
            token_params=token_params, auth_url=url, auth_headers=headers,
            auth_params=auth_params)
        self.assertEquals('another_token_string', token_details.token)
        request = responses.calls[0].request
        self.assertEquals(request.headers['foo'], 'bar')
        self.assertNotIn('this', request.headers)
        self.assertEquals(parse_qs(urlparse(request.url).query),
                          {'foo': ['token'], 'spam': ['eggs']})
        self.assertFalse(request.body)
Exemple #25
0
 def test_with_token_str_http(self):
     token = self.ably.auth.authorise()
     token = token.token
     ably = AblyRest(token=token, rest_host=test_vars["host"],
                     port=test_vars["port"], tls_port=test_vars["tls_port"],
                     tls=False, use_binary_protocol=self.use_binary_protocol)
     ably.channels.test_auth_with_token_str.publish('event', 'foo_bar')
    def test_host_fallback(self):
        ably = AblyRest(token="foo")
        self.assertIn('http_max_retry_count',
                      ably.http.CONNECTION_RETRY_DEFAULTS)

        def make_url(host):
            base_url = "%s://%s:%d" % (ably.http.preferred_scheme, host,
                                       ably.http.preferred_port)
            return urljoin(base_url, '/')

        with mock.patch('requests.Request',
                        wraps=requests.Request) as request_mock:
            with mock.patch('requests.sessions.Session.send',
                            side_effect=requests.exceptions.RequestException
                            ) as send_mock:
                with self.assertRaises(requests.exceptions.RequestException):
                    ably.http.make_request('GET', '/', skip_auth=True)

                self.assertEqual(
                    send_mock.call_count, ably.http.
                    CONNECTION_RETRY_DEFAULTS['http_max_retry_count'])

                expected_urls_set = set([
                    make_url(host)
                    for host in ([ably.http.preferred_host] +
                                 Defaults.get_fallback_rest_hosts(Options()))
                ])
                for ((__, url), ___) in request_mock.call_args_list:
                    self.assertIn(url, expected_urls_set)
                    expected_urls_set.remove(url)
    def test_max_retry_attempts_and_timeouts_defaults(self):
        ably = AblyRest(token="foo")
        self.assertIn('http_open_timeout', ably.http.CONNECTION_RETRY_DEFAULTS)
        self.assertIn('http_request_timeout',
                      ably.http.CONNECTION_RETRY_DEFAULTS)
        self.assertIn('http_max_retry_count',
                      ably.http.CONNECTION_RETRY_DEFAULTS)

        with mock.patch(
                'requests.sessions.Session.send',
                side_effect=requests.exceptions.RequestException) as send_mock:
            with self.assertRaises(requests.exceptions.RequestException):
                ably.http.make_request('GET', '/', skip_auth=True)

            self.assertEqual(
                send_mock.call_count,
                ably.http.CONNECTION_RETRY_DEFAULTS['http_max_retry_count'])
            self.assertEqual(
                send_mock.call_args,
                mock.call(
                    mock.ANY,
                    timeout=(
                        ably.http.
                        CONNECTION_RETRY_DEFAULTS['http_open_timeout'],
                        ably.http.
                        CONNECTION_RETRY_DEFAULTS['http_request_timeout'])))
Exemple #28
0
    def test_host_fallback(self):
        ably = AblyRest(token="foo")

        def make_url(host):
            base_url = "%s://%s:%d" % (ably.http.preferred_scheme, host,
                                       ably.http.preferred_port)
            return urljoin(base_url, '/')

        with mock.patch('requests.Request',
                        wraps=requests.Request) as request_mock:
            with mock.patch('requests.sessions.Session.send',
                            side_effect=requests.exceptions.RequestException
                            ) as send_mock:
                with pytest.raises(requests.exceptions.RequestException):
                    ably.http.make_request('GET', '/', skip_auth=True)

                assert send_mock.call_count == Defaults.http_max_retry_count

                expected_urls_set = set([
                    make_url(host) for host in Options(
                        http_max_retry_count=10).get_rest_hosts()
                ])
                for ((__, url), ___) in request_mock.call_args_list:
                    assert url in expected_urls_set
                    expected_urls_set.remove(url)
 def test_specified_tls_port(self):
     ably = AblyRest(token='foo', tls_port=9999, tls=True)
     self.assertEqual(
         9999,
         Defaults.get_port(ably.options),
         msg="Unexpected port mismatch. Expected: 9999. Actual: %d" %
         ably.options.tls_port)
 def setUpClass(cls):
     cls.ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                         rest_host=test_vars["host"],
                         port=test_vars["port"],
                         tls_port=test_vars["tls_port"],
                         tls=test_vars["tls"])
     cls.time_offset = cls.ably.time() - int(time.time())
Exemple #31
0
    def test_with_auth_url_headers_and_params_POST(self):
        url = 'http://www.example.com'
        headers = {'foo': 'bar'}
        self.ably = AblyRest(auth_url=url,
                             rest_host=test_vars["host"],
                             port=test_vars["port"],
                             tls_port=test_vars["tls_port"],
                             tls=test_vars["tls"])

        auth_params = {'foo': 'auth', 'spam': 'eggs'}
        token_params = {'foo': 'token'}

        responses.add(responses.POST, url, body='token_string')
        token_details = self.ably.auth.request_token(
            token_params=token_params, auth_url=url, auth_headers=headers,
            auth_method='POST', auth_params=auth_params)

        self.assertIsInstance(token_details, TokenDetails)
        self.assertEquals(len(responses.calls), 1)
        request = responses.calls[0].request
        self.assertEquals(request.headers['content-type'],
                          'application/x-www-form-urlencoded')
        self.assertEquals(headers['foo'], request.headers['foo'])
        self.assertEquals(urlparse(request.url).query, '')  # No querystring!
        self.assertEquals(parse_qs(request.body),  # TokenParams has precedence
                          {'foo': ['token'], 'spam': ['eggs']})
        self.assertEquals('token_string', token_details.token)
 def __init__(self, args, post_reporter):
     self.args = args
     self.post_reporter = post_reporter
     channel_name = u'com.openagua.update_s{}n{}'.format(args.source_id, args.network_id)
     rest = AblyRest(args.report_api_key)
     self.channel = rest.channels.get(channel_name)
     self.updater = None
Exemple #33
0
 def setUpClass(cls):
     cls.ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                         rest_host=test_vars["host"],
                         port=test_vars["port"],
                         tls_port=test_vars["tls_port"],
                         tls=test_vars["tls"],
                         use_binary_protocol=False)
Exemple #34
0
 def setUp(self):
     self.ably = AblyRest(test_vars["keys"][0]["key_str"],
                          rest_host=test_vars["host"],
                          port=test_vars["port"],
                          tls_port=test_vars["tls_port"],
                          tls=test_vars["tls"])
     self.per_protocol_setup(True)
    def test_wildcard_client_id_can_publish_as_others(self):
        wildcard_token_details = self.ably.auth.request_token(
            {'client_id': '*'})
        wildcard_ably = AblyRest(token_details=wildcard_token_details,
                                 rest_host=test_vars["host"],
                                 port=test_vars["port"],
                                 tls_port=test_vars["tls_port"],
                                 tls=test_vars["tls"],
                                 use_binary_protocol=self.use_binary_protocol)

        self.assertEqual(wildcard_ably.auth.client_id, '*')
        channel = wildcard_ably.channels[self.protocol_channel_name(
            'persisted:wildcard_client_id')]
        channel.publish(name='publish1', data='no client_id')
        some_client_id = uuid.uuid4().hex
        channel.publish(name='publish2',
                        data='some client_id',
                        client_id=some_client_id)

        history = channel.history()
        messages = history.items

        self.assertIsNotNone(messages, msg="Expected non-None messages")
        self.assertEqual(len(messages), 2, msg="Expected 2 messages")

        self.assertEqual(messages[0].client_id, some_client_id)
        self.assertIsNone(messages[1].client_id)
    def test_with_callback(self):
        called_token_params = {'ttl': '3600'}

        def callback(token_params):
            self.assertEquals(token_params, called_token_params)
            return 'token_string'

        self.ably = AblyRest(auth_callback=callback,
                             rest_host=test_vars["host"],
                             port=test_vars["port"],
                             tls_port=test_vars["tls_port"],
                             tls=test_vars["tls"])

        token_details = self.ably.auth.request_token(
            token_params=called_token_params, auth_callback=callback)
        self.assertIsInstance(token_details, TokenDetails)
        self.assertEquals('token_string', token_details.token)

        def callback(token_params):
            self.assertEquals(token_params, called_token_params)
            return TokenDetails(token='another_token_string')

        token_details = self.ably.auth.request_token(
            token_params=called_token_params, auth_callback=callback)
        self.assertEquals('another_token_string', token_details.token)
    def channel(self, channels, message, event='base-event'):
        """Specify which channel(s) you want to send information to.
        
        Arguments:
            channels {string|list} -- Can be a string for the channel or a list of strings for the channels.
            message {string} -- The message you want to send to the channel(s)
        
        Keyword Arguments:
            event {string} -- The event you want broadcasted along with your data. (default: {'base-event'})
        
        Raises:
            DriverLibraryNotFound -- Thrown when ably is not installed.
        
        Returns:
            string -- Returns the message sent.
        """

        try:
            from ably import AblyRest
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "ably" library. Please pip install this library running "pip install ably"'
            )

        client = AblyRest('{0}'.format(self.config.DRIVERS['ably']['secret']))

        if isinstance(channels, list):
            for channel in channels:
                ably_channel = client.channels.get(channel)
                ably_channel.publish(event, message)
        else:
            channel = client.channels.get(channels)
            channel.publish(event, message)

        return message
class TestAuthAuthorize(BaseTestCase):

    def setUp(self):
        self.ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                             rest_host=test_vars["host"],
                             port=test_vars["port"],
                             tls_port=test_vars["tls_port"],
                             tls=test_vars["tls"])

    def per_protocol_setup(self, use_binary_protocol):
        self.ably.options.use_binary_protocol = use_binary_protocol
        self.use_binary_protocol = use_binary_protocol

    def test_if_authorize_changes_auth_mechanism_to_token(self):

        self.assertEqual(Auth.Method.BASIC, self.ably.auth.auth_mechanism,
                         msg="Unexpected Auth method mismatch")

        self.ably.auth.authorise()

        self.assertEqual(Auth.Method.TOKEN, self.ably.auth.auth_mechanism,
                         msg="Authorise should change the Auth method")

    def test_authorize_shouldnt_create_token_if_not_expired(self):

        token = self.ably.auth.authorise()

        new_token = self.ably.auth.authorise()

        self.assertGreater(token.expires, time.time()*1000)

        self.assertIs(new_token, token)

    def test_authorize_should_create_new_token_if_forced(self):

        token = self.ably.auth.authorise()

        new_token = self.ably.auth.authorise(force=True)

        self.assertGreater(token.expires, time.time()*1000)

        self.assertIsNot(new_token, token)
        self.assertGreater(new_token.expires, token.expires)

        another_token = self.ably.auth.authorise(auth_options={'force': True})
        self.assertIsNot(new_token, another_token)

    def test_authorize_create_new_token_if_expired(self):

        token = self.ably.auth.authorise()

        with mock.patch('ably.types.tokendetails.TokenDetails.is_expired',
                        return_value=True):
            new_token = self.ably.auth.authorise()

        self.assertIsNot(token, new_token)

    def test_authorize_returns_a_token_details(self):

        token = self.ably.auth.authorise()

        self.assertIsInstance(token, TokenDetails)

    @dont_vary_protocol
    def test_authorize_adheres_to_request_token(self):
        token_params = {'ttl': 10, 'client_id': 'client_id'}
        auth_params = {'auth_url': 'somewhere.com', 'query_time': True}
        with mock.patch('ably.rest.auth.Auth.request_token') as request_mock:
            self.ably.auth.authorise(token_params, auth_params, force=True)

        token_called, auth_called = request_mock.call_args
        self.assertEqual(token_called[0], token_params)

        # Authorise may call request_token with some default auth_options.
        for arg, value in six.iteritems(auth_params):
            self.assertEqual(auth_called[arg], value,
                             "%s called with wrong value: %s" % (arg, value))

    def test_with_token_str_https(self):
        token = self.ably.auth.authorise()
        token = token.token
        ably = AblyRest(token=token, rest_host=test_vars["host"],
                        port=test_vars["port"], tls_port=test_vars["tls_port"],
                        tls=True, use_binary_protocol=self.use_binary_protocol)
        ably.channels.test_auth_with_token_str.publish('event', 'foo_bar')

    def test_with_token_str_http(self):
        token = self.ably.auth.authorise()
        token = token.token
        ably = AblyRest(token=token, rest_host=test_vars["host"],
                        port=test_vars["port"], tls_port=test_vars["tls_port"],
                        tls=False, use_binary_protocol=self.use_binary_protocol)
        ably.channels.test_auth_with_token_str.publish('event', 'foo_bar')

    def test_if_default_client_id_is_used(self):
        ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                        rest_host=test_vars["host"],
                        port=test_vars["port"],
                        tls_port=test_vars["tls_port"],
                        tls=test_vars["tls"],
                        client_id='my_client_id',
                        use_binary_protocol=self.use_binary_protocol)
        token = ably.auth.authorise()
        self.assertEqual(token.client_id, 'my_client_id')

    def test_if_parameters_are_stored_and_used_as_defaults(self):
        self.ably.auth.authorise({'ttl': 555, 'client_id': 'new_id'},
                                 {'auth_headers': {'a_headers': 'a_value'}})
        with mock.patch('ably.rest.auth.Auth.request_token',
                        wraps=self.ably.auth.request_token) as request_mock:
            self.ably.auth.authorise(force=True)

        token_called, auth_called = request_mock.call_args
        self.assertEqual(token_called[0], {'ttl': 555, 'client_id': 'new_id'})
        self.assertEqual(auth_called['auth_headers'], {'a_headers': 'a_value'})

    def test_force_and_timestamp_are_not_stored(self):
        # authorise once with arbitrary defaults
        token_1 = self.ably.auth.authorise(
            {'ttl': 60 * 1000, 'client_id': 'new_id'},
            {'auth_headers': {'a_headers': 'a_value'}})
        self.assertIsInstance(token_1, TokenDetails)

        # call authorise again with force and timestamp set
        timestamp = self.ably.time()
        with mock.patch('ably.rest.auth.TokenRequest',
                        wraps=ably.types.tokenrequest.TokenRequest) as tr_mock:
            token_2 = self.ably.auth.authorise(
                {'ttl': 60 * 1000, 'client_id': 'new_id', 'timestamp': timestamp},
                {'auth_headers': {'a_headers': 'a_value'}, 'force': True})
        self.assertIsInstance(token_2, TokenDetails)
        self.assertNotEqual(token_1, token_2)
        self.assertEqual(tr_mock.call_args[1]['timestamp'], timestamp)

        # call authorise again with no params
        token_3 = self.ably.auth.authorise()
        self.assertIsInstance(token_3, TokenDetails)
        self.assertEqual(token_2, token_3)

        # call authorise again with force
        with mock.patch('ably.rest.auth.TokenRequest',
                        wraps=ably.types.tokenrequest.TokenRequest) as tr_mock:
            token_4 = self.ably.auth.authorise(force=True)
        self.assertIsInstance(token_4, TokenDetails)
        self.assertNotEqual(token_2, token_4)
        self.assertNotEqual(tr_mock.call_args[1]['timestamp'], timestamp)
 def setUp(self):
     self.ably = AblyRest(key=test_vars["keys"][0]["key_str"],
                          rest_host=test_vars["host"],
                          port=test_vars["port"],
                          tls_port=test_vars["tls_port"],
                          tls=test_vars["tls"])