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_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 __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
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 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_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_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_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'])))
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))
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_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 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_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 __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
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_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 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())
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_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)
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()
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
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)
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)
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 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 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.cipher_params = CipherParams(secret_key='keyfordecrypt_16', algorithm='aes')
def test_auth_init_key_only(self): ably = AblyRest(key=test_vars["keys"][0]["key_str"]) self.assertEqual(Auth.Method.BASIC, ably.auth.auth_mechanism, msg="Unexpected Auth method mismatch") self.assertEqual(ably.auth.auth_options.key_name, test_vars["keys"][0]['key_name']) self.assertEqual(ably.auth.auth_options.key_secret, test_vars["keys"][0]['key_secret'])
def test_key_only(self): ably = AblyRest(key=test_vars["keys"][0]["key_str"]) self.assertEqual(ably.options.key_name, test_vars["keys"][0]["key_name"], "Key name does not match") self.assertEqual(ably.options.key_secret, test_vars["keys"][0]["key_secret"], "Key secret does not match")