Use context manager for assertRaises (#537)

* Use context manager for assertRaises, fixes #536.
* Update usage of unittest to unittest2.
* Remove unneeded `if __name__ == '__main__':` clauses in test files.
This commit is contained in:
Pat Ferate
2016-07-06 12:45:49 -07:00
committed by Jon Wayne Parrott
parent 267bbc59ca
commit f25b7abfaf
24 changed files with 185 additions and 279 deletions

View File

@@ -13,7 +13,7 @@
# limitations under the License.
import json
import unittest
import unittest2
import httplib2
from six.moves import http_client
@@ -24,7 +24,7 @@ from oauth2client.client import GoogleCredentials
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()
@@ -53,4 +53,4 @@ class TestComputeEngine(unittest.TestCase):
if __name__ == '__main__':
unittest.main()
unittest2.main()

View File

@@ -166,7 +166,3 @@ class TestCredentialsNDBProperty(unittest2.TestCase):
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()

View File

@@ -159,7 +159,8 @@ class TestAppAssertionCredentials(unittest2.TestCase):
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()
@@ -284,8 +285,8 @@ class TestAppAssertionCredentials(unittest2.TestCase):
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]
@@ -323,9 +324,8 @@ class FlowPropertyTest(unittest2.TestCase):
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):
@@ -382,9 +382,8 @@ class CredentialsPropertyTest(unittest2.TestCase):
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):
@@ -425,12 +424,12 @@ class StorageByKeyNameTest(unittest2.TestCase):
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())
@@ -728,7 +727,8 @@ class DecoratorTests(unittest2.TestCase):
# 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)
@@ -838,7 +838,8 @@ class DecoratorTests(unittest2.TestCase):
# 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)
@@ -922,11 +923,10 @@ class DecoratorTests(unittest2.TestCase):
'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(
@@ -1079,9 +1079,5 @@ class DecoratorXsrfProtectionTests(unittest2.TestCase):
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())

View File

@@ -19,7 +19,7 @@ import json
import os
import socket
import threading
import unittest
import unittest2
import mock
@@ -46,17 +46,17 @@ DEFAULT_CREDENTIAL_JSON = json.dumps([
])
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('[]')
@@ -79,12 +79,13 @@ class TestCredentialInfoResponse(unittest.TestCase):
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):
@@ -101,7 +102,8 @@ class Test_SendRecv(unittest.TestCase):
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()
@@ -172,10 +174,11 @@ class _AuthReferenceServer(threading.Thread):
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'
@@ -253,21 +256,17 @@ class DevshellCredentialsTests(unittest.TestCase):
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')

View File

@@ -104,7 +104,3 @@ class DictionaryStorageTests(unittest2.TestCase):
self.assertNotIn(key, dictionary)
self.assertIsNone(storage.get())
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -23,7 +23,7 @@ import imp
import os
import pickle
import sys
import unittest
import unittest2
# Mock a Django environment
from django.conf import global_settings
@@ -60,7 +60,7 @@ from oauth2client import GOOGLE_TOKEN_URI
__author__ = 'conleyo@google.com (Conley Owens)'
class TestCredentialsField(unittest.TestCase):
class TestCredentialsField(unittest2.TestCase):
def setUp(self):
self.fake_model = FakeCredentialsModel()
@@ -112,7 +112,7 @@ class TestCredentialsField(unittest.TestCase):
self.assertTrue(credentials.null)
class TestFlowField(unittest.TestCase):
class TestFlowField(unittest2.TestCase):
class FakeFlowModel(models.Model):
flow = FlowField()
@@ -163,7 +163,7 @@ class TestFlowField(unittest.TestCase):
self.assertTrue(flow.null)
class TestStorage(unittest.TestCase):
class TestStorage(unittest2.TestCase):
def setUp(self):
access_token = 'foo'
@@ -317,7 +317,3 @@ class FakeCredentialsModelMockNoSet(object):
self.deleted = False
credentials = CredentialsField()
if __name__ == '__main__': # pragma: NO COVER
unittest.main()

