Skip to content

Commit d62d979

Browse files
authored
Merge pull request #29 from Adyen/Tests-LibChanges
Fixes for Python3 version
2 parents 294370b + 264e507 commit d62d979

File tree

6 files changed

+42
-31
lines changed

6 files changed

+42
-31
lines changed

.travis.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ sudo: true
22
language: python
33
python:
44
- "2.7"
5+
- "3.6"
56
cache: pip
67
install:
78
- pip install requests

Adyen/client.py

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ def call_api(self, request_data, service, action, idempotency=False,
200200
from . import username, password, merchant_account, platform
201201
#
202202
if self.http_init == False:
203-
self.http_client = HTTPClient(self.app_name,self.LIB_VERSION,self.USER_AGENT_SUFFIX, self.http_force)
203+
self.http_client = HTTPClient(self.app_name,self.USER_AGENT_SUFFIX,self.LIB_VERSION,self.http_force)
204204
self.http_init = True
205205

206206
#username at self object has highest priority. fallback to root module
@@ -302,7 +302,7 @@ def call_hpp(self, message, action, hmac_key="", **kwargs):
302302
from . import hmac, platform
303303
#
304304
if self.http_init == False:
305-
self.http_client = HTTPClient(self.app_name,self.LIB_VERSION,self.USER_AGENT_SUFFIX, self.http_force)
305+
self.http_client = HTTPClient(self.app_name,self.USER_AGENT_SUFFIX,self.LIB_VERSION,self.http_force)
306306
self.http_init = True
307307

308308
#hmac provided in function has highest priority. fallback to self then
@@ -355,7 +355,7 @@ def hpp_payment(self,request_data, action, hmac_key="", **kwargs):
355355
from . import hmac, platform
356356
#
357357
if self.http_init == False:
358-
self.http_client = HTTPClient(self.app_name,self.LIB_VERSION,self.USER_AGENT_SUFFIX, self.http_force)
358+
self.http_client = HTTPClient(self.app_name,self.USER_AGENT_SUFFIX,self.LIB_VERSION,self.http_force)
359359
self.http_init = True
360360

361361
if self.platform:
@@ -409,24 +409,18 @@ def _handle_response(self, url, raw_response, raw_request, status_code, headers,
409409
response = {}
410410
# If the result can't be parsed into json, most likely is raw html.
411411
# Some response are neither json or raw html, handle them here:
412-
try:
413-
response = json_lib.loads(raw_result)
414-
415-
self._handle_http_error(url, response, status_code,
416-
headers.get('pspReference'), raw_request, raw_response, headers)
417-
except:
418412

419-
response = json_lib.loads(raw_response)
413+
response = json_lib.loads(raw_response)
420414

421-
# Pass raised error to error handler.
422-
self._handle_http_error(url,response,status_code,headers.get('pspReference'),raw_request,raw_response,headers,request_dict)
415+
# Pass raised error to error handler.
416+
self._handle_http_error(url,response,status_code,headers.get('pspReference'),raw_request,raw_response,headers,request_dict)
423417

424-
try:
425-
if response['errorCode']:
426-
return raw_response
427-
except KeyError:
428-
errstr = 'KeyError: errorCode'
429-
pass
418+
try:
419+
if response['errorCode']:
420+
return raw_response
421+
except KeyError:
422+
errstr = 'KeyError: errorCode'
423+
pass
430424
else:
431425
try:
432426
response = json_lib.loads(raw_response)

Adyen/httpclient.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/bin/python
22

33
from __future__ import absolute_import, division, print_function, unicode_literals
4+
import sys
45

56
try:
67
import requests
@@ -23,11 +24,11 @@
2324
from urllib2 import Request, urlopen, HTTPError
2425

2526
try:
26-
# Python 3
27-
from io import StringIO
28-
except ImportError:
2927
# Python 2
3028
from StringIO import StringIO
29+
except ImportError:
30+
# Python 3
31+
from io import BytesIO
3132

3233
import json as json_lib
3334
import re
@@ -40,13 +41,12 @@
4041
# ['raw_response','raw_request','status_code','headers'])
4142

4243
class HTTPClient(object):
43-
def __init__(self,app_name,USER_AGENT_SUFFIX,LIB_VERSION, force_request = None):
44+
def __init__(self,app_name,USER_AGENT_SUFFIX,LIB_VERSION,force_request = None):
4445
#Check if requests already available, default to urllib
4546
# self.app_name = app_name
4647
# self.LIB_VERSION = LIB_VERSION
4748
# self.USER_AGENT_SUFFIX = USER_AGENT_SUFFIX
4849
self.user_agent = app_name + " " + USER_AGENT_SUFFIX + LIB_VERSION
49-
5050
if not force_request:
5151
if requests:
5252
self.request = self._requests_post
@@ -107,15 +107,22 @@ def handle_header(header_line):
107107
curl = pycurl.Curl()
108108
curl.setopt(curl.URL, url)
109109

110-
stringbuffer = StringIO()
110+
if sys.version_info[0] >= 3:
111+
stringbuffer = BytesIO()
112+
else:
113+
stringbuffer = StringIO()
114+
#stringbuffer = StringIO()
111115
curl.setopt(curl.WRITEDATA, stringbuffer)
112116

113117
# Add User-Agent header to request so that the request can be identified as coming
114118
# from the Adyen Python library.
115119
headers['User-Agent'] = self.user_agent
116120

117121
# Convert the header dict to formatted array as pycurl needs.
118-
header_list = ["%s:%s" % (k,v) for k,v in headers.iteritems()]
122+
if sys.version_info[0] >= 3:
123+
header_list = ["%s:%s" % (k, v) for k, v in headers.items()]
124+
else:
125+
header_list = ["%s:%s" % (k, v) for k, v in headers.iteritems()]
119126
#Ensure proper content-type when adding headers
120127
if json:
121128
header_list.append("Content-Type:application/json")
@@ -236,7 +243,7 @@ def _urllib_post(self, url,
236243
raw_store = json
237244

238245
raw_request = json_lib.dumps(json) if json else urlencode(data)
239-
url_request = Request(url,data=raw_request)
246+
url_request = Request(url,data=raw_request.encode('utf8'))
240247
if json:
241248
url_request.add_header('Content-Type','application/json')
242249
elif not data:
@@ -251,8 +258,12 @@ def _urllib_post(self, url,
251258

252259
#Adding basic auth is username and password provided.
253260
if username and password:
254-
basicAuthstring = base64.encodestring('%s:%s' % (username,
255-
password)).replace('\n', '')
261+
if sys.version_info[0] >= 3:
262+
basicAuthstring = base64.encodebytes(('%s:%s' % (username,
263+
password)).encode()).decode().replace('\n', '')
264+
else:
265+
basicAuthstring = base64.encodestring('%s:%s' % (username,
266+
password)).replace('\n', '')
256267
url_request.add_header("Authorization", "Basic %s" % basicAuthstring)
257268

258269
#Adding the headers to the request.

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ payments within any Python application.
88

99
## Requirements
1010

11-
- Python 2.7
11+
- Python 2.7 or 3.6
1212
- Packages: requests or pycurl ( optional )
1313
- Adyen account. If you don't have this you can request it here: https://www.adyen.com/home/discover/test-account-signup#form
1414

test/BaseTest.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ def create_client_from_file(self, status, request, filename = None):
1111
if filename:
1212
with open(filename) as data_file:
1313
data = json.load(data_file)
14-
strjson = open(filename).read()
14+
st = open(filename)
15+
strjson = st.read()
1516
else:
1617
data = ""
18+
st = ""
1719
strjson = ""
1820

1921
self.ady.client.http_client = httpclient.HTTPClient
@@ -22,4 +24,7 @@ def create_client_from_file(self, status, request, filename = None):
2224

2325
# self.ady.client.http_client.request = mock.MagicMock(return_value=[strjson, request, status, {'User-Agent': 'appname adyen-python-api-library/1.0.0'}])
2426
mockclient = self.ady.client
27+
if st:
28+
st.close()
2529
return mockclient
30+

test/PaymentTest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def test_authorise_success_mocked(self):
3939
fraudCheckResult = result.message['fraudResult']['results'][0]['FraudCheckResult']
4040
self.assertEqual("CardChunkUsage", fraudCheckResult['name'])
4141
self.assertEqual(8, fraudCheckResult['accountScore'])
42-
self.assertEquals(2, fraudCheckResult['checkId'])
42+
self.assertEqual(2, fraudCheckResult['checkId'])
4343

4444
def test_authorise_error010_mocked(self):
4545
request = {}

0 commit comments

Comments
 (0)