Skip to content

Commit

Permalink
Improved unit-test line coverage and quality.
Browse files Browse the repository at this point in the history
In particular

- Upgraded some unit test modules to `unittest2`.
- Got to 100% line coverage in `test_jwt`, `test_clientsecrets`,
  and `test_service_account` by using `self.assertRaises`
  instead of `self.fail()`
- In some places used `self.assertRaises` as a context manager so
  the thrown exception can be inspected / compared against. This
  is done instead of manually catching the exception and
  holding on to it (`unittest2` backports this feature from
  `unittest` that was not available in Python 2.6)
- Added license to `test_multistore_file`
- Removed legacy `python2.4` hashbang from `test_jwt` and
  `test_service_account`
- Added `unittest2` as a test dependency in `tox.ini`
- Updated `test_clientsecrets.test_load_by_filename_missing_file`
  to use the `self.assertRaises` context manager (this was
  a problem in googleapis#349 and googleapis#350)
- Updated `test_jwt` module docstring to reflect actual purpose
  • Loading branch information
dhermes committed Dec 14, 2015
1 parent 7559dcb commit f3a118a
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 59 deletions.
14 changes: 14 additions & 0 deletions tests/contrib/test_multistore_file.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Unit tests for oauth2client.multistore_file."""

import datetime
Expand Down
44 changes: 19 additions & 25 deletions tests/test_clientsecrets.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from io import StringIO
import os
import tempfile
import unittest
import unittest2

from oauth2client._helpers import _from_bytes
from oauth2client import GOOGLE_AUTH_URI
Expand All @@ -37,7 +37,7 @@
os.path.dirname(__file__), 'afilethatisntthere.json')


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

def test_with_none(self):
self.assertRaises(clientsecrets.InvalidClientSecretsError,
Expand Down Expand Up @@ -157,7 +157,7 @@ def test_success_type_installed(self):
self.assertEqual(result, (clientsecrets.TYPE_INSTALLED, client_info))


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

def test_success(self):
client_type, client_info = clientsecrets._loadfile(VALID_FILE)
Expand Down Expand Up @@ -186,7 +186,7 @@ def test_bad_json(self):
clientsecrets._loadfile, filename)


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

def test_validate_error(self):
payload = (
Expand All @@ -210,32 +210,30 @@ def test_validate_error(self):
# Ensure that it is unicode
src = _from_bytes(src)
# Test load(s)
try:
with self.assertRaises(
clientsecrets.InvalidClientSecretsError) as exc_manager:
clientsecrets.loads(src)
self.fail(src + ' should not be a valid client_secrets file.')
except clientsecrets.InvalidClientSecretsError as e:
self.assertTrue(str(e).startswith(match))

self.assertTrue(str(exc_manager.exception).startswith(match))

# Test loads(fp)
try:
with self.assertRaises(
clientsecrets.InvalidClientSecretsError) as exc_manager:
fp = StringIO(src)
clientsecrets.load(fp)
self.fail(src + ' should not be a valid client_secrets file.')
except clientsecrets.InvalidClientSecretsError as e:
self.assertTrue(str(e).startswith(match))

self.assertTrue(str(exc_manager.exception).startswith(match))

def test_load_by_filename_missing_file(self):
caught_exception = None
try:
with self.assertRaises(
clientsecrets.InvalidClientSecretsError) as exc_manager:
clientsecrets._loadfile(NONEXISTENT_FILE)
except clientsecrets.InvalidClientSecretsError as exc:
caught_exception = exc

self.assertEquals(caught_exception.args[1], NONEXISTENT_FILE)
self.assertEquals(caught_exception.args[3], errno.ENOENT)
self.assertEquals(exc_manager.exception.args[1], NONEXISTENT_FILE)
self.assertEquals(exc_manager.exception.args[3], errno.ENOENT)


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

class CacheMock(object):
def __init__(self):
Expand Down Expand Up @@ -282,12 +280,8 @@ def test_cache_hit(self):
self.assertEqual(None, self.cache_mock.last_set_ns)

def test_validation(self):
try:
with self.assertRaises(clientsecrets.InvalidClientSecretsError):
clientsecrets.loadfile(INVALID_FILE, cache=self.cache_mock)
self.fail('Expected InvalidClientSecretsError to be raised '
'while loading %s' % INVALID_FILE)
except clientsecrets.InvalidClientSecretsError:
pass

def test_without_cache(self):
# this also ensures loadfile() is backward compatible
Expand All @@ -297,4 +291,4 @@ def test_without_cache(self):


if __name__ == '__main__': # pragma: NO COVER
unittest.main()
unittest2.main()
35 changes: 14 additions & 21 deletions tests/test_jwt.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/python2.4
#
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -14,15 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

"""Oauth2client tests
Unit tests for oauth2client.
"""
"""Unit tests for JWT related methods in oauth2client."""

import os
import tempfile
import time
import unittest
import unittest2

from .http_mock import HttpMockSequence
from oauth2client.client import Credentials
Expand All @@ -45,7 +40,7 @@ def datafile(filename):
return data


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

def setUp(self):
self.format = 'p12'
Expand Down Expand Up @@ -83,11 +78,11 @@ def _check_jwt_failure(self, jwt, expected_error):
certs = {'foo': public_key}
audience = ('https://www.googleapis.com/auth/id?client_id='
'[email protected]')
try:

with self.assertRaises(crypt.AppIdentityError) as exc_manager:
crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
self.fail()
except crypt.AppIdentityError as e:
self.assertTrue(expected_error in str(e))

self.assertTrue(expected_error in str(exc_manager.exception))

def _create_signed_jwt(self):
private_key = datafile('privatekey.%s' % self.format)
Expand Down Expand Up @@ -216,7 +211,7 @@ def setUp(self):
self.verifier = crypt.OpenSSLVerifier


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

def setUp(self):
self.format = 'p12'
Expand Down Expand Up @@ -310,7 +305,7 @@ def setUp(self):
crypt.Signer = crypt.PyCryptoSigner


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

def test_for_failure(self):
crypt.Signer = crypt.PyCryptoSigner
Expand All @@ -320,19 +315,17 @@ def test_for_failure(self):
private_key,
scope='read+write',
sub='[email protected]')
try:
credentials._generate_assertion()
self.fail()
except NotImplementedError:
pass

self.assertRaises(NotImplementedError,
credentials._generate_assertion)


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

def test_true(self):
self.assertEqual(True, HAS_OPENSSL)
self.assertEqual(True, HAS_CRYPTO)


if __name__ == '__main__': # pragma: NO COVER
unittest.main()
unittest2.main()
18 changes: 5 additions & 13 deletions tests/test_service_account.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/python2.4
#
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -61,17 +59,11 @@ def test_sign_blob(self):

self.assertTrue(rsa.pkcs1.verify(b'Google', signature, pub_key))

try:
rsa.pkcs1.verify(b'Orest', signature, pub_key)
self.fail('Verification should have failed!')
except rsa.pkcs1.VerificationError:
pass # Expected

try:
rsa.pkcs1.verify(b'Google', b'bad signature', pub_key)
self.fail('Verification should have failed!')
except rsa.pkcs1.VerificationError:
pass # Expected
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)

def test_service_account_email(self):
self.assertEqual(self.service_account_email,
Expand Down
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ basedeps = keyring
webtest
nose
flask
unittest2
deps = {[testenv]basedeps}
django
setenv =
Expand Down

0 comments on commit f3a118a

Please sign in to comment.