View File

@@ -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
@@ -37,7 +37,7 @@ urlpatterns = [
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):
@@ -66,11 +66,10 @@ class OAuth2SetupTest(unittest.TestCase):
}
)
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):
@@ -78,22 +77,20 @@ class OAuth2SetupTest(unittest.TestCase):
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

View File

@@ -137,10 +137,9 @@ class FlaskOAuth2Tests(unittest2.TestCase):
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__)
@@ -167,10 +166,8 @@ class FlaskOAuth2Tests(unittest2.TestCase):
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():
@@ -334,9 +331,8 @@ class FlaskOAuth2Tests(unittest2.TestCase):
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()
@@ -532,7 +528,3 @@ class FlaskOAuth2Tests(unittest2.TestCase):
self.oauth2.storage.delete()
self.assertNotIn('google_oauth2_credentials', flask.session)
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -99,8 +99,8 @@ class AppAssertionCredentialsTests(unittest2.TestCase):
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()
@@ -143,11 +143,7 @@ class AppAssertionCredentialsTests(unittest2.TestCase):
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
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -17,7 +17,7 @@
import datetime
import keyring
import threading
import unittest
import unittest2
import mock
@@ -29,7 +29,7 @@ from oauth2client.contrib.keyring_storage import Storage
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
class KeyringStorageTests(unittest.TestCase):
class KeyringStorageTests(unittest2.TestCase):
def test_constructor(self):
service_name = 'my_unit_test'
@@ -169,7 +169,3 @@ class _FakeLock(object):
def release(self):
self._release_count += 1
if __name__ == '__main__': # pragma: NO COVER
unittest.main()

View File

@@ -76,8 +76,8 @@ class TestPosixOpener(TestOpener):
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):
@@ -107,7 +107,8 @@ class TestPosixOpener(TestOpener):
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')
@@ -241,7 +242,3 @@ class TestLockedFile(unittest2.TestCase):
instance, opener = self._make_one()
instance.unlock_and_close()
opener.unlock_and_close.assert_called_with()
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -128,7 +128,8 @@ class MultistoreFileTests(unittest2.TestCase):
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)
@@ -186,9 +187,9 @@ class MultistoreFileTests(unittest2.TestCase):
'user-agent/1.0',
['some-scope', 'some-other-scope'])
try:
self.assertRaises(
locked_file.CredentialsFileSymbolicLinkError,
store.get)
with self.assertRaises(
locked_file.CredentialsFileSymbolicLinkError):
store.get()
finally:
os.unlink(SYMFILENAME)
@@ -356,9 +357,8 @@ class MultistoreFileTests(unittest2.TestCase):
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):
@@ -381,7 +381,3 @@ class MultistoreFileTests(unittest2.TestCase):
multistore._data = {}
multistore._delete_credential('nonexistent_key')
self.assertTrue(write_mock.called)
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -15,7 +15,7 @@
"""Tests for oauth2client.contrib.xsrfutil."""
import base64
import unittest
import unittest2
import mock
@@ -37,13 +37,15 @@ TEST_EXTRA_INFO_2 = b'more_extra_info'
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
class Test_generate_token(unittest.TestCase):
class Test_generate_token(unittest2.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'
@@ -109,14 +111,15 @@ class Test_generate_token(unittest.TestCase):
self.assertEqual(token, expected_token)
class Test_validate_token(unittest.TestCase):
class Test_validate_token(unittest2.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
@@ -215,7 +218,7 @@ class Test_validate_token(unittest.TestCase):
when=token_time)
class XsrfUtilTests(unittest.TestCase):
class XsrfUtilTests(unittest2.TestCase):
"""Test xsrfutil functions."""
def testGenerateAndValidateToken(self):
@@ -288,7 +291,3 @@ class XsrfUtilTests(unittest.TestCase):
None,
TEST_USER_ID_1,
action_id=TEST_ACTION_ID_1))
if __name__ == '__main__': # pragma: NO COVER
unittest.main()

