Merge lp:~elachuni/piston-mini-client/fix-tests into lp:piston-mini-client

Proposed by Anthony Lenton
Status: Merged
Approved by: Anthony Lenton
Approved revision: 66
Merged at revision: 61
Proposed branch: lp:~elachuni/piston-mini-client/fix-tests
Merge into: lp:piston-mini-client
Diff against target: 672 lines (+123/-102)
13 files modified
piston_mini_client/__init__.py (+25/-24)
piston_mini_client/auth.py (+3/-2)
piston_mini_client/failhandlers.py (+2/-2)
piston_mini_client/tests/test_auth.py (+5/-0)
piston_mini_client/tests/test_disable_ssl_check.py (+3/-3)
piston_mini_client/tests/test_failhandlers.py (+4/-4)
piston_mini_client/tests/test_log_to_file.py (+3/-3)
piston_mini_client/tests/test_pep8.py (+21/-28)
piston_mini_client/tests/test_resource.py (+39/-26)
piston_mini_client/tests/test_serializers.py (+1/-1)
piston_mini_client/tests/test_timeout.py (+4/-4)
piston_mini_client/tests/test_validators.py (+8/-2)
piston_mini_client/validators.py (+5/-3)
To merge this branch: bzr merge lp:~elachuni/piston-mini-client/fix-tests
Reviewer Review Type Date Requested Status
Jonathan Lange (community) Approve
software-store-developers Pending
Review via email: mp+117306@code.launchpad.net

Commit message

Made tests pass with the latest pep8 release.

Description of the change

This branch fixes the tests that were failing in trunk:
 - The latest pep8 release changes the internal layout of the module, so the test that uses it needed to apply matching changes.
 - oauth is still broken on Python 3 (it attempts to import urlparse, for starters), so the OAuth test is skipped on Python 3.

To post a comment you must log in.
Revision history for this message
Jonathan Lange (jml) wrote :

