Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

Commit

Permalink
Use context manager for assertRaises (#537)
Browse files Browse the repository at this point in the history
* Use context manager for assertRaises, fixes #536.
* Update usage of unittest to unittest2.
* Remove unneeded `if __name__ == '__main__':` clauses in test files.
  • Loading branch information
pferate authored and Jon Wayne Parrott committed Jul 6, 2016
1 parent 267bbc5 commit f25b7ab
Show file tree
Hide file tree
Showing 24 changed files with 185 additions and 279 deletions.
6 changes: 3 additions & 3 deletions scripts/run_gce_system_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

import json
import unittest
import unittest2

import httplib2
from six.moves import http_client
Expand All @@ -24,7 +24,7 @@
from oauth2client.contrib.gce import AppAssertionCredentials


class TestComputeEngine(unittest.TestCase):
class TestComputeEngine(unittest2.TestCase):

def test_application_default(self):
default_creds = GoogleCredentials.get_application_default()
Expand Down Expand Up @@ -53,4 +53,4 @@ def test_token_info(self):


if __name__ == '__main__':
unittest.main()
unittest2.main()
4 changes: 0 additions & 4 deletions tests/contrib/test__appengine_ndb.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,3 @@ def test__from_base_type_bad_json(self):
creds_prop = TestNDBModel.creds
creds_json = '{JK-I-AM-NOT-JSON'
self.assertIsNone(creds_prop._from_base_type(creds_json))


if __name__ == '__main__': # pragma: NO COVER
unittest2.main()
48 changes: 22 additions & 26 deletions tests/contrib/test_appengine.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,8 @@ def test_raise_correct_type_of_exception(self):
scope = 'http://www.googleapis.com/scope'
credentials = AppAssertionCredentials(scope)
http = httplib2.Http()
self.assertRaises(AccessTokenRefreshError, credentials.refresh, http)
with self.assertRaises(AccessTokenRefreshError):
credentials.refresh(http)

def test_get_access_token_on_refresh(self):
app_identity_stub = self.AppIdentityStubImpl()
Expand Down Expand Up @@ -284,8 +285,8 @@ def test_get_access_token(self):
def test_save_to_well_known_file(self):
os.environ[_CLOUDSDK_CONFIG_ENV_VAR] = tempfile.mkdtemp()
credentials = AppAssertionCredentials([])
self.assertRaises(NotImplementedError,
save_to_well_known_file, credentials)
with self.assertRaises(NotImplementedError):
save_to_well_known_file(credentials)
del os.environ[_CLOUDSDK_CONFIG_ENV_VAR]


Expand Down Expand Up @@ -323,9 +324,8 @@ def test_make_value_from_datastore_none(self):

def test_validate(self):
FlowProperty().validate(None)
self.assertRaises(
db.BadValueError,
FlowProperty().validate, 42)
with self.assertRaises(db.BadValueError):
FlowProperty().validate(42)


class TestCredentialsModel(db.Model):
Expand Down Expand Up @@ -382,9 +382,8 @@ def test_make_value_from_datastore(self):
def test_validate(self):
CredentialsProperty().validate(self.credentials)
CredentialsProperty().validate(None)
self.assertRaises(
db.BadValueError,
CredentialsProperty().validate, 42)
with self.assertRaises(db.BadValueError):
CredentialsProperty().validate(42)


def _http_request(*args, **kwargs):
Expand Down Expand Up @@ -425,12 +424,12 @@ def test__is_ndb(self):
storage = StorageByKeyName(
object(), 'foo', 'credentials')

self.assertRaises(
TypeError, storage._is_ndb)
with self.assertRaises(TypeError):
storage._is_ndb()

storage._model = type(object)
self.assertRaises(
TypeError, storage._is_ndb)
with self.assertRaises(TypeError):
storage._is_ndb()

storage._model = CredentialsModel
self.assertFalse(storage._is_ndb())
Expand Down Expand Up @@ -728,7 +727,8 @@ def test_required(self):

# Raising an exception still clears the Credentials.
self.should_raise = Exception('')
self.assertRaises(Exception, self.app.get, '/foo_path')
with self.assertRaises(Exception):
self.app.get('/foo_path')
self.should_raise = False
self.assertEqual(None, self.decorator.credentials)

Expand Down Expand Up @@ -838,7 +838,8 @@ def test_aware(self):

# Raising an exception still clears the Credentials.
self.should_raise = Exception('')
self.assertRaises(Exception, self.app.get, '/bar_path/2012/01')
with self.assertRaises(Exception):
self.app.get('/bar_path/2012/01')
self.should_raise = False
self.assertEqual(None, self.decorator.credentials)

Expand Down Expand Up @@ -922,11 +923,10 @@ def test_decorator_from_client_secrets_bad_type(self):
'oauth2client.contrib.appengine.clientsecrets.loadfile')
with loadfile_patch as loadfile_mock:
loadfile_mock.return_value = ('badtype', None)
self.assertRaises(
AppEngineInvalidClientSecretsError,
OAuth2DecoratorFromClientSecrets,
'doesntmatter.json',
scope=['foo_scope', 'bar_scope'])
with self.assertRaises(AppEngineInvalidClientSecretsError):
OAuth2DecoratorFromClientSecrets(
'doesntmatter.json',
scope=['foo_scope', 'bar_scope'])