View File

@@ -13,7 +13,7 @@
# limitations under the License.
"""Unit tests for oauth2client._helpers."""
import unittest
import unittest2
from oauth2client._helpers import _from_bytes
from oauth2client._helpers import _json_encode
@@ -23,7 +23,7 @@ from oauth2client._helpers import _urlsafe_b64decode
from oauth2client._helpers import _urlsafe_b64encode
class Test__parse_pem_key(unittest.TestCase):
class Test__parse_pem_key(unittest2.TestCase):
def test_valid_input(self):
test_string = b'1234-----BEGIN FOO BAR BAZ'
@@ -36,7 +36,7 @@ class Test__parse_pem_key(unittest.TestCase):
self.assertEqual(result, None)
class Test__json_encode(unittest.TestCase):
class Test__json_encode(unittest2.TestCase):
def test_dictionary_input(self):
# Use only a single key since dictionary hash order
@@ -51,7 +51,7 @@ class Test__json_encode(unittest.TestCase):
self.assertEqual(result, '[42,1337]')
class Test__to_bytes(unittest.TestCase):
class Test__to_bytes(unittest2.TestCase):
def test_with_bytes(self):
value = b'bytes-val'
@@ -64,10 +64,11 @@ class Test__to_bytes(unittest.TestCase):
def test_with_nonstring_type(self):
value = object()
self.assertRaises(ValueError, _to_bytes, value)
with self.assertRaises(ValueError):
_to_bytes(value)
class Test__from_bytes(unittest.TestCase):
class Test__from_bytes(unittest2.TestCase):
def test_with_unicode(self):
value = u'bytes-val'
@@ -80,10 +81,11 @@ class Test__from_bytes(unittest.TestCase):
def test_with_nonstring_type(self):
value = object()
self.assertRaises(ValueError, _from_bytes, value)
with self.assertRaises(ValueError):
_from_bytes(value)
class Test__urlsafe_b64encode(unittest.TestCase):
class Test__urlsafe_b64encode(unittest2.TestCase):
DEADBEEF_ENCODED = b'ZGVhZGJlZWY'
@@ -98,7 +100,7 @@ class Test__urlsafe_b64encode(unittest.TestCase):
self.assertEqual(result, self.DEADBEEF_ENCODED)
class Test__urlsafe_b64decode(unittest.TestCase):
class Test__urlsafe_b64decode(unittest2.TestCase):
def test_valid_input_bytes(self):
test_string = b'ZGVhZGJlZWY'
@@ -113,9 +115,5 @@ class Test__urlsafe_b64decode(unittest.TestCase):
def test_bad_input(self):
import binascii
bad_string = b'+'
self.assertRaises((TypeError, binascii.Error),
_urlsafe_b64decode, bad_string)
if __name__ == '__main__': # pragma: NO COVER
unittest.main()
with self.assertRaises((TypeError, binascii.Error)):
_urlsafe_b64decode(bad_string)

View File