Looks good to me. Thanks.

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'piston_mini_client/__init__.py'
--- piston_mini_client/__init__.py 2012-07-30 15:59:14 +0000
+++ piston_mini_client/__init__.py 2012-07-30 17:16:48 +0000
@@ -212,8 +212,8 @@
212 data = {}212 data = {}
213 for att in self._atts:213 for att in self._atts:
214 if not hasattr(self, att):214 if not hasattr(self, att):
215 raise ValueError("Attempted to serialize attribute '%s'"215 raise ValueError(
216 % att)216 "Attempted to serialize attribute '%s'" % att)
217 data[att] = getattr(self, att)217 data[att] = getattr(self, att)
218 return data218 return data
219219
@@ -333,8 +333,8 @@
333 def _get_http_obj_for_scheme(self, scheme):333 def _get_http_obj_for_scheme(self, scheme):
334 proxy_info = self._get_proxy_info(scheme)334 proxy_info = self._get_proxy_info(scheme)
335 http = None335 http = None
336 if (self._disable_ssl_validation or336 check_disabled_in_env = os.environ.get(DISABLE_SSL_VALIDATION_ENVVAR)
337 os.environ.get(DISABLE_SSL_VALIDATION_ENVVAR)):337 if self._disable_ssl_validation or check_disabled_in_env:
338 try:338 try:
339 http = httplib2.Http(339 http = httplib2.Http(
340 cache=self._httplib2_cache,340 cache=self._httplib2_cache,
@@ -346,7 +346,7 @@
346 pass346 pass
347 if http is None:347 if http is None:
348 http = httplib2.Http(cache=self._httplib2_cache,348 http = httplib2.Http(cache=self._httplib2_cache,
349 timeout=self._timeout, proxy_info=proxy_info)349 timeout=self._timeout, proxy_info=proxy_info)
350 return http350 return http
351351
352 def _get_proxy_info(self, scheme):352 def _get_proxy_info(self, scheme):
@@ -396,10 +396,10 @@
396 path += urlencode(args)396 path += urlencode(args)
397 headers = self._prepare_headers(extra_headers=extra_headers)397 headers = self._prepare_headers(extra_headers=extra_headers)
398 return self._request(path, method='GET', scheme=scheme,398 return self._request(path, method='GET', scheme=scheme,
399 headers=headers)399 headers=headers)
400400
401 def _post(self, path, data=None, content_type=None, scheme=None,401 def _post(self, path, data=None, content_type=None, scheme=None,
402 extra_headers=None):402 extra_headers=None):
403 """Perform an HTTP POST request.403 """Perform an HTTP POST request.
404404
405 The provided ``path`` is appended to this api's ``_service_root``405 The provided ``path`` is appended to this api's ``_service_root``
@@ -424,12 +424,12 @@
424 will be added to the http request.424 will be added to the http request.
425 """425 """
426 body, headers = self._prepare_request(data, content_type,426 body, headers = self._prepare_request(data, content_type,
427 extra_headers=extra_headers)427 extra_headers=extra_headers)
428 return self._request(path, method='POST', body=body,428 return self._request(path, method='POST', body=body,
429 headers=headers, scheme=scheme)429 headers=headers, scheme=scheme)
430430
431 def _put(self, path, data=None, content_type=None, scheme=None,431 def _put(self, path, data=None, content_type=None, scheme=None,
432 extra_headers=None):432 extra_headers=None):
433 """Perform an HTTP PUT request.433 """Perform an HTTP PUT request.
434434
435 The provided ``path`` is appended to this api's ``_service_root``435 The provided ``path`` is appended to this api's ``_service_root``
@@ -454,9 +454,9 @@
454 will be added to the http request.454 will be added to the http request.
455 """455 """
456 body, headers = self._prepare_request(data, content_type,456 body, headers = self._prepare_request(data, content_type,
457 extra_headers=extra_headers)457 extra_headers=extra_headers)
458 return self._request(path, method='PUT', body=body,458 return self._request(path, method='PUT', body=body,
459 headers=headers, scheme=scheme)459 headers=headers, scheme=scheme)
460460
461 def _delete(self, path, scheme=None, extra_headers=None):461 def _delete(self, path, scheme=None, extra_headers=None):
462 """Perform an HTTP DELETE request.462 """Perform an HTTP DELETE request.
@@ -473,10 +473,10 @@
473 """473 """
474 headers = self._prepare_headers(extra_headers=extra_headers)474 headers = self._prepare_headers(extra_headers=extra_headers)
475 return self._request(path, method='DELETE', scheme=scheme,475 return self._request(path, method='DELETE', scheme=scheme,
476 headers=headers)476 headers=headers)
477477
478 def _prepare_request(self, data=None, content_type=None,478 def _prepare_request(self, data=None, content_type=None,
479 extra_headers=None):479 extra_headers=None):
480 """Put together a set of headers and a body for a request.480 """Put together a set of headers and a body for a request.
481481
482 If ``content_type`` is not provided, ``self.default_content_type``482 If ``content_type`` is not provided, ``self.default_content_type``
@@ -550,8 +550,8 @@
550 if self.log_filename:550 if self.log_filename:
551 self._dump_request(url, method, body, headers)551 self._dump_request(url, method, body, headers)
552 try:552 try:
553 response, response_body = self._http[scheme].request(url,553 response, response_body = self._http[scheme].request(
554 method=method, body=body, headers=headers)554 url, method=method, body=body, headers=headers)
555 except AttributeError as e:555 except AttributeError as e:
556 # Special case out httplib2's way of telling us unable to connect556 # Special case out httplib2's way of telling us unable to connect
557 if e.args[0] == "'NoneType' object has no attribute 'makefile'":557 if e.args[0] == "'NoneType' object has no attribute 'makefile'":
@@ -560,10 +560,10 @@
560 raise560 raise
561 except socket.timeout as e:561 except socket.timeout as e:
562 raise TimeoutError('Timed out attempting to connect to %s' %562 raise TimeoutError('Timed out attempting to connect to %s' %
563 self._service_root)563 self._service_root)
564 except (socket.gaierror, socket.error) as e:564 except (socket.gaierror, socket.error) as e:
565 raise SocketError('connecting to %s: %s' % (self._service_root,565 msg = 'connecting to %s: %s' % (self._service_root, e.message)
566 e.message))566 raise SocketError(msg)
567 if self.log_filename:567 if self.log_filename:
568 self._dump_response(response, response_body)568 self._dump_response(response, response_body)
569 handler = self.fail_handler(url, method, body, headers)569 handler = self.fail_handler(url, method, body, headers)
@@ -573,16 +573,16 @@
573 def _dump_request(self, url, method, body, headers):573 def _dump_request(self, url, method, body, headers):
574 try:574 try:
575 with open(self.log_filename, 'a') as f:575 with open(self.log_filename, 'a') as f:
576 f.write("{0}: {1}".format(datetime.now(),576 formatted = format_request(url, method, body, headers)
577 format_request(url, method, body, headers)))577 f.write("{0}: {1}".format(datetime.now(), formatted))
578 except IOError:578 except IOError:
579 pass579 pass
580580
581 def _dump_response(self, response, body):581 def _dump_response(self, response, body):
582 try:582 try:
583 with open(self.log_filename, 'a') as f:583 with open(self.log_filename, 'a') as f:
584 f.write("{0}: {1}".format(datetime.now(),584 formatted = format_response(response, body)
585 format_response(response, body)))585 f.write("{0}: {1}".format(datetime.now(), formatted))
586 except IOError:586 except IOError:
587 pass587 pass
588588
@@ -595,7 +595,8 @@
595 cached_value = self._http[scheme].cache.get(595 cached_value = self._http[scheme].cache.get(
596 httplib2.urlnorm(url)[-1])596 httplib2.urlnorm(url)[-1])
597 if cached_value:597 if cached_value:
598 info, content = cached_value.decode("utf-8").split('\r\n\r\n', 1)598 info, content = cached_value.decode("utf-8").split(
599 '\r\n\r\n', 1)
599 return content600 return content
600601
601 def _path2url(self, path, scheme=None):602 def _path2url(self, path, scheme=None):
602603
=== modified file 'piston_mini_client/auth.py'
--- piston_mini_client/auth.py 2012-06-14 08:19:19 +0000
+++ piston_mini_client/auth.py 2012-07-30 17:16:48 +0000
@@ -12,6 +12,7 @@
1212
13import base6413import base64
1414
15
15class OAuthAuthorizer(object):16class OAuthAuthorizer(object):
16 """Authenticate to OAuth protected APIs."""17 """Authenticate to OAuth protected APIs."""
17 def __init__(self, token_key, token_secret, consumer_key, consumer_secret,18 def __init__(self, token_key, token_secret, consumer_key, consumer_secret,
@@ -33,13 +34,13 @@
33 # Import oauth here so that you don't need it if you're not going34 # Import oauth here so that you don't need it if you're not going
34 # to use it. Plan B: move this out into a separate oauth module.35 # to use it. Plan B: move this out into a separate oauth module.
35 from oauth.oauth import (OAuthRequest, OAuthConsumer, OAuthToken,36 from oauth.oauth import (OAuthRequest, OAuthConsumer, OAuthToken,
36 OAuthSignatureMethod_PLAINTEXT)37 OAuthSignatureMethod_PLAINTEXT)
37 consumer = OAuthConsumer(self.consumer_key, self.consumer_secret)38 consumer = OAuthConsumer(self.consumer_key, self.consumer_secret)
38 token = OAuthToken(self.token_key, self.token_secret)39 token = OAuthToken(self.token_key, self.token_secret)
39 oauth_request = OAuthRequest.from_consumer_and_token(40 oauth_request = OAuthRequest.from_consumer_and_token(
40 consumer, token, http_url=url)41 consumer, token, http_url=url)
41 oauth_request.sign_request(OAuthSignatureMethod_PLAINTEXT(),42 oauth_request.sign_request(OAuthSignatureMethod_PLAINTEXT(),
42 consumer, token)43 consumer, token)
43 headers.update(oauth_request.to_header(self.oauth_realm))44 headers.update(oauth_request.to_header(self.oauth_realm))
4445
4546
4647
=== modified file 'piston_mini_client/failhandlers.py'
--- piston_mini_client/failhandlers.py 2012-07-19 15:38:19 +0000
+++ piston_mini_client/failhandlers.py 2012-07-30 17:16:48 +0000
@@ -113,7 +113,7 @@
113 raise APIError('No status code in response')113 raise APIError('No status code in response')
114 if self.was_error(response):114 if self.was_error(response):
115 raise APIError('%s: %s' % (response['status'], response), body,115 raise APIError('%s: %s' % (response['status'], response), body,
116 data=self.data)116 data=self.data)
117 return body117 return body
118118
119119
@@ -197,5 +197,5 @@
197 status = response.get('status')197 status = response.get('status')
198 exception_class = self.exceptions.get(status, APIError)198 exception_class = self.exceptions.get(status, APIError)
199 raise exception_class('%s: %s' % (status, response), body,199 raise exception_class('%s: %s' % (status, response), body,
200 data=self.data)200 data=self.data)
201 return body201 return body
202202
=== modified file 'piston_mini_client/tests/test_auth.py'
--- piston_mini_client/tests/test_auth.py 2012-06-14 08:19:19 +0000
+++ piston_mini_client/tests/test_auth.py 2012-07-30 17:16:48 +0000
@@ -2,6 +2,7 @@
2# Copyright 2010-2012 Canonical Ltd. This software is licensed under the2# Copyright 2010-2012 Canonical Ltd. This software is licensed under the
3# GNU Lesser General Public License version 3 (see the file LICENSE).3# GNU Lesser General Public License version 3 (see the file LICENSE).
44
5import sys
5from piston_mini_client.auth import OAuthAuthorizer, BasicAuthorizer6from piston_mini_client.auth import OAuthAuthorizer, BasicAuthorizer
6from unittest import TestCase7from unittest import TestCase
78
@@ -19,6 +20,10 @@
1920
20class OAuthAuthorizerTestCase(TestCase):21class OAuthAuthorizerTestCase(TestCase):
21 def test_sign_request(self):22 def test_sign_request(self):
23 if sys.version_info[0] == 3:
24 # Skip on Python 3 as oauth is still broken there.
25 # don't use skipIf as it's missing on python2.6
26 return
22 auth = OAuthAuthorizer('tkey', 'tsecret', 'ckey', 'csecret')27 auth = OAuthAuthorizer('tkey', 'tsecret', 'ckey', 'csecret')
23 url = 'http://example.com/api'28 url = 'http://example.com/api'
24 headers = {}29 headers = {}
2530
=== modified file 'piston_mini_client/tests/test_disable_ssl_check.py'
--- piston_mini_client/tests/test_disable_ssl_check.py 2012-03-30 17:17:49 +0000
+++ piston_mini_client/tests/test_disable_ssl_check.py 2012-07-30 17:16:48 +0000
@@ -35,14 +35,14 @@
35 api = DentistAPI()35 api = DentistAPI()
3636
37 self.assertTrue('disable_ssl_certificate_validation' not in37 self.assertTrue('disable_ssl_certificate_validation' not in
38 mock_http.call_args[1])38 mock_http.call_args[1])
3939
40 @patch('httplib2.Http')40 @patch('httplib2.Http')
41 def test_disable_via_constructor(self, mock_http):41 def test_disable_via_constructor(self, mock_http):
42 api = DentistAPI(disable_ssl_validation=True)42 api = DentistAPI(disable_ssl_validation=True)
4343
44 self.assertTrue('disable_ssl_certificate_validation' in44 self.assertTrue('disable_ssl_certificate_validation' in
45 mock_http.call_args[1])45 mock_http.call_args[1])
4646
47 @patch('httplib2.Http')47 @patch('httplib2.Http')
48 def test_disable_via_envvar(self, mock_http):48 def test_disable_via_envvar(self, mock_http):
@@ -50,4 +50,4 @@
50 api = DentistAPI()50 api = DentistAPI()
5151
52 self.assertTrue('disable_ssl_certificate_validation' in52 self.assertTrue('disable_ssl_certificate_validation' in
53 mock_http.call_args[1])53 mock_http.call_args[1])
5454
=== modified file 'piston_mini_client/tests/test_failhandlers.py'
--- piston_mini_client/tests/test_failhandlers.py 2012-07-19 15:56:33 +0000
+++ piston_mini_client/tests/test_failhandlers.py 2012-07-30 17:16:48 +0000
@@ -120,7 +120,7 @@
120 handler = ExceptionFailHandler('/foo', 'GET', '', {})120 handler = ExceptionFailHandler('/foo', 'GET', '', {})
121 for status in bad_status:121 for status in bad_status:
122 self.assertRaises(APIError, handler.handle,122 self.assertRaises(APIError, handler.handle,
123 {'status': status}, '')123 {'status': status}, '')
124124
125125
126class NoneFailHandlerTestCase(TestCase):126class NoneFailHandlerTestCase(TestCase):
@@ -253,7 +253,7 @@
253 mock_request.return_value = {'status': '200'}, '{"foo": "bar"}'253 mock_request.return_value = {'status': '200'}, '{"foo": "bar"}'
254254
255 self.assertTrue(isinstance(self.api.get_plant(),255 self.assertTrue(isinstance(self.api.get_plant(),
256 PistonResponseObject))256 PistonResponseObject))
257257
258 @patch('httplib2.Http.request')258 @patch('httplib2.Http.request')
259 def test_interacts_well_with_returns_list_of(self, mock_request):259 def test_interacts_well_with_returns_list_of(self, mock_request):
@@ -285,7 +285,7 @@
285 handler = MultiExceptionFailHandler('/foo', 'GET', '', {})285 handler = MultiExceptionFailHandler('/foo', 'GET', '', {})
286 for status, exception in bad_status.items():286 for status, exception in bad_status.items():
287 self.assertRaises(exception, handler.handle, {'status': status},287 self.assertRaises(exception, handler.handle, {'status': status},
288 '')288 '')
289289
290 @patch('httplib2.Http.request')290 @patch('httplib2.Http.request')
291 def test_interacts_well_with_returns_json_on_fail(self, mock_request):291 def test_interacts_well_with_returns_json_on_fail(self, mock_request):
@@ -324,7 +324,7 @@
324 mock_request.return_value = {'status': '200'}, '{"foo": "bar"}'324 mock_request.return_value = {'status': '200'}, '{"foo": "bar"}'
325325
326 self.assertTrue(isinstance(self.api.get_plant(),326 self.assertTrue(isinstance(self.api.get_plant(),
327 PistonResponseObject))327 PistonResponseObject))
328328
329 @patch('httplib2.Http.request')329 @patch('httplib2.Http.request')
330 def test_interacts_well_with_returns_list_of(self, mock_request):330 def test_interacts_well_with_returns_list_of(self, mock_request):
331331
=== modified file 'piston_mini_client/tests/test_log_to_file.py'
--- piston_mini_client/tests/test_log_to_file.py 2012-06-14 08:10:28 +0000
+++ piston_mini_client/tests/test_log_to_file.py 2012-07-30 17:16:48 +0000
@@ -19,14 +19,14 @@
19 @returns_json19 @returns_json
20 def poke(self, data=None):20 def poke(self, data=None):
21 return self._post('/poke/', data=data,21 return self._post('/poke/', data=data,
22 extra_headers={'location': 'ribs'})22 extra_headers={'location': 'ribs'})
2323
2424
25class LogToFileTestCase(TestCase):25class LogToFileTestCase(TestCase):
26 @patch('httplib2.Http.request')26 @patch('httplib2.Http.request')
27 def test_requests_are_dumped_to_file(self, mock_request):27 def test_requests_are_dumped_to_file(self, mock_request):
28 mock_request.return_value = ({'status': '201', 'x-foo': 'bar'},28 mock_request.return_value = ({'status': '201', 'x-foo': 'bar'},
29 '"Go away!"')29 '"Go away!"')
3030
31 with NamedTemporaryFile() as fp:31 with NamedTemporaryFile() as fp:
32 api = AnnoyAPI(log_filename=fp.name)32 api = AnnoyAPI(log_filename=fp.name)
@@ -41,7 +41,7 @@
41 self.assertTrue(lines[0].endswith(41 self.assertTrue(lines[0].endswith(
42 'Request: POST http://test.info/api/1.0/poke/'))42 'Request: POST http://test.info/api/1.0/poke/'))
43 self.assertEqual(['Content-type: application/json',43 self.assertEqual(['Content-type: application/json',
44 'location: ribs', '', '[1, 2, 3]'], lines[1:5])44 'location: ribs', '', '[1, 2, 3]'], lines[1:5])
45 self.assertTrue(lines[5].endswith('Response: 201'))45 self.assertTrue(lines[5].endswith('Response: 201'))
46 self.assertEqual(['x-foo: bar', '', '"Go away!"', ''], lines[6:])46 self.assertEqual(['x-foo: bar', '', '"Go away!"', ''], lines[6:])
4747
4848
=== modified file 'piston_mini_client/tests/test_pep8.py'
--- piston_mini_client/tests/test_pep8.py 2012-03-30 17:17:49 +0000
+++ piston_mini_client/tests/test_pep8.py 2012-07-30 17:16:48 +0000
@@ -15,36 +15,29 @@
15 packages = [piston_mini_client]15 packages = [piston_mini_client]
16 exclude = ['socks.py'] # Leave 3rd party dep. alone.16 exclude = ['socks.py'] # Leave 3rd party dep. alone.
1717
18 def message(self, text):
19 self.errors.append(text)
20
21 def setUp(self):
22 self.errors = []
23
24 class Options(object):
25 exclude = self.exclude
26 filename = ['*.py']
27 testsuite = ''
28 doctest = ''
29 counters = defaultdict(int)
30 messages = {}
31 verbose = 0
32 quiet = 0
33 repeat = True
34 show_source = False
35 show_pep8 = False
36 select = []
37 ignore = []
38 max_line_length = 79
39 pep8.options = Options()
40 pep8.message = self.message
41 Options.physical_checks = pep8.find_checks('physical_line')
42 Options.logical_checks = pep8.find_checks('logical_line')
43
44 def test_all_code(self):18 def test_all_code(self):
19 pep8style = pep8.StyleGuide(
20 counters=defaultdict(int),
21 doctest='',
22 exclude=self.exclude,
23 filename=['*.py'],
24 ignore=[],
25 messages={},
26 repeat=True,
27 select=[],
28 show_pep8=False,
29 show_source=False,
30 max_line_length=79,
31 quiet=0,
32 statistics=False,
33 testsuite='',
34 verbose=0,
35 )
36
45 for package in self.packages:37 for package in self.packages:
46 pep8.input_dir(os.path.dirname(package.__file__))38 pep8style.input_dir(os.path.dirname(package.__file__))
47 self.assertEqual([], self.errors)39 self.assertEqual(pep8style.options.report.total_errors, 0)
40
4841
49if __name__ == "__main__":42if __name__ == "__main__":
50 unittest.main()43 unittest.main()
5144
=== modified file 'piston_mini_client/tests/test_resource.py'
--- piston_mini_client/tests/test_resource.py 2012-07-30 15:59:14 +0000
+++ piston_mini_client/tests/test_resource.py 2012-07-30 17:16:48 +0000
@@ -27,11 +27,11 @@
2727
28 @patch('httplib2.Http.request')28 @patch('httplib2.Http.request')
29 def test_request(self, mock_request):29 def test_request(self, mock_request):
30 mock_request.return_value = ({'status': '200'30 mock_request.return_value = ({'status': '200'}, 'hello world!')
31 }, 'hello world!')
32 api = self.CoffeeAPI()31 api = self.CoffeeAPI()
33 api._request('/foo', 'POST', body='foo=bar')32 api._request('/foo', 'POST', body='foo=bar')
34 mock_request.assert_called_with('http://localhost:12345/foo',33 mock_request.assert_called_with(
34 'http://localhost:12345/foo',
35 body='foo=bar', headers={}, method='POST')35 body='foo=bar', headers={}, method='POST')
3636
37 @patch('httplib2.Http.request')37 @patch('httplib2.Http.request')
@@ -68,7 +68,8 @@
68 cache = httplib2.FileCache(tmpdir, safe=safename)68 cache = httplib2.FileCache(tmpdir, safe=safename)
69 http = httplib2.Http(cache=cache)69 http = httplib2.Http(cache=cache)
70 cachekey = self.CoffeeAPI.default_service_root + path70 cachekey = self.CoffeeAPI.default_service_root + path
71 http.cache.set(cachekey.encode('utf-8'),71 http.cache.set(
72 cachekey.encode('utf-8'),
72 "header\r\n\r\nmy_cached_body_from_long_path\n".encode('utf-8'))73 "header\r\n\r\nmy_cached_body_from_long_path\n".encode('utf-8'))
73 # ensure that we trigger a error like when offline (no dns)74 # ensure that we trigger a error like when offline (no dns)
74 mock_request.side_effect = httplib2.ServerNotFoundError("")75 mock_request.side_effect = httplib2.ServerNotFoundError("")
@@ -83,11 +84,11 @@
83 def test_auth_request(self, mock_request):84 def test_auth_request(self, mock_request):
84 mock_request.return_value = ({'status': '200'}, '""')85 mock_request.return_value = ({'status': '200'}, '""')
85 api = self.CoffeeAPI(auth=BasicAuthorizer(username='foo',86 api = self.CoffeeAPI(auth=BasicAuthorizer(username='foo',
86 password='bar'))87 password='bar'))
87 api._request('/fee', 'GET')88 api._request('/fee', 'GET')
88 kwargs = mock_request.call_args[1]89 kwargs = mock_request.call_args[1]
89 self.assertEqual(kwargs['headers']['Authorization'],90 self.assertEqual(kwargs['headers']['Authorization'],
90 'Basic Zm9vOmJhcg==')91 'Basic Zm9vOmJhcg==')
91 self.assertEqual(kwargs['method'], 'GET')92 self.assertEqual(kwargs['method'], 'GET')
9293
93 @patch('httplib2.Http.request')94 @patch('httplib2.Http.request')
@@ -116,10 +117,10 @@
116 mock_request.return_value = ({'status': '200'}, '""')117 mock_request.return_value = ({'status': '200'}, '""')
117 api = self.CoffeeAPI()118 api = self.CoffeeAPI()
118 api._post('/serve', data={'foo': 'bar'},119 api._post('/serve', data={'foo': 'bar'},
119 content_type='application/x-www-form-urlencoded')120 content_type='application/x-www-form-urlencoded')
120 kwargs = mock_request.call_args[1]121 kwargs = mock_request.call_args[1]
121 self.assertEqual(kwargs['headers']['Content-type'],122 self.assertEqual(kwargs['headers']['Content-type'],
122 'application/x-www-form-urlencoded')123 'application/x-www-form-urlencoded')
123 self.assertEqual(kwargs['method'], 'POST')124 self.assertEqual(kwargs['method'], 'POST')
124125
125 @patch('httplib2.Http.request')126 @patch('httplib2.Http.request')
@@ -150,7 +151,7 @@
150 body = api._get('/simmer')151 body = api._get('/simmer')
151 self.assertEqual(expected_body, body)152 self.assertEqual(expected_body, body)
152 mock_request.assert_called_with('http://localhost:12345/simmer',153 mock_request.assert_called_with('http://localhost:12345/simmer',
153 body='', headers={}, method='GET')154 body='', headers={}, method='GET')
154155
155 @patch('httplib2.Http.request')156 @patch('httplib2.Http.request')
156 def test_get_with_extra_args(self, mock_request):157 def test_get_with_extra_args(self, mock_request):
@@ -187,7 +188,7 @@
187 api = self.CoffeeAPI()188 api = self.CoffeeAPI()
188 api._request('/foo', 'GET', scheme='https')189 api._request('/foo', 'GET', scheme='https')
189 mock_request.assert_called_with('https://localhost:12345/foo',190 mock_request.assert_called_with('https://localhost:12345/foo',
190 body='', headers={}, method='GET')191 body='', headers={}, method='GET')
191192
192 @patch('httplib2.Http.request')193 @patch('httplib2.Http.request')
193 def test_get_scheme_switch_to_https(self, mock_request):194 def test_get_scheme_switch_to_https(self, mock_request):
@@ -195,14 +196,15 @@
195 api = self.CoffeeAPI()196 api = self.CoffeeAPI()
196 api._get('/foo', scheme='https')197 api._get('/foo', scheme='https')
197 mock_request.assert_called_with('https://localhost:12345/foo',198 mock_request.assert_called_with('https://localhost:12345/foo',
198 body='', headers={}, method='GET')199 body='', headers={}, method='GET')
199200
200 @patch('httplib2.Http.request')201 @patch('httplib2.Http.request')
201 def test_post_scheme_switch_to_https(self, mock_request):202 def test_post_scheme_switch_to_https(self, mock_request):
202 mock_request.return_value = ({'status': '200'}, '""')203 mock_request.return_value = ({'status': '200'}, '""')
203 api = self.CoffeeAPI()204 api = self.CoffeeAPI()
204 api._post('/foo', scheme='https')205 api._post('/foo', scheme='https')
205 mock_request.assert_called_with('https://localhost:12345/foo',206 mock_request.assert_called_with(
207 'https://localhost:12345/foo',
206 body='null', headers={'Content-type': 'application/json'},208 body='null', headers={'Content-type': 'application/json'},
207 method='POST')209 method='POST')
208210
@@ -250,7 +252,8 @@
250 mock_request.return_value = ({'status': '200'}, '""')252 mock_request.return_value = ({'status': '200'}, '""')
251 api = self.CoffeeAPI()253 api = self.CoffeeAPI()
252 api._put('/foo', scheme='https')254 api._put('/foo', scheme='https')
253 mock_request.assert_called_with('https://localhost:12345/foo',255 mock_request.assert_called_with(
256 'https://localhost:12345/foo',
254 body='null', headers={'Content-type': 'application/json'},257 body='null', headers={'Content-type': 'application/json'},
255 method='PUT')258 method='PUT')
256259
@@ -259,11 +262,11 @@
259 mock_request.return_value = ({'status': '200'}, '""')262 mock_request.return_value = ({'status': '200'}, '""')
260 api = self.CoffeeAPI()263 api = self.CoffeeAPI()
261 api._put('/serve', data={'foo': 'bar'},264 api._put('/serve', data={'foo': 'bar'},
262 content_type='application/x-www-form-urlencoded')265 content_type='application/x-www-form-urlencoded')
263 kwargs = mock_request.call_args[1]266 kwargs = mock_request.call_args[1]
264 self.assertEqual(kwargs['body'], 'foo=bar')267 self.assertEqual(kwargs['body'], 'foo=bar')
265 self.assertEqual(kwargs['headers']['Content-type'],268 self.assertEqual(kwargs['headers']['Content-type'],
266 'application/x-www-form-urlencoded')269 'application/x-www-form-urlencoded')
267 self.assertEqual(kwargs['method'], 'PUT')270 self.assertEqual(kwargs['method'], 'PUT')
268271
269 @patch('httplib2.Http.request')272 @patch('httplib2.Http.request')
@@ -273,17 +276,21 @@
273 api.extra_headers = {'X-Foo': 'bar'}276 api.extra_headers = {'X-Foo': 'bar'}
274 api._get('/foo')277 api._get('/foo')
275 expected_headers = {'X-Foo': 'bar'}278 expected_headers = {'X-Foo': 'bar'}
276 mock_request.assert_called_with('http://localhost:12345/foo',279 mock_request.assert_called_with(
280 'http://localhost:12345/foo',
277 body='', headers=expected_headers, method='GET')281 body='', headers=expected_headers, method='GET')
278 api._delete('/foo')282 api._delete('/foo')
279 mock_request.assert_called_with('http://localhost:12345/foo',283 mock_request.assert_called_with(
284 'http://localhost:12345/foo',
280 body='', headers=expected_headers, method='DELETE')285 body='', headers=expected_headers, method='DELETE')
281 expected_headers['Content-type'] = 'application/json'286 expected_headers['Content-type'] = 'application/json'
282 api._post('/foo')287 api._post('/foo')
283 mock_request.assert_called_with('http://localhost:12345/foo',288 mock_request.assert_called_with(
289 'http://localhost:12345/foo',
284 body='null', headers=expected_headers, method='POST')290 body='null', headers=expected_headers, method='POST')
285 api._put('/foo')291 api._put('/foo')
286 mock_request.assert_called_with('http://localhost:12345/foo',292 mock_request.assert_called_with(
293 'http://localhost:12345/foo',
287 body='null', headers=expected_headers, method='PUT')294 body='null', headers=expected_headers, method='PUT')
288295
289 @patch('httplib2.Http.request')296 @patch('httplib2.Http.request')
@@ -292,17 +299,21 @@
292 api = self.CoffeeAPI()299 api = self.CoffeeAPI()
293 api._get('/foo', extra_headers={'X-Foo': 'bar'})300 api._get('/foo', extra_headers={'X-Foo': 'bar'})
294 expected_headers = {'X-Foo': 'bar'}301 expected_headers = {'X-Foo': 'bar'}
295 mock_request.assert_called_with('http://localhost:12345/foo',302 mock_request.assert_called_with(
303 'http://localhost:12345/foo',
296 body='', headers=expected_headers, method='GET')304 body='', headers=expected_headers, method='GET')
297 api._delete('/foo', extra_headers={'X-Foo': 'bar'})305 api._delete('/foo', extra_headers={'X-Foo': 'bar'})
298 mock_request.assert_called_with('http://localhost:12345/foo',306 mock_request.assert_called_with(
307 'http://localhost:12345/foo',
299 body='', headers=expected_headers, method='DELETE')308 body='', headers=expected_headers, method='DELETE')
300 expected_headers['Content-type'] = 'application/json'309 expected_headers['Content-type'] = 'application/json'
301 api._post('/foo', extra_headers={'X-Foo': 'bar'})310 api._post('/foo', extra_headers={'X-Foo': 'bar'})
302 mock_request.assert_called_with('http://localhost:12345/foo',311 mock_request.assert_called_with(
312 'http://localhost:12345/foo',
303 body='null', headers=expected_headers, method='POST')313 body='null', headers=expected_headers, method='POST')
304 api._put('/foo', extra_headers={'X-Foo': 'bar'})314 api._put('/foo', extra_headers={'X-Foo': 'bar'})
305 mock_request.assert_called_with('http://localhost:12345/foo',315 mock_request.assert_called_with(
316 'http://localhost:12345/foo',
306 body='null', headers=expected_headers, method='PUT')317 body='null', headers=expected_headers, method='PUT')
307318
308 @patch('httplib2.Http.request')319 @patch('httplib2.Http.request')
@@ -317,12 +328,14 @@
317 api = self.CoffeeAPI()328 api = self.CoffeeAPI()
318 api.serializers = {'application/json': MySerializer()}329 api.serializers = {'application/json': MySerializer()}
319 api._post('/foo', data=[])330 api._post('/foo', data=[])
320 mock_request.assert_called_with('http://localhost:12345/foo',331 mock_request.assert_called_with(
332 'http://localhost:12345/foo',
321 body=expected, headers={'Content-type': 'application/json'},333 body=expected, headers={'Content-type': 'application/json'},
322 method='POST')334 method='POST')
323335
324 api._put('/foo', data=None)336 api._put('/foo', data=None)
325 mock_request.assert_called_with('http://localhost:12345/foo',337 mock_request.assert_called_with(
338 'http://localhost:12345/foo',
326 body=expected, headers={'Content-type': 'application/json'},339 body=expected, headers={'Content-type': 'application/json'},
327 method='PUT')340 method='PUT')
328341
@@ -341,7 +354,7 @@
341 api = self.CoffeeAPI()354 api = self.CoffeeAPI()
342 api._delete('/sugar/12', scheme='https')355 api._delete('/sugar/12', scheme='https')
343 mock_request.assert_called_with('https://localhost:12345/sugar/12',356 mock_request.assert_called_with('https://localhost:12345/sugar/12',
344 body='', headers={}, method='DELETE')357 body='', headers={}, method='DELETE')
345358
346 def test_cachedir_crash_race_lp803280(self):359 def test_cachedir_crash_race_lp803280(self):
347 def _simulate_race(path):360 def _simulate_race(path):
348361
=== modified file 'piston_mini_client/tests/test_serializers.py'
--- piston_mini_client/tests/test_serializers.py 2012-03-30 17:17:49 +0000
+++ piston_mini_client/tests/test_serializers.py 2012-07-30 17:16:48 +0000
@@ -44,4 +44,4 @@
44 # Maybe we should flatly refuse to serialize nested structures?44 # Maybe we should flatly refuse to serialize nested structures?
45 serializer = FormSerializer()45 serializer = FormSerializer()
46 self.assertEqual('foo=%7B%27a%27%3A+%27b%27%7D',46 self.assertEqual('foo=%7B%27a%27%3A+%27b%27%7D',
47 serializer.serialize({'foo': {'a': 'b'}}))47 serializer.serialize({'foo': {'a': 'b'}}))
4848
=== modified file 'piston_mini_client/tests/test_timeout.py'
--- piston_mini_client/tests/test_timeout.py 2012-04-02 14:23:33 +0000
+++ piston_mini_client/tests/test_timeout.py 2012-07-30 17:16:48 +0000
@@ -25,7 +25,7 @@
25 api = LazyAPI(timeout=1)25 api = LazyAPI(timeout=1)
26 self.assertEqual(1, api._timeout)26 self.assertEqual(1, api._timeout)
27 mock_http.assert_called_with(cache=None, proxy_info=None, timeout=1,27 mock_http.assert_called_with(cache=None, proxy_info=None, timeout=1,
28 disable_ssl_certificate_validation=True)28 disable_ssl_certificate_validation=True)
2929
30 @patch('os.environ.get')30 @patch('os.environ.get')
31 @patch('httplib2.Http')31 @patch('httplib2.Http')
@@ -34,7 +34,7 @@
34 api = LazyAPI()34 api = LazyAPI()
35 self.assertEqual(3.14, api._timeout)35 self.assertEqual(3.14, api._timeout)
36 mock_http.assert_called_with(cache=None, proxy_info=None, timeout=3.14,36 mock_http.assert_called_with(cache=None, proxy_info=None, timeout=3.14,
37 disable_ssl_certificate_validation=True)37 disable_ssl_certificate_validation=True)
3838
39 @patch('os.environ.get')39 @patch('os.environ.get')
40 @patch('httplib2.Http')40 @patch('httplib2.Http')
@@ -47,7 +47,7 @@
47 @patch('os.environ.get')47 @patch('os.environ.get')
48 @patch('httplib2.Http')48 @patch('httplib2.Http')
49 def test_no_nothing_falls_back_to_system_default(self, mock_http,49 def test_no_nothing_falls_back_to_system_default(self, mock_http,
50 mock_get):50 mock_get):
51 class DefaultAPI(PistonAPI):51 class DefaultAPI(PistonAPI):
52 default_service_root = 'http://test.info/api/1.0/'52 default_service_root = 'http://test.info/api/1.0/'
5353
@@ -63,7 +63,7 @@
63 api = LazyAPI()63 api = LazyAPI()
64 self.assertEqual(42, api._timeout)64 self.assertEqual(42, api._timeout)
65 mock_http.assert_called_with(cache=None, proxy_info=None, timeout=42,65 mock_http.assert_called_with(cache=None, proxy_info=None, timeout=42,
66 disable_ssl_certificate_validation=True)66 disable_ssl_certificate_validation=True)
6767
68 @patch('httplib2.HTTPConnectionWithTimeout.connect')68 @patch('httplib2.HTTPConnectionWithTimeout.connect')
69 def test_timeout_is_handled_by_failhandler(self, mock_connect):69 def test_timeout_is_handled_by_failhandler(self, mock_connect):
7070
=== modified file 'piston_mini_client/tests/test_validators.py'
--- piston_mini_client/tests/test_validators.py 2012-03-30 17:17:49 +0000
+++ piston_mini_client/tests/test_validators.py 2012-07-30 17:16:48 +0000
@@ -2,8 +2,14 @@
2# Copyright 2010-2012 Canonical Ltd. This software is licensed under the2# Copyright 2010-2012 Canonical Ltd. This software is licensed under the
3# GNU Lesser General Public License version 3 (see the file LICENSE).3# GNU Lesser General Public License version 3 (see the file LICENSE).
44
5from piston_mini_client.validators import (validate_pattern, validate,5from piston_mini_client.validators import (
6 validate_integer, oauth_protected, basic_protected, ValidationException)6 basic_protected,
7 oauth_protected,
8 validate,
9 validate_integer,
10 validate_pattern,
11 ValidationException,
12)
7from piston_mini_client.auth import OAuthAuthorizer, BasicAuthorizer13from piston_mini_client.auth import OAuthAuthorizer, BasicAuthorizer
8from unittest import TestCase14from unittest import TestCase
915
1016
=== modified file 'piston_mini_client/validators.py'
--- piston_mini_client/validators.py 2012-06-13 13:25:54 +0000
+++ piston_mini_client/validators.py 2012-07-30 17:16:48 +0000
@@ -42,7 +42,7 @@
42 if not re.match(pattern, kwargs[varname]):42 if not re.match(pattern, kwargs[varname]):
43 raise ValidationException(43 raise ValidationException(
44 "Argument '%s' must match pattern '%s'" % (varname,44 "Argument '%s' must match pattern '%s'" % (varname,
45 pattern))45 pattern))
46 elif required:46 elif required:
47 raise ValidationException(47 raise ValidationException(
48 "Required named argument '%s' missing" % varname)48 "Required named argument '%s' missing" % varname)
@@ -111,7 +111,8 @@
111 @wraps(func)111 @wraps(func)
112 def wrapper(self, *args, **kwargs):112 def wrapper(self, *args, **kwargs):
113 if not hasattr(self, '_auth') or self._auth is None:113 if not hasattr(self, '_auth') or self._auth is None:
114 raise ValidationException("This method is OAuth protected. "114 raise ValidationException(
115 "This method is OAuth protected. "
115 "Pass in an 'auth' argument to the constructor.")116 "Pass in an 'auth' argument to the constructor.")
116 if not isinstance(self._auth, OAuthAuthorizer):117 if not isinstance(self._auth, OAuthAuthorizer):
117 raise ValidationException("self.auth must be an OAuthAuthorizer.")118 raise ValidationException("self.auth must be an OAuthAuthorizer.")
@@ -128,7 +129,8 @@
128 @wraps(func)129 @wraps(func)
129 def wrapper(self, *args, **kwargs):130 def wrapper(self, *args, **kwargs):
130 if not hasattr(self, '_auth') or self._auth is None:131 if not hasattr(self, '_auth') or self._auth is None:
131 raise ValidationException("This method uses Basic auth. "132 raise ValidationException(
133 "This method uses Basic auth. "
132 "Pass in an 'auth' argument to the constructor.")134 "Pass in an 'auth' argument to the constructor.")
133 if not isinstance(self._auth, BasicAuthorizer):135 if not isinstance(self._auth, BasicAuthorizer):
134 raise ValidationException("self.auth must be a BasicAuthorizer.")136 raise ValidationException("self.auth must be a BasicAuthorizer.")

Subscribers

People subscribed via source and target branches