def test_decorator_from_client_secrets_kwargs(self):
decorator = OAuth2DecoratorFromClientSecrets(
Expand Down Expand Up @@ -1079,9 +1079,5 @@ def test_build_and_parse_state(self):
self.assertEqual(
'https://example.org',
appengine._parse_state_value(state, UserMock()))
self.assertRaises(appengine.InvalidXsrfTokenError,
appengine._parse_state_value, state[1:], UserMock())


if __name__ == '__main__': # pragma: NO COVER
unittest2.main()
with self.assertRaises(appengine.InvalidXsrfTokenError):
appengine._parse_state_value(state[1:], UserMock())
41 changes: 20 additions & 21 deletions tests/contrib/test_devshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import os
import socket
import threading
import unittest
import unittest2

import mock

Expand All @@ -46,17 +46,17 @@
])


class TestCredentialInfoResponse(unittest.TestCase):
class TestCredentialInfoResponse(unittest2.TestCase):

def test_constructor_with_non_list(self):
json_non_list = '{}'
self.assertRaises(ValueError, CredentialInfoResponse,
json_non_list)
with self.assertRaises(ValueError):
CredentialInfoResponse(json_non_list)

def test_constructor_with_bad_json(self):
json_non_list = '{BADJSON'
self.assertRaises(ValueError, CredentialInfoResponse,
json_non_list)
with self.assertRaises(ValueError):
CredentialInfoResponse(json_non_list)

def test_constructor_empty_list(self):
info_response = CredentialInfoResponse('[]')
Expand All @@ -79,12 +79,13 @@ def test_constructor_full_list(self):
self.assertEqual(info_response.expires_in, expires_in)


class Test_SendRecv(unittest.TestCase):
class Test_SendRecv(unittest2.TestCase):

def test_port_zero(self):
with mock.patch('oauth2client.contrib.devshell.os') as os_mod:
os_mod.getenv = mock.MagicMock(name='getenv', return_value=0)
self.assertRaises(NoDevshellServer, _SendRecv)
with self.assertRaises(NoDevshellServer):
_SendRecv()
os_mod.getenv.assert_called_once_with(DEVSHELL_ENV, 0)

def test_no_newline_in_received_header(self):
Expand All @@ -101,7 +102,8 @@ def test_no_newline_in_received_header(self):
with mock.patch('oauth2client.contrib.devshell.socket') as socket:
socket.socket = mock.MagicMock(name='socket',
return_value=sock)
self.assertRaises(CommunicationError, _SendRecv)
with self.assertRaises(CommunicationError):
_SendRecv()
os_mod.getenv.assert_called_once_with(DEVSHELL_ENV, 0)
socket.socket.assert_called_once_with()
sock.recv(6).decode.assert_called_once_with()
Expand Down Expand Up @@ -172,10 +174,11 @@ def run(self):
s.close()


class DevshellCredentialsTests(unittest.TestCase):
class DevshellCredentialsTests(unittest2.TestCase):

def test_signals_no_server(self):
self.assertRaises(NoDevshellServer, DevshellCredentials)
with self.assertRaises(NoDevshellServer):
DevshellCredentials()

def test_bad_message_to_mock_server(self):
request_content = CREDENTIAL_INFO_REQUEST_JSON + 'extrastuff'
Expand Down Expand Up @@ -253,21 +256,17 @@ def test_refuses_to_save_to_well_known_file(self):
os.path.isdir = lambda path: True
with _AuthReferenceServer():
creds = DevshellCredentials()
self.assertRaises(NotImplementedError,
save_to_well_known_file, creds)
with self.assertRaises(NotImplementedError):
save_to_well_known_file(creds)
finally:
os.path.isdir = ORIGINAL_ISDIR