@@ -178,7 +178,3 @@ class TestRsaSigner(unittest2.TestCase):
key_bytes = 'bogus-key'
with self.assertRaises(ValueError):
RsaSigner.from_string(key_bytes)
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -69,7 +69,3 @@ class TestPyCryptoSigner(unittest2.TestCase):
key_bytes = 'definitely-not-pem-format'
with self.assertRaises(NotImplementedError):
PyCryptoSigner.from_string(key_bytes)
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -559,7 +559,8 @@ class GoogleCredentialsTests(unittest2.TestCase):
os.path.join('gcloud', _WELL_KNOWN_CREDENTIALS_FILE))
credentials = _get_application_default_credential_from_file(
credential_file)
self.assertRaises(OSError, save_to_well_known_file, credentials)
with self.assertRaises(OSError):
save_to_well_known_file(credentials)
config_dir = os.path.join(os.path.expanduser('~'), '.config', 'gcloud')
isdir_mock.assert_called_once_with(config_dir)
@@ -614,9 +615,8 @@ class GoogleCredentialsTests(unittest2.TestCase):
credentials_file = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_3.json'))
self.assertRaises(ValueError,
_get_application_default_credential_from_file,
credentials_file)
with self.assertRaises(ValueError):
_get_application_default_credential_from_file(credentials_file)
def test_raise_exception_for_missing_fields(self):
missing_fields = ['first', 'second', 'third']
@@ -813,10 +813,9 @@ class GoogleCredentialsTests(unittest2.TestCase):
credentials_file = datafile(
os.path.join('gcloud',
'application_default_credentials_malformed_3.json'))
self.assertRaises(
ApplicationDefaultCredentialsError,
self.get_a_google_credentials_object().from_stream,
credentials_file)
with self.assertRaises(ApplicationDefaultCredentialsError):
self.get_a_google_credentials_object().from_stream(
credentials_file)
def test_to_from_json_authorized_user(self):
filename = 'application_default_credentials_authorized_user.json'
@@ -1051,11 +1050,9 @@ class BasicCredentialsTests(unittest2.TestCase):
# Next, test that we do fail on unicode.
unicode_str = six.unichr(40960) + 'abcd'
self.assertRaises(
NonAsciiHeaderError,
http.request,
u'http://example.com', method=u'GET',
headers={u'foo': unicode_str})
with self.assertRaises(NonAsciiHeaderError):
http.request(u'http://example.com', method=u'GET',
headers={u'foo': unicode_str})
def test_no_unicode_in_request_params(self):
access_token = u'foo'
@@ -1507,15 +1504,11 @@ class BasicCredentialsTests(unittest2.TestCase):
self.credentials.retrieve_scopes(http)
self.assertEqual(set(['foo', 'bar']), self.credentials.scopes)
self.assertRaises(
Error,
self.credentials.retrieve_scopes,
http)
with self.assertRaises(Error):
self.credentials.retrieve_scopes(http)
self.assertRaises(
Error,
self.credentials.retrieve_scopes,
http)
with self.assertRaises(Error):
self.credentials.retrieve_scopes(http)
def test_refresh_updates_id_token(self):
for status_code in REFRESH_STATUS_CODES:
@@ -1664,7 +1657,8 @@ class ExtractIdTokenTest(unittest2.TestCase):
body_json = json.dumps(body).encode('ascii')
payload = base64.urlsafe_b64encode(body_json).strip(b'=')
jwt = b'stuff.' + payload
self.assertRaises(VerifyJwtTokenError, _extract_id_token, jwt)
with self.assertRaises(VerifyJwtTokenError):
_extract_id_token(jwt)
class OAuth2WebServerFlowTest(unittest2.TestCase):
@@ -1860,7 +1854,8 @@ class OAuth2WebServerFlowTest(unittest2.TestCase):
flow.step2_exchange(code='code', device_flow_info='dfi')
def test_scope_is_required(self):
self.assertRaises(TypeError, OAuth2WebServerFlow, 'client_id+1')
with self.assertRaises(TypeError):
OAuth2WebServerFlow('client_id+1')
def test_exchange_failure(self):
http = HttpMockSequence([
@@ -2057,8 +2052,8 @@ class OAuth2WebServerFlowTest(unittest2.TestCase):
b'}')
http = HttpMockSequence([({'status': '200'}, payload)])
self.assertRaises(VerifyJwtTokenError, self.flow.step2_exchange,
code='some random code', http=http)
with self.assertRaises(VerifyJwtTokenError):
self.flow.step2_exchange(code='some random code', http=http)
def test_exchange_id_token(self):
body = {'foo': 'bar'}
@@ -2382,7 +2377,3 @@ class TestDeviceFlowInfo(unittest2.TestCase):
expected_result = DeviceFlowInfo(self.DEVICE_CODE, self.USER_CODE,
None, self.VER_URL, expire)
self.assertEqual(result, expected_result)
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -40,31 +40,26 @@ NONEXISTENT_FILE = os.path.join(
class Test__validate_clientsecrets(unittest2.TestCase):
def test_with_none(self):
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
None)
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets(None)
def test_with_other_than_one_key(self):
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
{})
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
{'one': 'val', 'two': 'val'})
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets({})
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets({'one': 'val', 'two': 'val'})
def test_with_non_dictionary(self):
non_dict = [None]
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
non_dict)
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets(non_dict)
def test_invalid_client_type(self):
fake_type = 'fake_type'
self.assertNotEqual(fake_type, clientsecrets.TYPE_WEB)
self.assertNotEqual(fake_type, clientsecrets.TYPE_INSTALLED)
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
{fake_type: None})
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets({fake_type: None})
def test_missing_required_type_web(self):
required = clientsecrets.VALID_CLIENT[
@@ -75,9 +70,8 @@ class Test__validate_clientsecrets(unittest2.TestCase):
clientsecrets_dict = {
clientsecrets.TYPE_WEB: {'not_required': None},
}
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
clientsecrets_dict)
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets(clientsecrets_dict)
def test_string_not_configured_type_web(self):
string_props = clientsecrets.VALID_CLIENT[
@@ -93,9 +87,8 @@ class Test__validate_clientsecrets(unittest2.TestCase):
'token_uri': None,
},
}
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
clientsecrets_dict)
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets(clientsecrets_dict)
def test_missing_required_type_installed(self):
required = clientsecrets.VALID_CLIENT[
@@ -106,9 +99,8 @@ class Test__validate_clientsecrets(unittest2.TestCase):
clientsecrets_dict = {
clientsecrets.TYPE_INSTALLED: {'not_required': None},
}
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
clientsecrets_dict)
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets(clientsecrets_dict)
def test_string_not_configured_type_installed(self):
string_props = clientsecrets.VALID_CLIENT[
@@ -124,9 +116,8 @@ class Test__validate_clientsecrets(unittest2.TestCase):
'token_uri': None,
},
}
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._validate_clientsecrets,
clientsecrets_dict)
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._validate_clientsecrets(clientsecrets_dict)
def test_success_type_web(self):
client_info = {
@@ -175,15 +166,15 @@ class Test__loadfile(unittest2.TestCase):
def test_non_existent(self):
path = os.path.join(DATA_DIR, 'fake.json')
self.assertFalse(os.path.exists(path))
self.assertRaises(clientsecrets.InvalidClientSecretsError,
clientsecrets._loadfile, path)
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets._loadfile(path)
def test_bad_json(self):
filename = tempfile.mktemp()
with open(filename, 'wb') as file_obj:
file_obj.write(b'[')
self.assertRaises(ValueError,
clientsecrets._loadfile, filename)
with self.assertRaises(ValueError):
clientsecrets._loadfile(filename)
class OAuth2CredentialsTests(unittest2.TestCase):
@@ -288,7 +279,3 @@ class CachedClientsecretsTests(unittest2.TestCase):
client_type, client_info = clientsecrets.loadfile(VALID_FILE)
self.assertEqual('web', client_type)
self.assertEqual('foo_client_secret', client_info['client_secret'])
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -14,7 +14,7 @@
import base64
import os
import unittest
import unittest2
import mock
@@ -33,13 +33,14 @@ def datafile(filename):
return file_obj.read()
class Test__bad_pkcs12_key_as_pem(unittest.TestCase):
class Test__bad_pkcs12_key_as_pem(unittest2.TestCase):
def test_fails(self):
self.assertRaises(NotImplementedError, crypt._bad_pkcs12_key_as_pem)
with self.assertRaises(NotImplementedError):
crypt._bad_pkcs12_key_as_pem()
class Test_pkcs12_key_as_pem(unittest.TestCase):
class Test_pkcs12_key_as_pem(unittest2.TestCase):
def _make_svc_account_creds(self, private_key_file='privatekey.p12'):
filename = data_filename(private_key_file)
@@ -71,7 +72,7 @@ class Test_pkcs12_key_as_pem(unittest.TestCase):
self._succeeds_helper(password)
class Test__verify_signature(unittest.TestCase):
class Test__verify_signature(unittest2.TestCase):
def test_success_single_cert(self):
cert_value = 'cert-value'
@@ -134,8 +135,8 @@ class Test__verify_signature(unittest.TestCase):
with mock.patch('oauth2client.crypt.Verifier') as Verifier:
Verifier.from_string = mock.MagicMock(name='from_string',
return_value=verifier)
self.assertRaises(crypt.AppIdentityError, crypt._verify_signature,
message, signature, certs)
with self.assertRaises(crypt.AppIdentityError):
crypt._verify_signature(message, signature, certs)
# Make sure our mocks were called as expected.
Verifier.from_string.assert_called_once_with(cert_value,
@@ -143,7 +144,7 @@ class Test__verify_signature(unittest.TestCase):
verifier.verify.assert_called_once_with(message, signature)
class Test__check_audience(unittest.TestCase):
class Test__check_audience(unittest2.TestCase):
def test_null_audience(self):
result = crypt._check_audience(None, None)
@@ -159,18 +160,18 @@ class Test__check_audience(unittest.TestCase):
def test_missing_aud(self):
audience = 'audience'
payload_dict = {}
self.assertRaises(crypt.AppIdentityError, crypt._check_audience,
payload_dict, audience)
with self.assertRaises(crypt.AppIdentityError):
crypt._check_audience(payload_dict, audience)
def test_wrong_aud(self):
audience1 = 'audience1'
audience2 = 'audience2'
self.assertNotEqual(audience1, audience2)
payload_dict = {'aud': audience1}
self.assertRaises(crypt.AppIdentityError, crypt._check_audience,
payload_dict, audience2)
with self.assertRaises(crypt.AppIdentityError):
crypt._check_audience(payload_dict, audience2)
class Test__verify_time_range(unittest.TestCase):
class Test__verify_time_range(unittest2.TestCase):
def _exception_helper(self, payload_dict):
exception_caught = None
@@ -254,7 +255,7 @@ class Test__verify_time_range(unittest.TestCase):
self.assertEqual(exception_caught, None)
class Test_verify_signed_jwt_with_certs(unittest.TestCase):
class Test_verify_signed_jwt_with_certs(unittest2.TestCase):
def test_jwt_no_segments(self):
exception_caught = None
@@ -309,7 +310,3 @@ class Test_verify_signed_jwt_with_certs(unittest.TestCase):
verify_time.assert_called_once_with(payload_dict)
check_aud.assert_called_once_with(payload_dict, audience)
certs.values.assert_called_once_with()
if __name__ == '__main__': # pragma: NO COVER
unittest.main()

View File

@@ -241,7 +241,3 @@ class OAuth2ClientFileTests(unittest2.TestCase):
if os.name == 'posix': # pragma: NO COVER
mode = os.stat(FILENAME).st_mode
self.assertEquals('0o600', oct(stat.S_IMODE(mode)))
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -152,9 +152,10 @@ class CryptTests(unittest2.TestCase):
({'status': '404'}, datafile('certs.json')),
])
self.assertRaises(VerifyJwtTokenError, verify_id_token, jwt,
'some_audience_address@testing.gserviceaccount.com',
http=http)
with self.assertRaises(VerifyJwtTokenError):
verify_id_token(jwt,
'some_audience_address@testing.gserviceaccount.com',
http=http)
def test_verify_id_token_bad_tokens(self):
private_key = datafile('privatekey.' + self.format_)
@@ -330,7 +331,3 @@ class TestHasOpenSSLFlag(unittest2.TestCase):
def test_true(self):
self.assertEqual(True, HAS_OPENSSL)
self.assertEqual(True, HAS_CRYPTO)
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -87,11 +87,10 @@ class ServiceAccountCredentialsTests(unittest2.TestCase):
self.assertTrue(rsa.pkcs1.verify(b'Google', signature, pub_key))
self.assertRaises(rsa.pkcs1.VerificationError,
rsa.pkcs1.verify, b'Orest', signature, pub_key)
self.assertRaises(rsa.pkcs1.VerificationError,
rsa.pkcs1.verify,
b'Google', b'bad signature', pub_key)
with self.assertRaises(rsa.pkcs1.VerificationError):
rsa.pkcs1.verify(b'Orest', signature, pub_key)
with self.assertRaises(rsa.pkcs1.VerificationError):
rsa.pkcs1.verify(b'Google', b'bad signature', pub_key)
def test_service_account_email(self):
self.assertEqual(self.service_account_email,
@@ -582,6 +581,3 @@ class JWTAccessCredentialsTests(unittest2.TestCase):
token_2 = self.jwt.access_token
self.assertEquals(self.jwt.token_expiry, T2_EXPIRY_DATE)
self.assertNotEqual(token_1, token_2)
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()

View File

@@ -102,7 +102,7 @@ class TestRunFlow(unittest2.TestCase):
self.assertEqual(self.flow.redirect_uri, OOB_CALLBACK_URN)
self.flow.step2_exchange.assert_called_once_with(
'auth_code', http=None)
@mock.patch('oauth2client.tools.logging')
@mock.patch('oauth2client.tools.input')
def test_run_flow_no_webserver_exchange_error(
@@ -161,7 +161,7 @@ class TestRunFlow(unittest2.TestCase):
self, webbrowser_open_mock, server_ctor_mock, logging_mock):
server_ctor_mock.return_value = self.server
self.server.query_params = {}
# No code found in response
with self.assertRaises(SystemExit):
returned_credentials = tools.run_flow(
@@ -193,7 +193,3 @@ class TestRunFlow(unittest2.TestCase):
class TestMessageIfMissing(unittest2.TestCase):
def test_message_if_missing(self):
self.assertIn('somefile.txt', tools.message_if_missing('somefile.txt'))
if __name__ == '__main__': # pragma: NO COVER
unittest.main()

View File

@@ -22,7 +22,8 @@ class PositionalTests(unittest2.TestCase):
self.assertTrue(fn(1))
self.assertTrue(fn(1, kwonly=2))
self.assertRaises(TypeError, fn, 1, 2)
with self.assertRaises(TypeError):
fn(1, 2)
# No positional, but a required keyword arg.
@util.positional(0)
@@ -30,7 +31,8 @@ class PositionalTests(unittest2.TestCase):
return True
self.assertTrue(fn2(required_kw=1))
self.assertRaises(TypeError, fn2, 1)
with self.assertRaises(TypeError):
fn2(1)
# Unspecified positional, should automatically figure out 1 positional
# 1 keyword-only (same as first case above).
@@ -40,7 +42,8 @@ class PositionalTests(unittest2.TestCase):
self.assertTrue(fn3(1))
self.assertTrue(fn3(1, kwonly=2))
self.assertRaises(TypeError, fn3, 1, 2)
with self.assertRaises(TypeError):
fn3(1, 2)
@mock.patch('oauth2client.util.logger')
@@ -121,6 +124,3 @@ class AddQueryParameterTests(unittest2.TestCase):
self.assertEqual(
util._add_query_parameter('/action', 'a', ' ='),
'/action?a=+%3D')
if __name__ == '__main__': # pragma: NO COVER
unittest2.main()