Skip to content

Commit c4cc41e

Browse files
committed
Streamline API call test and code
* add docstrings * mionr variable renaming * split tests finctions Signed-off-by: Philippe Ombredanne <[email protected]>
1 parent 67926e6 commit c4cc41e

File tree

2 files changed

+59
-26
lines changed

2 files changed

+59
-26
lines changed

src/attributecode/api.py

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -20,28 +20,35 @@
2020

2121
import json
2222

23-
try: # Python 2
24-
from urllib import urlencode, quote
25-
from urllib2 import urlopen, Request, HTTPError
26-
except ImportError: # Python 3
27-
from urllib.parse import urlencode, quote
28-
from urllib.request import urlopen, Request
29-
from urllib.error import HTTPError
30-
3123
from attributecode import ERROR
3224
from attributecode import Error
25+
from attributecode.util import python2
26+
27+
28+
if python2:
29+
from urllib import quote # NOQA
30+
from urllib import urlencode # NOQA
31+
from urllib2 import HTTPError # NOQA
32+
from urllib2 import Request # NOQA
33+
from urllib2 import urlopen # NOQA
34+
else:
35+
from urllib.parse import quote # NOQA
36+
from urllib.parse import urlencode # NOQA
37+
from urllib.request import Request # NOQA
38+
from urllib.request import urlopen # NOQA
39+
from urllib.error import HTTPError # NOQA
3340

3441

3542
"""
3643
API call helpers
3744
"""
3845

3946

40-
def request_license_data(url, api_key, license_key):
47+
# FIXME: args should start with license_key
48+
def request_license_data(api_url, api_key, license_key):
4149
"""
42-
Return a dictionary of license data.
43-
Send a request to a given API URL to gather license data for
44-
license_key, authenticating through an api_key.
50+
Return a tuple of (dictionary of license data, list of errors) given a
51+
`license_key`. Send a request to `api_url` authenticating with `api_key`.
4552
"""
4653
headers = {
4754
'Authorization': 'Token %s' % api_key,
@@ -52,9 +59,10 @@ def request_license_data(url, api_key, license_key):
5259
'format': 'json'
5360
}
5461

55-
url = url.rstrip('/')
56-
encoded_payload = urlencode(payload)
57-
full_url = '%(url)s/?%(encoded_payload)s' % locals()
62+
api_url = api_url.rstrip('/')
63+
payload = urlencode(payload)
64+
65+
full_url = '%(api_url)s/?%(payload)s' % locals()
5866
# handle special characters in URL such as space etc.
5967
quoted_url = quote(full_url, safe="%/:=&?~#+!$,;'@()*[]")
6068

@@ -64,10 +72,12 @@ def request_license_data(url, api_key, license_key):
6472
request = Request(quoted_url, headers=headers)
6573
response = urlopen(request)
6674
response_content = response.read().decode('utf-8')
75+
# FIXME: this should be an ordered dict
6776
license_data = json.loads(response_content)
6877
if not license_data['results']:
6978
msg = u"Invalid 'license': %s" % license_key
7079
errors.append(Error(ERROR, msg))
80+
7181
except HTTPError as http_e:
7282
# some auth problem
7383
if http_e.code == 403:
@@ -80,20 +90,29 @@ def request_license_data(url, api_key, license_key):
8090
# this exception.
8191
msg = u"Invalid 'license': %s" % license_key
8292
errors.append(Error(ERROR, msg))
93+
8394
except Exception as e:
8495
errors.append(Error(ERROR, str(e)))
96+
8597
finally:
86-
license_data = license_data.get('results')[0] if license_data.get('count') == 1 else {}
98+
if license_data.get('count') == 1:
99+
license_data = license_data.get('results')[0]
100+
else:
101+
license_data = {}
87102

88103
return license_data, errors
89104

90105

91-
def get_license_details_from_api(url, api_key, license_key):
106+
# FIXME: args should start with license_key
107+
def get_license_details_from_api(api_url, api_key, license_key):
92108
"""
93-
Return the license_text of a given license_key using an API request.
94-
Return an empty string if the text is not available.
109+
Return a tuple of license data given a `license_key` using the `api_url`
110+
authenticating with `api_key`.
111+
The details are a tuple of (license_name, license_key, license_text, errors)
112+
where errors is a list of strings.
113+
Missing values are provided as empty strings.
95114
"""
96-
license_data, errors = request_license_data(url, api_key, license_key)
115+
license_data, errors = request_license_data(api_url, api_key, license_key)
97116
license_name = license_data.get('name', '')
98117
license_text = license_data.get('full_text', '')
99118
license_key = license_data.get('key', '')

tests/test_api.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ def __init__(self, response_content):
3636
def read(self):
3737
return self.response_content
3838

39+
3940
class ApiTest(unittest.TestCase):
41+
4042
@mock.patch.object(api, 'request_license_data')
4143
def test_api_get_license_details_from_api(self, request_license_data):
4244
license_data = {
@@ -47,22 +49,34 @@ def test_api_get_license_details_from_api(self, request_license_data):
4749
errors = []
4850
request_license_data.return_value = license_data, errors
4951

50-
expected = ('Apache License 2.0', 'apache-2.0', 'Apache License Version 2.0 ...', [])
51-
result = api.get_license_details_from_api('url', 'api_key', 'license_key')
52+
expected = (
53+
'Apache License 2.0',
54+
'apache-2.0',
55+
'Apache License Version 2.0 ...',
56+
[])
57+
result = api.get_license_details_from_api(
58+
api_url='api_url', api_key='api_key', license_key='license_key')
5259
assert expected == result
5360

5461
@mock.patch.object(api, 'urlopen')
55-
def test_api_request_license_data(self, mock_data):
62+
def test_api_request_license_data_with_result(self, mock_data):
5663
response_content = (
5764
b'{"count":1,"results":[{"name":"Apache 2.0","key":"apache-2.0","text":"Text"}]}'
5865
)
5966
mock_data.return_value = FakeResponse(response_content)
60-
license_data = api.request_license_data('http://fake.url/', 'api_key', 'apache-2.0')
61-
expected = ({'name': 'Apache 2.0', 'key': 'apache-2.0', 'text': 'Text'}, [])
67+
license_data = api.request_license_data(
68+
api_url='http://fake.url/', api_key='api_key', license_key='apache-2.0')
69+
expected = (
70+
{'name': 'Apache 2.0', 'key': 'apache-2.0', 'text': 'Text'},
71+
[]
72+
)
6273
assert expected == license_data
6374

75+
@mock.patch.object(api, 'urlopen')
76+
def test_api_request_license_data_without_result(self, mock_data):
6477
response_content = b'{"count":0,"results":[]}'
6578
mock_data.return_value = FakeResponse(response_content)
66-
license_data = api.request_license_data('http://fake.url/', 'api_key', 'apache-2.0')
79+
license_data = api.request_license_data(
80+
api_url='http://fake.url/', api_key='api_key', license_key='apache-2.0')
6781
expected = ({}, [Error(ERROR, "Invalid 'license': apache-2.0")])
6882
assert expected == license_data

0 commit comments

Comments
 (0)