Skip to content

Commit

Permalink
Merge pull request #30 from peshay/2.2
Browse files Browse the repository at this point in the history
2.2
  • Loading branch information
peshay authored Jan 31, 2018
2 parents e98a687 + 3314b16 commit 1556f20
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 21 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ install:
- pip install -r requirements.txt
- pip install -r tests/requirements.txt
- python setup.py -q install
script: nosetests --with-coverage
script: nosetests --with-coverage --cover-package=btcde
after_success:
- codecov
jobs:
Expand All @@ -37,4 +37,4 @@ jobs:
on:
tags: true
branch: master
condition: $TRAVIS_PYTHON_VERSION = "2.7"
condition: $TRAVIS_PYTHON_VERSION = "2.7"
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ All mandatory parameters have to be passed to a function, all optional are resol
* only_kyc_full
* payment_option
* seat_of_bank

*API Credits Cost: 1*

#### deleteOrder(order_id, trading_pair)
Expand All @@ -87,7 +87,7 @@ All mandatory parameters have to be passed to a function, all optional are resol
* date_start
* date_end
* page

*API Credits Cost: 2*

#### showMyOrderDetails(order_id)
Expand All @@ -113,7 +113,7 @@ All mandatory parameters have to be passed to a function, all optional are resol
* date_start
* date_end
* page

*API Credits Cost: 3*

#### showMyTradeDetails(trade_id)
Expand Down
13 changes: 5 additions & 8 deletions btcde.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@
import decimal

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
log = logging.getLogger(__name__)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

__version__ = '2.1'
__version__ = '2.2'

# disable unsecure SSL warning
requests.packages.urllib3.disable_warnings()
Expand Down Expand Up @@ -48,7 +46,7 @@ def verify_keys_and_values(self, avail_params, given_params):
self.error_on_invalid_value(v, self.PAYMENT_OPTIONS)
elif k == 'state':
self.error_on_invalid_value(v, self.STATES)

def error_on_invalid_value(self, value, list):
if value not in list:
list_string = ', '.join(str(x) for x in list)
Expand All @@ -65,7 +63,7 @@ def create_url(self, uri):
self.encoded_string = ''
self.url = uri


TRADING_PAIRS = ['btceur', 'bcheur', 'etheur']
ORDER_TYPES = ['buy', 'sell']
CURRENCIES = ['btc', 'bch', 'eth']
Expand Down Expand Up @@ -93,8 +91,7 @@ def HandleAPIErrors(r):
"""To handle Errors from BTCDE API."""
valid_status_codes = [200, 201, 204]
if r.status_code not in valid_status_codes:
reader = codecs.getreader("utf-8")
content = json.load(reader(r.raw))
content = r.json()
errors = content.get('errors')
log.warning('API Error Code: {}'.format(str(errors[0]['code'])))
log.warning('API Error Message: {}'.format(errors[0]['message']))
Expand Down Expand Up @@ -125,7 +122,7 @@ def build_hmac_sign(self, md5string, method, url):
md5=md5string)
hmac_signed = hmac.new(bytearray(self.api_secret.encode()), msg=hmac_data.encode(), digestmod=hashlib.sha256).hexdigest()
return hmac_signed

def set_header(self, url, method, encoded_string):
# raise self.nonce before using
self.nonce += 1
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"""Setup to install Bitcoin.de API Python Module."""
from distutils.core import setup
setup(name='btcde',
version='2.1',
version='2.2',
py_modules=['btcde'],
install_requires=['requests', 'future'],
description='API Wrapper for Bitcoin.de Trading API.',
Expand Down
1 change: 1 addition & 0 deletions tests/resources/NonUTF8
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"errors":[{"message":"Order not possible","code":51,"field":"order_id"}],"credits":29}
44 changes: 37 additions & 7 deletions tests/test_btcde_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
from mock import patch
import json
import btcde
from decimal import Decimal


@patch('btcde.log')
@requests_mock.Mocker()
class TestBtcdeAPIDocu(TestCase):
'''Tests are as in bitcoin.de API documentation.
https://www.bitcoin.de/de/api/tapi/v2/docu'''

def sampleData(self, file):
'''Retrieve sample data from json files.'''
filepath = 'tests/resources/{}.json'.format(file)
Expand Down Expand Up @@ -348,27 +349,56 @@ def test_showAccountLedger(self, mock_logger, m):
self.assertEqual(history[0].url, base_url + url_args)
self.assertTrue(mock_logger.debug.called)

def test_decimal_parsing(self, mock_logger, m):
'''Test if the decimal parsing calculates correctly.'''
params = {'type': 'buy',
'trading_pair': 'btceur',
'max_amount': 10,
'price': 1337}
response = self.sampleData('showOrderbook_buy')
m.get(requests_mock.ANY, json=response, status_code=200)
data = self.conn.showOrderbook(params.get('type'),
params.get('trading_pair'),
price=params.get('price'))
price = data.get('orders')[0].get('price')
self.assertIsInstance(price, Decimal)
self.assertEqual(price + Decimal('22.3'), Decimal('2232.2'))
self.assertNotEqual(float(price) + float('22.3'), float('2232.2'))


class TestBtcdeExceptions(TestCase):
'''Test for Exception Handling.'''

def sampleData(self, file):
'''Retrieve sample data from json files.'''
filepath = 'tests/resources/{}.json'.format(file)
data = json.load(open(filepath))
return data

def setUp(self):
self.XAPIKEY = 'f00b4r'
self.XAPISECRET = 'b4rf00'
self.conn = btcde.Connection(self.XAPIKEY, self.XAPISECRET)
self.conn = btcde.Connection(self.XAPIKEY, self.XAPISECRET)
self.XAPINONCE = self.conn.nonce

def tearDown(self):
del self.XAPIKEY
del self.XAPISECRET
del self.conn

@requests_mock.Mocker()
def test_dont_fail_on_non_utf8(self, m):
'''Test if no exception raises with a non-utf8 response.
https://github.com/peshay/btcde/issues/12'''
filepath = 'tests/resources/NonUTF8'
with open(filepath, 'r') as f:
m.post(requests_mock.ANY, content=f.read().encode('utf-16', 'replace'), status_code=403)
try:
self.conn.executeTrade('foobar', 'buy', 'btceur', '0')
self.assertTrue(True)
except UnicodeDecodeError:
self.assertTrue(False)

@requests_mock.Mocker()
def test_APIException(self, m):
'''Test API Exception.'''
Expand All @@ -390,20 +420,20 @@ def test_APIException(self, m):
history = m.request_history
self.assertEqual(history[0].method, "POST")
self.assertEqual(history[0].url, base_url + url_args)

@patch('btcde.log')
def test_RequestException(self, mock_logger):
'''Test Requests Exception.'''
params = {'type': 'buy',
'trading_pair': 'btceur',
'max_amount': 10,
'price': 13}
'price': 13}
self.conn.orderuri = 'https://foo.bar'
self.conn.createOrder(params.get('type'),
params.get('trading_pair'), params.get('max_amount'),
price=params.get('price'))
self.assertTrue(mock_logger.warning.called)

def test_TradingPairValueException(self):
'''Test wrong traiding_pair Value Exception.'''
with self.assertRaises(ValueError) as context:
Expand Down

0 comments on commit 1556f20

Please sign in to comment.