Skip to content

Commit

Permalink
Use context manager for assertRaises
Browse files Browse the repository at this point in the history
Resolve issue googleapis#536.
  • Loading branch information
pferate committed Jul 5, 2016
1 parent 267bbc5 commit 617f441
Show file tree
Hide file tree
Showing 15 changed files with 150 additions and 159 deletions.
44 changes: 22 additions & 22 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,8 +1079,8 @@ 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())
with self.assertRaises(appengine.InvalidXsrfTokenError):
appengine._parse_state_value(state[1:], UserMock())


if __name__ == '__main__': # pragma: NO COVER
Expand Down
29 changes: 16 additions & 13 deletions tests/contrib/test_devshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ class TestCredentialInfoResponse(unittest.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 Down Expand Up @@ -84,7 +84,8 @@ class Test_SendRecv(unittest.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 @@ -175,7 +177,8 @@ def run(self):
class DevshellCredentialsTests(unittest.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,20 +256,20 @@ 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')
with self.assertRaises(NotImplementedError):
getattr(credentials, 'serialization_data')


if __name__ == '__main__': # pragma: NO COVER
Expand Down
27 changes: 12 additions & 15 deletions tests/contrib/test_django_util.py
Original file line number Diff line number Diff line change
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
18 changes: 7 additions & 11 deletions tests/contrib/test_flask_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,9 @@ def test_bad_client_secrets(self):

with mock.patch('oauth2client.clientsecrets.loadfile',
return_value=return_val):
self.assertRaises(
ValueError,
FlaskOAuth2,
flask.Flask(__name__), client_secrets_file='file.json')
with self.assertRaises(ValueError):
FlaskOAuth2(flask.Flask(__name__),
client_secrets_file='file.json')

def test_app_configuration(self):
app = flask.Flask(__name__)
Expand All @@ -167,10 +166,8 @@ def test_app_configuration(self):
self.assertEqual(oauth2.client_secret, 'secret2')

def test_no_configuration(self):
self.assertRaises(
ValueError,
FlaskOAuth2,
flask.Flask(__name__))
with self.assertRaises(ValueError):
FlaskOAuth2(flask.Flask(__name__))

def test_create_flow(self):
with self.app.test_request_context():
Expand Down Expand Up @@ -334,9 +331,8 @@ def test_no_credentials(self):
self.assertTrue(self.oauth2.credentials is None)
self.assertTrue(self.oauth2.user_id is None)
self.assertTrue(self.oauth2.email is None)
self.assertRaises(
ValueError,
self.oauth2.http)
with self.assertRaises(ValueError):
self.oauth2.http()
self.assertFalse(self.oauth2.storage.get())
self.oauth2.storage.delete()

Expand Down
8 changes: 4 additions & 4 deletions tests/contrib/test_gce.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ def test_refresh_token_failed_fetch(self):

def test_serialization_data(self):
credentials = AppAssertionCredentials()
self.assertRaises(NotImplementedError, getattr,
credentials, 'serialization_data')
with self.assertRaises(NotImplementedError):
getattr(credentials, 'serialization_data')

def test_create_scoped_required(self):
credentials = AppAssertionCredentials()
Expand Down Expand Up @@ -143,8 +143,8 @@ def test_save_to_well_known_file(self):
try:
os.path.isdir = lambda path: True
credentials = AppAssertionCredentials()
self.assertRaises(NotImplementedError, save_to_well_known_file,
credentials)
with self.assertRaises(NotImplementedError):
save_to_well_known_file(credentials)
finally:
os.path.isdir = ORIGINAL_ISDIR

Expand Down
7 changes: 4 additions & 3 deletions tests/contrib/test_locked_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ def test_relock_fail(self):

self.assertTrue(instance.is_locked())
self.assertIsNotNone(instance.file_handle())
self.assertRaises(
locked_file.AlreadyLockedException, instance.open_and_lock, 1, 1)
with self.assertRaises(locked_file.AlreadyLockedException):
instance.open_and_lock(1, 1)

@mock.patch('oauth2client.contrib.locked_file.open', create=True)
def test_lock_access_error_fallback_mode(self, mock_open):
Expand Down Expand Up @@ -107,7 +107,8 @@ def test_lock_unexpected_error(self, mock_open):

with mock.patch('os.open') as mock_os_open:
mock_os_open.side_effect = [OSError(errno.EPERM, '')]
self.assertRaises(OSError, instance.open_and_lock, 1, 1)
with self.assertRaises(OSError):
instance.open_and_lock(1, 1)

@mock.patch('oauth2client.contrib.locked_file.open', create=True)
@mock.patch('oauth2client.contrib.locked_file.logger')
Expand Down
15 changes: 7 additions & 8 deletions tests/contrib/test_multistore_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

from oauth2client import util
from oauth2client.client import OAuth2Credentials
from oauth2client.contrib import locked_file
from oauth2client.contrib.locked_file import CredentialsFileSymbolicLinkError
from oauth2client.contrib import multistore_file

_filehandle, FILENAME = tempfile.mkstemp('oauth2client_test.data')
Expand Down Expand Up @@ -128,7 +128,8 @@ def test_lock_file_raise_unexpected_error(self):
try:
multistore = multistore_file._MultiStore(filename)
multistore._file = _MockLockedFile(filename, IOError, errno.EBUSY)
self.assertRaises(IOError, multistore._lock)
with self.assertRaises(IOError):
multistore._lock()
self.assertTrue(multistore._file.open_and_lock_called)
finally:
os.unlink(filename)
Expand Down Expand Up @@ -186,9 +187,8 @@ def test_multistore_no_symbolic_link_files(self):
'user-agent/1.0',
['some-scope', 'some-other-scope'])
try:
self.assertRaises(
locked_file.CredentialsFileSymbolicLinkError,
store.get)
with self.assertRaises(CredentialsFileSymbolicLinkError):
store.get()
finally:
os.unlink(SYMFILENAME)

Expand Down Expand Up @@ -356,9 +356,8 @@ def test__refresh_data_cache_newer_version(self):

with json_patch as json_mock:
json_mock.return_value = {'file_version': 5}
self.assertRaises(
multistore_file.NewerCredentialStoreError,
multistore._refresh_data_cache)
with self.assertRaises(multistore_file.NewerCredentialStoreError):
multistore._refresh_data_cache()
self.assertTrue(json_mock.called)

def test__refresh_data_cache_bad_credentials(self):
Expand Down
13 changes: 8 additions & 5 deletions tests/contrib/test_xsrfutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ class Test_generate_token(unittest.TestCase):

def test_bad_positional(self):
# Need 2 positional arguments.
self.assertRaises(TypeError, xsrfutil.generate_token, None)
with self.assertRaises(TypeError):
xsrfutil.generate_token(None)
# At most 2 positional arguments.
self.assertRaises(TypeError, xsrfutil.generate_token, None, None, None)
with self.assertRaises(TypeError):
xsrfutil.generate_token(None, None, None)

def test_it(self):
digest = b'foobar'
Expand Down Expand Up @@ -113,10 +115,11 @@ class Test_validate_token(unittest.TestCase):

def test_bad_positional(self):
# Need 3 positional arguments.
self.assertRaises(TypeError, xsrfutil.validate_token, None, None)
with self.assertRaises(TypeError):
xsrfutil.validate_token(None, None)
# At most 3 positional arguments.
self.assertRaises(TypeError, xsrfutil.validate_token,
None, None, None, None)
with self.assertRaises(TypeError):
xsrfutil.validate_token(None, None, None, None)

def test_no_token(self):
key = token = user_id = None
Expand Down
Loading

0 comments on commit 617f441

Please sign in to comment.