def test_base_api_uri_used_instead_of_default(self): # Requests to the default BASE_API_URI will noticeably fail by raising an # AssertionError. Requests to the new URL will respond HTTP 200. new_base_api_uri = 'http://example.com/api/v1/' # If any error is raised by the server, the test suite will never exit when # using Python 3. This strange technique is used to raise the errors # outside of the mocked server environment. errors_in_server = [] def server_response(request, uri, headers): try: self.assertEqual(uri, new_base_api_uri) except AssertionError as e: errors_in_server.append(e) return (200, headers, "") hp.register_uri(hp.GET, OAuthClient.BASE_API_URI, body=server_response) hp.register_uri(hp.GET, new_base_api_uri, body=server_response) client = OAuthClient(client_id, client_secret, access_token, refresh_token) with self.assertRaises(AssertionError): client._get() if errors_in_server: raise errors_in_server.pop() client2 = OAuthClient( client_id, client_secret, access_token, refresh_token, base_api_uri=new_base_api_uri) self.assertEqual(client2._get().status_code, 200)
def test_oauth_details_required(self): with self.assertRaises(ValueError): OAuthClient(None, client_secret, access_token, refresh_token) with self.assertRaises(ValueError): OAuthClient(client_id, None, access_token, refresh_token) with self.assertRaises(ValueError): OAuthClient(client_id, client_secret, None, refresh_token) with self.assertRaises(ValueError): OAuthClient(client_id, client_secret, access_token, None)
def test_refresh(self): client = OAuthClient(client_id, client_secret, access_token, refresh_token) def server_response(request, uri, headers): return (200, headers, json.dumps(data)) hp.register_uri(hp.POST, client.TOKEN_ENDPOINT_URI, body=server_response) data = { 'access_token': 'newaccesstoken', 'refresh_token': 'newrefreshtoken', } self.assertNotEqual(client.access_token, data['access_token']) self.assertNotEqual(client.refresh_token, data['refresh_token']) client.refresh() self.assertEqual(client.access_token, data['access_token']) self.assertEqual(client.refresh_token, data['refresh_token']) def server_response(request, uri, headers): return (400, headers, '') hp.reset() hp.register_uri(hp.POST, client.TOKEN_ENDPOINT_URI, body=server_response) client.access_token = access_token client.refresh_token = refresh_token with self.assertRaises(TokenRefreshError): client.refresh() self.assertEqual(client.access_token, access_token) self.assertEqual(client.refresh_token, refresh_token)
def test_base_api_uri_used_instead_of_default(self): # Requests to the default BASE_API_URI will noticeably fail by raising an # AssertionError. Requests to the new URL will respond HTTP 200. new_base_api_uri = 'http://example.com/api/v1/' # If any error is raised by the server, the test suite will never exit when # using Python 3. This strange technique is used to raise the errors # outside of the mocked server environment. errors_in_server = [] def server_response(request, uri, headers): try: self.assertEqual(uri, new_base_api_uri) except AssertionError as e: errors_in_server.append(e) return (200, headers, "") hp.register_uri(hp.GET, OAuthClient.BASE_API_URI, body=server_response) hp.register_uri(hp.GET, new_base_api_uri, body=server_response) client = OAuthClient(client_id, client_secret, access_token, refresh_token) with self.assertRaises(AssertionError): client._get() if errors_in_server: raise errors_in_server.pop() client2 = OAuthClient(client_id, client_secret, access_token, refresh_token, base_api_uri=new_base_api_uri) self.assertEqual(client2._get().status_code, 200)
def test_token_endpoint_uri_used_instead_of_default(self): # Requests to the default BASE_API_URI will noticeably fail by raising an # AssertionError. Requests to the new URL will respond HTTP 200. new_token_endpoint_uri = 'http://example.com/oauth/token' # If any error is raised by the server, the test suite will never exit when # using Python 3. This strange technique is used to raise the errors # outside of the mocked server environment. errors_in_server = [] def server_response(request, uri, headers): parsed_uri = urlparse(uri) parsed_reference = urlparse(new_token_endpoint_uri) try: self.assertEqual(parsed_uri.scheme, parsed_reference.scheme) self.assertEqual(parsed_uri.netloc, parsed_reference.netloc) self.assertEqual(parsed_uri.path, parsed_reference.path) except AssertionError as e: errors_in_server.append(e) response = { 'access_token': 'newaccesstoken', 'refresh_token': 'newrefreshtoken', } return (200, headers, json.dumps(response)) hp.register_uri(hp.POST, OAuthClient.TOKEN_ENDPOINT_URI, body=server_response) hp.register_uri(hp.POST, new_token_endpoint_uri, body=server_response) client = OAuthClient(client_id, client_secret, access_token, refresh_token) with self.assertRaises(AssertionError): client.refresh() if errors_in_server: raise errors_in_server.pop() client2 = OAuthClient( client_id, client_secret, access_token, refresh_token, token_endpoint_uri=new_token_endpoint_uri) self.assertTrue(client2.refresh())
def test_token_endpoint_uri_used_instead_of_default(self): # Requests to the default BASE_API_URI will noticeably fail by raising an # AssertionError. Requests to the new URL will respond HTTP 200. new_token_endpoint_uri = 'http://example.com/oauth/token' # If any error is raised by the server, the test suite will never exit when # using Python 3. This strange technique is used to raise the errors # outside of the mocked server environment. errors_in_server = [] def server_response(request, uri, headers): parsed_uri = urlparse(uri) parsed_reference = urlparse(new_token_endpoint_uri) try: self.assertEqual(parsed_uri.scheme, parsed_reference.scheme) self.assertEqual(parsed_uri.netloc, parsed_reference.netloc) self.assertEqual(parsed_uri.path, parsed_reference.path) except AssertionError as e: errors_in_server.append(e) response = { 'access_token': 'newaccesstoken', 'refresh_token': 'newrefreshtoken', } return (200, headers, json.dumps(response)) hp.register_uri(hp.POST, OAuthClient.TOKEN_ENDPOINT_URI, body=server_response) hp.register_uri(hp.POST, new_token_endpoint_uri, body=server_response) client = OAuthClient(client_id, client_secret, access_token, refresh_token) with self.assertRaises(AssertionError): client.refresh() if errors_in_server: raise errors_in_server.pop() client2 = OAuthClient(client_id, client_secret, access_token, refresh_token, token_endpoint_uri=new_token_endpoint_uri) self.assertTrue(client2.refresh())
def test_send_money(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' base_kwargs = { 'to_btc_address': 'some-btc-address', 'amount': '12.0 BTC', } with self.assertRaises(ValueError): kwargs = base_kwargs.copy() kwargs.update(amount=None, amount_string=None, amount_currency_iso=None) account.send_money(**kwargs) with self.assertRaises(ValueError): kwargs = base_kwargs.copy() kwargs.update(amount='12.0', amount_string=None, amount_currency_iso='USD') account.send_money(**kwargs) with self.assertRaises(ValueError): kwargs = base_kwargs.copy() kwargs.update(amount='12.0', amount_string='12.0', amount_currency_iso=None) account.send_money(**kwargs) with self.assertRaises(ValueError): kwargs = base_kwargs.copy() kwargs.update(amount='12.0', amount_string='12.0', amount_currency_iso='USD') account.send_money(**kwargs) with self.assertRaises(ValueError): kwargs = base_kwargs.copy() kwargs.update(amount=None, amount_string=None, amount_currency_iso='USD') account.send_money(**kwargs) with self.assertRaises(ValueError): kwargs = base_kwargs.copy() kwargs.update(amount=None, amount_string='12.0', amount_currency_iso=None) account.send_money(**kwargs) def server_response(request, uri, headers): try: req = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") tx_data = req.get('transaction') self.assertIsInstance(tx_data, dict) self.assertEqual(len(tx_data), len(kwargs)) return (200, headers, json.dumps(data)) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) with self.assertRaises(APIError): data = {'success': False, 'transaction': {'id': '1'}} kwargs = base_kwargs.copy() account.send_money(**kwargs) with self.assertRaises(UnexpectedDataFormatError): data = {'success': True, 'transaction': 'wrong-type'} kwargs = base_kwargs.copy() account.send_money(**kwargs) with self.assertRaises(UnexpectedDataFormatError): data = {'success': True, 'missing-transaction-key': True} kwargs = base_kwargs.copy() account.send_money(**kwargs) data = {'success': True, 'transaction': {'id': '1'}} kwargs = base_kwargs.copy() tx = account.send_money(**kwargs) self.assertIsInstance(tx, Transaction) oauth_account = Account( OAuthClient(client_id, client_secret, access_token, refresh_token)) oauth_account.id = 'fakeaccountid' hp.reset() def server_response(request, uri, headers): try: req = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") tx_data = req.get('transaction') self.assertIsInstance(tx_data, dict) if two_factor_token: self.assertEqual(request.headers.get('CB-2FA-Token'), two_factor_token) self.assertIsNone(tx_data.get('CB-2FA-Token')) return (200, headers, json.dumps(data)) return (402, headers, '') hp.register_uri(hp.POST, re.compile('.*'), body=server_response) kwargs = base_kwargs.copy() kwargs['two_factor_token'] = two_factor_token = None with self.assertRaises(TwoFactorTokenRequired): oauth_account.send_money(**kwargs) kwargs['two_factor_token'] = two_factor_token = 'sometoken' tx = oauth_account.send_money(**kwargs) self.assertIsInstance(tx, Transaction)
def test_response_handling(self): resp200 = lambda r, u, h: (200, h, '') resp400 = lambda r, u, h: (400, h, '') header_template = ( 'Bearer realm="Doorkeeper" error="{id}" error_description="{error}"' ) def resp401_expired(request, uri, headers): error_data = { 'id': 'invalid_token', 'error': 'The access token expired', } headers.update( {'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_invalid(request, uri, headers): error_data = { 'id': 'invalid_token', 'error': 'The access token is invalid', } headers.update( {'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_generic(request, uri, headers): error_data = { 'id': 'some_error', 'error': 'Some description', } headers.update( {'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_nobody(request, uri, headers): return (401, headers, '') def resp401_header_expired(request, uri, headers): code, headers, _ = resp401_expired(request, uri, headers) return (code, headers, '') def resp401_header_invalid(request, uri, headers): code, headers, _ = resp401_invalid(request, uri, headers) return (code, headers, '') def resp401_header_generic(request, uri, headers): code, headers, _ = resp401_generic(request, uri, headers) return (code, headers, '') resp402 = lambda r, u, h: (402, h, '') hp.register_uri(hp.GET, re.compile('.*200$'), resp200) hp.register_uri(hp.GET, re.compile('.*400$'), resp400) hp.register_uri(hp.GET, re.compile('.*401_expired$'), resp401_expired) hp.register_uri(hp.GET, re.compile('.*401_invalid$'), resp401_invalid) hp.register_uri(hp.GET, re.compile('.*401_generic$'), resp401_generic) hp.register_uri(hp.GET, re.compile('.*401_nobody$'), resp401_nobody) hp.register_uri(hp.GET, re.compile('.*401_header_expired$'), resp401_header_expired) hp.register_uri(hp.GET, re.compile('.*401_header_invalid$'), resp401_header_invalid) hp.register_uri(hp.GET, re.compile('.*401_header_generic$'), resp401_header_generic) hp.register_uri(hp.GET, re.compile('.*402$'), resp402) client = OAuthClient(client_id, client_secret, access_token, refresh_token) assert client._get('200').status_code == 200 with self.assertRaises(APIError): client._get('400') with self.assertRaises(AuthenticationError): client._get('401_generic') with self.assertRaises(AuthenticationError): client._get('401_header_generic') with self.assertRaises(InvalidAccessToken): client._get('401_invalid') with self.assertRaises(InvalidAccessToken): client._get('401_header_invalid') with self.assertRaises(ExpiredAccessToken): client._get('401_expired') with self.assertRaises(ExpiredAccessToken): client._get('401_header_expired') with self.assertRaises(AuthenticationError): client._get('401_nobody') with self.assertRaises(TwoFactorTokenRequired): client._get('402')
def test_response_handling(self): resp200 = lambda r, u, h: (200, h, '') resp400 = lambda r, u, h: (400, h, '') header_template = ( 'Bearer realm="Doorkeeper" error="{id}" error_description="{error}"') def resp401_expired(request, uri, headers): error_data = { 'id': 'invalid_token', 'error': 'The access token expired', } headers.update({'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_invalid(request, uri, headers): error_data = { 'id': 'invalid_token', 'error': 'The access token is invalid', } headers.update({'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_generic(request, uri, headers): error_data = { 'id': 'some_error', 'error': 'Some description', } headers.update({'www-authenticate': header_template.format(**error_data)}) return (401, headers, json.dumps(error_data)) def resp401_nobody(request, uri, headers): return (401, headers, '') def resp401_header_expired(request, uri, headers): code, headers, _ = resp401_expired(request, uri, headers) return (code, headers, '') def resp401_header_invalid(request, uri, headers): code, headers, _ = resp401_invalid(request, uri, headers) return (code, headers, '') def resp401_header_generic(request, uri, headers): code, headers, _ = resp401_generic(request, uri, headers) return (code, headers, '') resp402 = lambda r, u, h: (402, h, '') hp.register_uri(hp.GET, re.compile('.*200$'), resp200) hp.register_uri(hp.GET, re.compile('.*400$'), resp400) hp.register_uri(hp.GET, re.compile('.*401_expired$'), resp401_expired) hp.register_uri(hp.GET, re.compile('.*401_invalid$'), resp401_invalid) hp.register_uri(hp.GET, re.compile('.*401_generic$'), resp401_generic) hp.register_uri(hp.GET, re.compile('.*401_nobody$'), resp401_nobody) hp.register_uri(hp.GET, re.compile('.*401_header_expired$'), resp401_header_expired) hp.register_uri(hp.GET, re.compile('.*401_header_invalid$'), resp401_header_invalid) hp.register_uri(hp.GET, re.compile('.*401_header_generic$'), resp401_header_generic) hp.register_uri(hp.GET, re.compile('.*402$'), resp402) client = OAuthClient(client_id, client_secret, access_token, refresh_token) assert client._get('200').status_code == 200 with self.assertRaises(APIError): client._get('400') with self.assertRaises(AuthenticationError): client._get('401_generic') with self.assertRaises(AuthenticationError): client._get('401_header_generic') with self.assertRaises(InvalidAccessToken): client._get('401_invalid') with self.assertRaises(InvalidAccessToken): client._get('401_header_invalid') with self.assertRaises(ExpiredAccessToken): client._get('401_expired') with self.assertRaises(ExpiredAccessToken): client._get('401_header_expired') with self.assertRaises(AuthenticationError): client._get('401_nobody') with self.assertRaises(TwoFactorTokenRequired): client._get('402')