def test_from_json(self):
self.assertRaises(NotImplementedError,
DevshellCredentials.from_json, None)
with self.assertRaises(NotImplementedError):
DevshellCredentials.from_json(None)

def test_serialization_data(self):
with _AuthReferenceServer('[]'):
credentials = DevshellCredentials()
self.assertRaises(NotImplementedError, getattr,
credentials, 'serialization_data')


if __name__ == '__main__': # pragma: NO COVER
unittest.main()
with self.assertRaises(NotImplementedError):
getattr(credentials, 'serialization_data')
4 changes: 0 additions & 4 deletions tests/contrib/test_dictionary_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,3 @@ def test_delete(self):

self.assertNotIn(key, dictionary)
self.assertIsNone(storage.get())


if __name__ == '__main__': # pragma: NO COVER
unittest2.main()
12 changes: 4 additions & 8 deletions tests/contrib/test_django_orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import os
import pickle
import sys
import unittest
import unittest2
# Mock a Django environment
from django.conf import global_settings

Expand Down Expand Up @@ -60,7 +60,7 @@ class DjangoOrmTestApp(AppConfig):
__author__ = '[email protected] (Conley Owens)'


class TestCredentialsField(unittest.TestCase):
class TestCredentialsField(unittest2.TestCase):

def setUp(self):
self.fake_model = FakeCredentialsModel()
Expand Down Expand Up @@ -112,7 +112,7 @@ def test_credentials_without_null(self):
self.assertTrue(credentials.null)


class TestFlowField(unittest.TestCase):
class TestFlowField(unittest2.TestCase):

class FakeFlowModel(models.Model):
flow = FlowField()
Expand Down Expand Up @@ -163,7 +163,7 @@ def test_flow_with_null(self):
self.assertTrue(flow.null)


class TestStorage(unittest.TestCase):
class TestStorage(unittest2.TestCase):

def setUp(self):
access_token = 'foo'
Expand Down Expand Up @@ -317,7 +317,3 @@ def __init__(self, set_store=False, *args, **kwargs):
self.deleted = False

credentials = CredentialsField()


if __name__ == '__main__': # pragma: NO COVER
unittest.main()
31 changes: 14 additions & 17 deletions tests/contrib/test_django_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

import json
import unittest
import unittest2

from django.conf.urls import include, url
from django.core import exceptions
Expand All @@ -37,7 +37,7 @@
urlpatterns += [url(r'^oauth2/', include(site.urls))]


class OAuth2SetupTest(unittest.TestCase):
class OAuth2SetupTest(unittest2.TestCase):

@mock.patch("oauth2client.contrib.django_util.clientsecrets")
def test_settings_initialize(self, clientsecrets):
Expand Down Expand Up @@ -66,34 +66,31 @@ def test_settings_initialize_invalid_type(self, clientsecrets):
}
)

self.assertRaises(
ValueError,
django_util.OAuth2Settings.__init__,
object.__new__(django_util.OAuth2Settings),
django.conf.settings)
with self.assertRaises(ValueError):
django_util.OAuth2Settings.__init__(
object.__new__(django_util.OAuth2Settings),
django.conf.settings)

@mock.patch("oauth2client.contrib.django_util.clientsecrets")
def test_no_settings(self, clientsecrets):
django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = None
django.conf.settings.GOOGLE_OAUTH2_CLIENT_SECRET = None
django.conf.settings.GOOGLE_OAUTH2_CLIENT_ID = None

self.assertRaises(
exceptions.ImproperlyConfigured,
django_util.OAuth2Settings.__init__,
object.__new__(django_util.OAuth2Settings),
django.conf.settings)
with self.assertRaises(exceptions.ImproperlyConfigured):
django_util.OAuth2Settings.__init__(
object.__new__(django_util.OAuth2Settings),
django.conf.settings)

@mock.patch("oauth2client.contrib.django_util.clientsecrets")
def test_no_session_middleware(self, clientsecrets):
old_classes = django.conf.settings.MIDDLEWARE_CLASSES
django.conf.settings.MIDDLEWARE_CLASSES = ()

self.assertRaises(
exceptions.ImproperlyConfigured,
django_util.OAuth2Settings.__init__,
object.__new__(django_util.OAuth2Settings),
django.conf.settings)
with self.assertRaises(exceptions.ImproperlyConfigured):
django_util.OAuth2Settings.__init__(
object.__new__(django_util.OAuth2Settings),
django.conf.settings)
django.conf.settings.MIDDLEWARE_CLASSES = old_classes


Expand Down
Loading

0 comments on commit f25b7ab

Please sign in to comment.