From 3cbd8e18cbae4bfd5596a637a45a38cbb0d16fe7 Mon Sep 17 00:00:00 2001 From: Nathaniel Manista Date: Thu, 4 Feb 2016 18:35:38 +0000 Subject: [PATCH] Use symbolic constants for HTTP codes --- oauth2client/client.py | 17 +++++++++-------- oauth2client/contrib/gce.py | 5 +++-- oauth2client/tools.py | 3 ++- scripts/run_system_tests.py | 5 +++-- tests/contrib/test_django_util.py | 9 +++++---- tests/contrib/test_gce.py | 11 ++++++----- tests/test_client.py | 17 +++++++++-------- 7 files changed, 37 insertions(+), 30 deletions(-) diff --git a/oauth2client/client.py b/oauth2client/client.py index de386ae..ef19d6f 100644 --- a/oauth2client/client.py +++ b/oauth2client/client.py @@ -30,6 +30,7 @@ import tempfile import time import shutil import six +from six.moves import http_client from six.moves import urllib import httplib2 @@ -73,7 +74,7 @@ ID_TOKEN_VERIFICATON_CERTS = ID_TOKEN_VERIFICATION_CERTS OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob' # Google Data client libraries may need to set this to [401, 403]. -REFRESH_STATUS_CODES = [401] +REFRESH_STATUS_CODES = (http_client.UNAUTHORIZED,) # The value representing user credentials. AUTHORIZED_USER = 'authorized_user' @@ -891,7 +892,7 @@ class OAuth2Credentials(Credentials): resp, content = http_request( self.token_uri, method='POST', body=body, headers=headers) content = _from_bytes(content) - if resp.status == 200: + if resp.status == http_client.OK: d = json.loads(content) self.token_response = d self.access_token = d['access_token'] @@ -956,7 +957,7 @@ class OAuth2Credentials(Credentials): query_params = {'token': token} token_revoke_uri = _update_query_params(self.revoke_uri, query_params) resp, content = http_request(token_revoke_uri) - if resp.status == 200: + if resp.status == http_client.OK: self.invalid = True else: error_msg = 'Invalid response %s.' % resp.status @@ -1001,7 +1002,7 @@ class OAuth2Credentials(Credentials): query_params) resp, content = http_request(token_info_uri) content = _from_bytes(content) - if resp.status == 200: + if resp.status == http_client.OK: d = json.loads(content) self.scopes = set(util.string_to_scopes(d.get('scope', ''))) else: @@ -1107,7 +1108,7 @@ def _detect_gce_environment(): headers = {_METADATA_FLAVOR_HEADER: _DESIRED_METADATA_FLAVOR} connection.request('GET', '/', headers=headers) response = connection.getresponse() - if response.status == 200: + if response.status == http_client.OK: return (response.getheader(_METADATA_FLAVOR_HEADER) == _DESIRED_METADATA_FLAVOR) except socket.error: # socket.timeout or socket.error(64, 'Host is down') @@ -1759,7 +1760,7 @@ def verify_id_token(id_token, audience, http=None, http = _cached_http resp, content = http.request(cert_uri) - if resp.status == 200: + if resp.status == http_client.OK: certs = json.loads(_from_bytes(content)) return crypt.verify_signed_jwt_with_certs(id_token, certs, audience) else: @@ -2104,7 +2105,7 @@ class OAuth2WebServerFlow(Flow): resp, content = http.request(self.device_uri, method='POST', body=body, headers=headers) content = _from_bytes(content) - if resp.status == 200: + if resp.status == http_client.OK: try: flow_info = json.loads(content) except ValueError as e: @@ -2187,7 +2188,7 @@ class OAuth2WebServerFlow(Flow): resp, content = http.request(self.token_uri, method='POST', body=body, headers=headers) d = _parse_exchange_token_response(content) - if resp.status == 200 and 'access_token' in d: + if resp.status == http_client.OK and 'access_token' in d: access_token = d['access_token'] refresh_token = d.get('refresh_token', None) if not refresh_token: diff --git a/oauth2client/contrib/gce.py b/oauth2client/contrib/gce.py index 77b08f1..a834a43 100644 --- a/oauth2client/contrib/gce.py +++ b/oauth2client/contrib/gce.py @@ -19,6 +19,7 @@ Utilities for making it easier to use OAuth 2.0 on Google Compute Engine. import json import logging +from six.moves import http_client from six.moves import urllib from oauth2client._helpers import _from_bytes @@ -86,7 +87,7 @@ class AppAssertionCredentials(AssertionCredentials): uri = META.replace('{?scope}', query) response, content = http_request(uri) content = _from_bytes(content) - if response.status == 200: + if response.status == http_client.OK: try: d = json.loads(content) except Exception as e: @@ -94,7 +95,7 @@ class AppAssertionCredentials(AssertionCredentials): status=response.status) self.access_token = d['accessToken'] else: - if response.status == 404: + if response.status == http_client.NOT_FOUND: content += (' This can occur if a VM was created' ' with no service account or scopes.') raise HttpAccessTokenRefreshError(content, status=response.status) diff --git a/oauth2client/tools.py b/oauth2client/tools.py index 629866b..aa40b9e 100644 --- a/oauth2client/tools.py +++ b/oauth2client/tools.py @@ -26,6 +26,7 @@ import socket import sys from six.moves import BaseHTTPServer +from six.moves import http_client from six.moves import urllib from six.moves import input @@ -95,7 +96,7 @@ class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): if the flow has completed. Note that we can't detect if an error occurred. """ - self.send_response(200) + self.send_response(http_client.OK) self.send_header("Content-type", "text/html") self.end_headers() query = self.path.split('?', 1)[-1] diff --git a/scripts/run_system_tests.py b/scripts/run_system_tests.py index 3f7baba..343e15b 100644 --- a/scripts/run_system_tests.py +++ b/scripts/run_system_tests.py @@ -2,6 +2,7 @@ import json import os import httplib2 +from six.moves import http_client from oauth2client import client from oauth2client import service_account @@ -41,8 +42,8 @@ def _require_environ(): def _check_user_info(credentials, expected_email): http = credentials.authorize(httplib2.Http()) response, content = http.request(USER_INFO) - if response.status != 200: - raise ValueError('Expected 200 response.') + if response.status != http_client.OK: + raise ValueError('Expected 200 OK response.') content = content.decode('utf-8') payload = json.loads(content) diff --git a/tests/contrib/test_django_util.py b/tests/contrib/test_django_util.py index a3734a2..5620aca 100644 --- a/tests/contrib/test_django_util.py +++ b/tests/contrib/test_django_util.py @@ -27,6 +27,7 @@ from oauth2client.contrib.django_util import decorators from oauth2client.contrib.django_util import site from oauth2client.contrib.django_util import storage from oauth2client.contrib.django_util import views +from six.moves import http_client from six.moves.urllib import parse urlpatterns = [ @@ -116,7 +117,7 @@ class OAuth2EnabledDecoratorTest(TestWithSession): return http.HttpResponse("test") # pragma: NO COVER response = test_view(request) - self.assertEquals(response.status_code, 200) + self.assertEquals(response.status_code, http_client.OK) self.assertIsNotNone(request.oauth) self.assertFalse(request.oauth.has_credentials()) self.assertIsNone(request.oauth.http) @@ -137,7 +138,7 @@ class OAuth2EnabledDecoratorTest(TestWithSession): return http.HttpResponse("test") response = test_view(request) - self.assertEquals(response.status_code, 200) + self.assertEquals(response.status_code, http_client.OK) self.assertEquals(response.content, b"test") self.assertTrue(request.oauth.has_credentials()) self.assertIsNotNone(request.oauth.http) @@ -158,7 +159,7 @@ class OAuth2EnabledDecoratorTest(TestWithSession): return http.HttpResponse("hello world") # pragma: NO COVER response = test_view(request) - self.assertEquals(response.status_code, 200) + self.assertEquals(response.status_code, http_client.OK) self.assertIsNotNone(request.oauth) self.assertFalse(request.oauth.has_credentials()) @@ -196,7 +197,7 @@ class OAuth2RequiredDecoratorTest(TestWithSession): my_user_oauth.has_credentials.return_value = True response = test_view(request) - self.assertEquals(response.status_code, 200) + self.assertEquals(response.status_code, http_client.OK) self.assertEquals(response.content, b"test") @mock.patch('oauth2client.contrib.dictionary_storage.OAuth2Credentials') diff --git a/tests/contrib/test_gce.py b/tests/contrib/test_gce.py index 4367e7f..3ecb37f 100644 --- a/tests/contrib/test_gce.py +++ b/tests/contrib/test_gce.py @@ -18,6 +18,7 @@ Unit tests for oauth2client.contrib.gce. """ import json +from six.moves import http_client from six.moves import urllib import unittest @@ -58,7 +59,7 @@ class AppAssertionCredentialsTests(unittest.TestCase): return_val = _to_bytes(return_val) http = mock.MagicMock() http.request = mock.MagicMock( - return_value=(mock.Mock(status=200), return_val)) + return_value=(mock.Mock(status=http_client.OK), return_val)) scopes = ['http://example.com/a', 'http://example.com/b'] credentials = AppAssertionCredentials(scope=scopes) @@ -82,7 +83,7 @@ class AppAssertionCredentialsTests(unittest.TestCase): http = mock.MagicMock() content = '{BADJSON' http.request = mock.MagicMock( - return_value=(mock.Mock(status=200), content)) + return_value=(mock.Mock(status=http_client.OK), content)) credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) @@ -92,7 +93,7 @@ class AppAssertionCredentialsTests(unittest.TestCase): http = mock.MagicMock() content = '{}' http.request = mock.MagicMock( - return_value=(mock.Mock(status=400), content)) + return_value=(mock.Mock(status=http_client.BAD_REQUEST), content)) credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) @@ -110,7 +111,7 @@ class AppAssertionCredentialsTests(unittest.TestCase): http = mock.MagicMock() content = '{}' http.request = mock.MagicMock( - return_value=(mock.Mock(status=404), content)) + return_value=(mock.Mock(status=http_client.NOT_FOUND), content)) credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) @@ -149,7 +150,7 @@ class AppAssertionCredentialsTests(unittest.TestCase): def test_get_access_token(self): http = mock.MagicMock() http.request = mock.MagicMock( - return_value=(mock.Mock(status=200), + return_value=(mock.Mock(status=http_client.OK), '{"accessToken": "this-is-a-token"}')) credentials = AppAssertionCredentials(['dummy_scope']) diff --git a/tests/test_client.py b/tests/test_client.py index 131e72e..6417578 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -216,12 +216,12 @@ class GoogleCredentialsTests(unittest2.TestCase): server_software=''): response = mock.MagicMock() if status_ok: - response.status = 200 + response.status = http_client.OK response.getheader = mock.MagicMock( name='getheader', return_value=client._DESIRED_METADATA_FLAVOR) else: - response.status = 404 + response.status = http_client.NOT_FOUND connection = mock.MagicMock() connection.getresponse = mock.MagicMock(name='getresponse', @@ -232,8 +232,8 @@ class GoogleCredentialsTests(unittest2.TestCase): with mock.patch('oauth2client.client.os') as os_module: os_module.environ = {client._SERVER_SOFTWARE: server_software} with mock.patch('oauth2client.client.six') as six_module: - http_client = six_module.moves.http_client - http_client.HTTPConnection = mock.MagicMock( + http_client_module = six_module.moves.http_client + http_client_module.HTTPConnection = mock.MagicMock( name='HTTPConnection', return_value=connection) if server_software == '': @@ -247,7 +247,7 @@ class GoogleCredentialsTests(unittest2.TestCase): self.assertFalse(_in_gce_environment()) if server_software == '': - http_client.HTTPConnection.assert_called_once_with( + http_client_module.HTTPConnection.assert_called_once_with( client._GCE_METADATA_HOST, timeout=1) connection.getresponse.assert_called_once_with() # Remaining calls are not "getresponse" @@ -265,7 +265,8 @@ class GoogleCredentialsTests(unittest2.TestCase): response.getheader.assert_called_once_with( client._METADATA_FLAVOR_HEADER) else: - self.assertEqual(http_client.HTTPConnection.mock_calls, []) + self.assertEqual( + http_client_module.HTTPConnection.mock_calls, []) self.assertEqual(connection.getresponse.mock_calls, []) # Remaining calls are not "getresponse" self.assertEqual(connection.method_calls, []) @@ -785,7 +786,7 @@ class BasicCredentialsTests(unittest2.TestCase): ]) http = self.credentials.authorize(http) resp, content = http.request('http://example.com') - self.assertEqual(400, resp.status) + self.assertEqual(http_client.BAD_REQUEST, resp.status) self.assertEqual(None, self.credentials.token_response) def test_to_from_json(self): @@ -1058,7 +1059,7 @@ class AccessTokenCredentialsTests(unittest2.TestCase): ]) http = self.credentials.authorize(http) resp, content = http.request('http://example.com') - self.assertEqual(400, resp.status) + self.assertEqual(http_client.BAD_REQUEST, resp.status) def test_auth_header_sent(self): http = HttpMockSequence([