Skip to content

Commit a6c74ea

Browse files
committed
Decode response_content before loading in JSON #297
- Add a unit test for `api.request_license_data` Signed-off-by: Thomas Druez <[email protected]>
1 parent e186aa5 commit a6c74ea

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/attributecode/api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def request_license_data(url, api_key, license_key):
6363
try:
6464
request = Request(quoted_url, headers=headers)
6565
response = urlopen(request)
66-
response_content = response.read()
66+
response_content = response.read().decode('utf-8')
6767
license_data = json.loads(response_content)
6868
if not license_data['results']:
6969
msg = u"Invalid 'license': %s" % license_key

tests/test_api.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,23 @@
2323
from mock import patch
2424

2525
from attributecode import api
26+
from attributecode import ERROR
27+
from attributecode import Error
28+
29+
30+
class FakeResponse(object):
31+
response_content = None
32+
33+
def __init__(self, response_content):
34+
self.response_content = response_content
35+
36+
def read(self):
37+
return self.response_content
2638

2739

2840
class ApiTest(unittest.TestCase):
2941
@patch.object(api, 'request_license_data')
30-
def test_get_license_details_from_api(self, mock_data):
42+
def test_api_get_license_details_from_api(self, mock_data):
3143
license_data = {
3244
'name': 'Apache License 2.0',
3345
'full_text': 'Apache License Version 2.0 ...',
@@ -39,3 +51,19 @@ def test_get_license_details_from_api(self, mock_data):
3951
expected = ('Apache License 2.0', 'apache-2.0', 'Apache License Version 2.0 ...', [])
4052
result = api.get_license_details_from_api('url', 'api_key', 'license_key')
4153
assert expected == result
54+
55+
@patch.object(api, 'urlopen')
56+
def test_api_request_license_data(self, mock_data):
57+
response_content = (
58+
b'{"count":1,"results":[{"name":"Apache 2.0","key":"apache-2.0","text":"Text"}]}'
59+
)
60+
mock_data.return_value = FakeResponse(response_content)
61+
license_data = api.request_license_data('http://fake.url/', 'api_key', 'apache-2.0')
62+
expected = ({'name': 'Apache 2.0', 'key': 'apache-2.0', 'text': 'Text'}, [])
63+
assert expected == license_data
64+
65+
response_content = b'{"count":0,"results":[]}'
66+
mock_data.return_value = FakeResponse(response_content)
67+
license_data = api.request_license_data('http://fake.url/', 'api_key', 'apache-2.0')
68+
expected = ({}, [Error(ERROR, "Invalid 'license': apache-2.0")])
69+
assert expected == license_data

0 commit comments

Comments
 (0)