def test_get_payment_methods(self): def server_response(request, uri, headers): self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = { 'default_buy': '54a710de25dc9a311800006e', 'default_sell': '54a710de25dc9a311800006e', 'payment_methods': [{ 'payment_method': { 'can_buy': True, 'can_sell': True, 'currency': 'USD', 'id': '54a710de25dc9a311800006e', 'name': 'Test Bank *****1111', 'type': 'ach_bank_account' } }] } methods = client.get_payment_methods() self.assertIsInstance(methods, APIObject) for method in methods.payment_methods: self.assertIsInstance(method, PaymentMethod) for method in methods[::]: self.assertIsInstance(method, PaymentMethod)
def test_get_payment_method(self): def server_response(request, uri, headers): self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = { "payment_method": { "id": "530eb5b217cb34e07a000011", "name": "US Bank ****4567", "can_buy": True, "can_sell": True } } method = client.get_payment_method('id') self.assertIsInstance(method, PaymentMethod) data = {'missing_payment_method_key': True} with self.assertRaises(UnexpectedDataFormatError): client.get_payment_method('id') data = {'payment_method': 'wrong-type'} with self.assertRaises(UnexpectedDataFormatError): client.get_payment_method('id')
def test_commit(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' transfer = account.load({'transfer': {'id': '1'}}).transfer def server_response(request, uri, headers): try: json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") return (200, headers, json.dumps(data)) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) with self.assertRaises(APIError): data = {'success': False, 'transfer': {'id': '1'}} transfer.commit() with self.assertRaises(UnexpectedDataFormatError): data = {'success': True, 'transfer': 'wrong-type'} transfer.commit() with self.assertRaises(UnexpectedDataFormatError): data = {'success': True, 'missing-transfer-key': True} transfer.commit() data = {'success': True, 'transfer': {'id': '1'}} tx = transfer.commit() self.assertIsInstance(tx, Transfer)
def test_create_user(self): def server_response(request, uri, headers): try: request_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") if isinstance(scopes, (list, tuple)): self.assertEqual(' '.join(scopes), request_data['user']['scopes']) elif isinstance(scopes, six.string_types): self.assertEqual(scopes, request_data['user']['scopes']) self.assertIsInstance(request_data.get('user'), dict) return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) scopes = None data = {'success': False, 'errors': ['Email is not available']} with self.assertRaises(APIError): client.create_user('*****@*****.**', 'password') for scopes in (['a', 'b', 'c'], ('a', 'b', 'c'), 'a b c'): data = {'success': True, 'user': {'id': 'fakeid'}} client.create_user('*****@*****.**', 'password', scopes=scopes)
def test_get_button(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' button_code = 'fakebuttoncode' def server_response(request, uri, headers): self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = {'button': 'not-the-right-type'} with self.assertRaises(UnexpectedDataFormatError): account.get_button(button_code) data = {'missing-button-key': True} with self.assertRaises(UnexpectedDataFormatError): account.get_button(button_code) data = {'button': {'code': button_code}} button = account.get_button(button_code) self.assertIsInstance(button, Button) data = {'badkey': 'bar', 'success': True} with self.assertRaises(UnexpectedDataFormatError): account.get_address() data = { 'address': 'a', 'callback_url': None, 'label': None, 'success': True } address = account.get_address() self.assertIsInstance(address, Address)
def test_get_address(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' def server_response(request, uri, headers): self.assertTrue(uri.endswith('%s/address' % account.id)) self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = { 'address': 'a', 'callback_url': None, 'label': None, 'success': False } with self.assertRaises(APIError): account.get_address() data = {'badkey': 'bar', 'success': True} with self.assertRaises(UnexpectedDataFormatError): account.get_address() data = { 'address': 'a', 'callback_url': None, 'label': None, 'success': True } address = account.get_address() self.assertIsInstance(address, Address)
def test_get_order(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' def server_response(request, uri, headers): try: json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") return (200, headers, json.dumps(data)) order_id = 'fakeorderid' hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = {'missing_order_key': True} with self.assertRaises(UnexpectedDataFormatError): account.get_order(order_id) data = {'order': 'not-the-right-type'} with self.assertRaises(UnexpectedDataFormatError): account.get_order(order_id) data = {'order': {'id': '1'}} order = account.get_order(order_id) self.assertIsInstance(order, Order)
def test_get_buy_and_sell_price(self): def server_response(request, uri, headers): try: request_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") self.assertEqual(request_data.get('qty'), quantity) self.assertEqual(request_data.get('currency'), currency) return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) for func in (client.get_buy_price, client.get_sell_price): quantity, currency = (None, None) data = { 'amount': '10.25', 'currency': 'USD', 'btc': { 'amount': '1.0', 'currency': 'BTC' }, } price = func() self.assertIsInstance(price, Money) self.assertEqual(price, data) quantity, currency = (12, 'USD') price = func(quantity, currency) self.assertIsInstance(price, Money) self.assertEqual(price, data)
def test_modify(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' account.name = initial_name = 'Wallet' def server_response(request, uri, headers): self.assertTrue(uri.endswith(account.id)) try: request_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") name = request_data.get('account', {}).get('name') assert name == new_name return (200, headers, json.dumps(data)) new_name = 'Vault' data = {'success': False, 'account': {'name': new_name}} hp.register_uri(hp.PUT, re.compile('.*'), body=server_response) with self.assertRaises(APIError): account.modify(new_name) self.assertEqual(account.name, initial_name) data = {'success': True, 'account': {'name': new_name}} account.modify(new_name) self.assertEqual(account.name, new_name) data = {'success': True, 'account': 'nottherighttype'} with self.assertRaises(UnexpectedDataFormatError): account.modify(new_name)
def test_create_account(self): def server_response(request, uri, headers): try: request_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") account = request_data.get('account') assert isinstance(account, dict) name = account.get('name') assert isinstance(name, six.string_types) return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) data = {'account': {'id': 'fakeid'}, 'success': False} with self.assertRaises(APIError): client.create_account('accountname') data = {'noaccountkey': True, 'success': True} with self.assertRaises(UnexpectedDataFormatError): client.create_account('accountname') data = {'account': {'id': 'fakeid'}, 'success': True} account = client.create_account('accountname') self.assertIsInstance(account, Account)
def test_get_accounts(self): def server_response(request, uri, headers): try: json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") return (200, headers, json.dumps({ 'current_page': 1, 'num_pages': 1, 'total_count': 3, 'accounts': [{ 'id': '54a710dd25dc9a311800003f' }, { 'id': '54a710dd25dc9a311800003g' }], })) client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) response = client.get_accounts() self.assertIsInstance(response, APIObject) self.assertEqual(len(response.accounts), 2) for account in response.accounts: self.assertIsInstance(account, Account)
def test_get_account(self): def make_server_response(account_id): def server_response(request, uri, headers): self.assertTrue(uri.endswith(account_id), (uri, account_id)) return (200, headers, json.dumps(data) ) # Data coming from outer scope. return server_response # Check that client fetches primary account by default. client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=make_server_response('primary')) data = {'account': {'id': '54a710dd25dc9a311800003f'}} account = client.get_account() self.assertIsInstance(account, Account) # Check that client fetches specific account ID. hp.reset() account_id = 'fakeid' hp.register_uri(hp.GET, re.compile('.*'), body=make_server_response(account_id)) account = client.get_account(account_id) self.assertIsInstance(account, Account) # Check that the client raises error on bad response format data = {'notaccount': {'foo': 'bar'}} with self.assertRaises(UnexpectedDataFormatError): account = client.get_account(account_id)
def test_get_orders(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' initial_name = 'name' initial_price_string = '12.0' initial_price_currency_iso = 'USD' button = account.load({ 'button': { 'id': '1', 'name': initial_name, 'price_string': initial_price_string, 'price_currency_iso': initial_price_currency_iso, 'code': 'buttoncode', }, }).button def server_response(request, uri, headers): try: json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") return (200, headers, json.dumps(data)) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = { 'total_count': 3, 'current_page': 1, 'num_pages': 1, 'orders': [ { 'order': { 'id': '1' } }, { 'order': { 'id': '2' } }, { 'order': { 'id': '3' } }, ], } response = button.get_orders() self.assertIsInstance(response, APIObject) self.assertEqual(len(response.orders), 3) for order in response.orders: self.assertIsInstance(order, Order)
def test_auth_succeeds_with_bytes_and_unicode(self): resp200 = lambda r, uh, h: (200, h, '') hp.register_uri(hp.GET, re.compile('.*'), resp200) api_key = 'key' api_secret = 'secret' self.assertIsInstance(api_key, six.text_type) # Unicode self.assertIsInstance(api_secret, six.text_type) # Unicode client = Client(api_key, api_secret) self.assertEqual(client._get().status_code, 200) api_key = api_key.encode('utf-8') api_secret = api_secret.encode('utf-8') self.assertIsInstance(api_key, six.binary_type) # Bytes self.assertIsInstance(api_secret, six.binary_type) # Bytes client = Client(api_key, api_secret) self.assertEqual(client._get().status_code, 200)
def test_create_order(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' initial_name = 'name' initial_price_string = '12.0' initial_price_currency_iso = 'USD' button = account.load({ 'button': { 'id': '1', 'name': initial_name, 'price_string': initial_price_string, 'price_currency_iso': initial_price_currency_iso, 'code': 'buttoncode', }, }).button def server_response(request, uri, headers): self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) name = 'b-name' price_string = 'b-price' price_currency_iso = 'BTC' with self.assertRaises(APIError): data = { 'success': False, 'order': { 'name': name, 'price_string': price_string, 'price_currency_iso': price_currency_iso, }, } button.create_order() with self.assertRaises(UnexpectedDataFormatError): data = {'success': True, 'order': 'wrong-type'} button.create_order() with self.assertRaises(UnexpectedDataFormatError): data = {'success': True, 'missing-order-key': True} button.create_order() data = { 'success': True, 'order': { 'name': name, 'price_string': price_string, 'price_currency_iso': price_currency_iso, }, } order = button.create_order() self.assertIsInstance(order, Order)
def test_create_address(self): def server_response(request, uri, headers): try: request_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") address = request_data.get('address') assert isinstance(address, dict) if label is not None: assert address.get('label') == label if callback_url is not None: assert address.get('callback_url') == callback_url return (200, headers, json.dumps(data)) account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' hp.register_uri(hp.POST, re.compile('.*'), body=server_response) label, callback_url = ('label', 'http://example.com/') data = { 'success': False, 'address': 'foo', 'label': label, 'callback_url': callback_url } with self.assertRaises(APIError): account.create_address(label, callback_url) label, callback_url = ('label', 'http://example.com/') data = {'success': True, 'arbkey': 'bar'} with self.assertRaises(UnexpectedDataFormatError): account.create_address(label, callback_url) label, callback_url = ('label', 'http://example.com/') data = { 'success': True, 'address': 'foo', 'label': label, 'callback_url': callback_url } address = account.create_address(label, callback_url) self.assertIsInstance(address, Address) label, callback_url = (None, None) data = { 'success': True, 'address': 'foo', 'label': label, 'callback_url': callback_url } address = account.create_address() self.assertIsInstance(address, Address)
def test_get_exchange_rates(self): def server_response(request, uri, headers): self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = {'aed_to_btc': '0.027224', 'btc_to_aed': '36.73247'} rates = client.get_exchange_rates() self.assertIsInstance(rates, APIObject) self.assertEqual(rates, data)
def test_get_supported_currencies(self): def server_response(request, uri, headers): self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = [['Afghan Afghani (AFN)', 'AFN'], ['United States Dollar (USD)', 'USD']] currencies = client.get_supported_currencies() self.assertIsInstance(currencies, list) self.assertEqual(currencies, data)
def test_get_addresses(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' def server_response(request, uri, headers): try: json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") data = { 'total_count': 3, 'current_page': 1, 'num_pages': 1, 'addresses': [ { 'address': { 'label': '', 'address': 'foo', 'callback_url': '', 'id': '1' } }, { 'address': { 'label': '', 'address': 'foo', 'callback_url': '', 'id': '2' } }, { 'address': { 'label': '', 'address': 'foo', 'callback_url': '', 'id': '3' } }, ], } return (200, headers, json.dumps(data)) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) response = account.get_addresses() self.assertIsInstance(response, APIObject) self.assertEqual(len(response.addresses), 3) for address in response.addresses: self.assertIsInstance(address, Address)
def test_get_authorization(self): data = {'meta': 'example', 'key': 'value'} def server_response(request, uri, headers): return (200, headers, json.dumps(data) ) # Data coming from outer scope. client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) authorization = client.get_authorization() self.assertIsInstance(authorization, APIObject) for key, value in authorization.items(): self.assertEqual(data.get(key), value)
def test_create_order(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' def server_response(request, uri, headers): try: request_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") button_data = request_data.get('button') self.assertIsInstance(button_data, dict) for key in ['name', 'price_string', 'price_currency_iso']: self.assertTrue(key in button_data) return (200, headers, json.dumps(data)) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) name = 'b-name' price_string = 'b-price' price_currency_iso = 'BTC' with self.assertRaises(APIError): data = { 'success': False, 'order': { 'name': name, 'price_string': price_string, 'price_currency_iso': price_currency_iso, }, } account.create_order(name, price_string, price_currency_iso) with self.assertRaises(UnexpectedDataFormatError): data = {'success': True, 'order': 'wrong-type'} account.create_order(name, price_string, price_currency_iso) with self.assertRaises(UnexpectedDataFormatError): data = {'success': True, 'missing-order-key': True} account.create_order(name, price_string, price_currency_iso) data = { 'success': True, 'order': { 'name': name, 'price_string': price_string, 'price_currency_iso': price_currency_iso, }, } order = account.create_order(name, price_string, price_currency_iso) self.assertIsInstance(order, Order)
def test_get_current_user(self): def server_response(request, uri, headers): self.assertTrue(uri.endswith('users/self')) self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) data = {'nouserkey': True} with self.assertRaises(UnexpectedDataFormatError): client.get_current_user() data = {'user': {'id': 'fakeid'}} user = client.get_current_user() self.assertIsInstance(user, User)
def test_delete(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' def server_response(request, uri, headers): self.assertTrue(uri.endswith(account.id)) self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) hp.register_uri(hp.DELETE, re.compile('.*'), body=server_response) data = {'success': False} with self.assertRaises(APIError): account.delete() data = {'success': True} self.assertIsNone(account.delete())
def test_response_handling(self): resp200 = lambda r, u, h: (200, h, '') resp400 = lambda r, u, h: (400, h, '') resp401 = lambda r, u, h: (401, 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$'), resp401) client = Client(api_key, api_secret) assert client._get('200').status_code == 200 with self.assertRaises(APIError): client._get('400') with self.assertRaises(AuthenticationError): client._get('401')
def test_get_balance(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' account.balance = initial_balance = lambda: None # Initial value def server_response(request, uri, headers): self.assertTrue(uri.endswith('%s/balance' % account.id)) self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) data = {'currency': 'USD', 'amount': '10.00'} hp.register_uri(hp.GET, re.compile('.*'), body=server_response) balance = account.get_balance() self.assertIsInstance(balance, Money) # Fetching the current balance should not modify the balance attribute on # the Account object. self.assertEqual(account.balance, initial_balance)
def test_redeem_token(self): def server_response(request, uri, headers): try: request_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") token_id = request_data.get('token_id') assert isinstance(token_id, six.text_type) return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) data = {'success': False} assert False == client.redeem_token('token1') data = {'success': True} assert True == client.redeem_token('token2')
def test_set_primary(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' account.primary = None def server_response(request, uri, headers): self.assertTrue(uri.endswith('%s/primary' % account.id)) self.assertEqual(request.body.decode(), '') return (200, headers, json.dumps(data)) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) data = {'success': False} with self.assertRaises(APIError): account.set_primary() self.assertIsNone( account.primary) # Primary status should not have changed. data = {'success': True} account.set_primary() self.assertTrue(account.primary) # Primary status should have changed.
def test_cancel(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' transaction = account.load({'transaction': {'id': '1'}}).transaction def server_response(request, uri, headers): try: json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") return (200, headers, json.dumps(data)) hp.register_uri(hp.DELETE, re.compile('.*'), body=server_response) with self.assertRaises(APIError): data = {'success': False} transaction.cancel() data = {'success': True} self.assertTrue(transaction.cancel())
def test_get_spot_price(self): def server_response(request, uri, headers): try: request_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") self.assertEqual(request_data.get('currency'), currency) return (200, headers, json.dumps(data)) client = Client(api_key, api_secret) hp.register_uri(hp.GET, re.compile('.*'), body=server_response) currency = None data = {'amount': '1.000', 'currency': 'BTC'} price = client.get_spot_price() self.assertIsInstance(price, Money) self.assertEqual(price, data) currency = 'USD' data = {'amount': '10.00', 'currency': 'USD'} price = client.get_spot_price(currency) self.assertIsInstance(price, Money) self.assertEqual(price, data)
def test_refund(self): account = Account(Client(api_key, api_secret)) account.id = 'fakeaccountid' order = account.load({ 'order': { 'id': '1', 'custom': 'custom', 'button': { 'id': 'fakeid', 'code': 'acode' }, }, }).order def server_response(request, uri, headers): try: req_data = json.loads(request.body.decode()) except ValueError: raise AssertionError("request body was malformed.") order_data = req_data.get('order') self.assertIsInstance(order_data, dict) return (200, headers, json.dumps(data)) hp.register_uri(hp.POST, re.compile('.*'), body=server_response) with self.assertRaises(UnexpectedDataFormatError): data = {'order': 'wrong-type'} order.refund('USD') with self.assertRaises(UnexpectedDataFormatError): data = {'missing-order-key': True} order.refund('USD') data = {'order': {'id': '1'}} refunded = order.refund('USD') self.assertEqual(refunded, data['order']) self.assertIsInstance(refunded, Order)