Skip to content

Commit

Permalink
Use testtools as base test class.
Browse files Browse the repository at this point in the history
Minor tests refactoring due to use testtools:
 - added missed setUp() and tearDown() to call these functions in
   base test case.
 - removed some superfluous tearDown() calls.
 - moved test_crud_inherited_role_grants_failed_if_disabled() method
   to separate class.

Fixes for python 2.6 enviroment:
 - replaced `with self.assertRaises(Exception): foo()` to
   `self.assertRaises(Exception, foo)
 - added to safe_repr(), assertDictEqual() and assertRaisesRegexp() methods
   to TestCase() class in keystone/test.py

Fixes bug 1179009

Change-Id: Iea67ad10d02db82fc8ed79b1096ddb5233925bfd
  • Loading branch information
vikt0rs committed Aug 29, 2013
1 parent 8fdfbf0 commit 221851c
Show file tree
Hide file tree
Showing 17 changed files with 147 additions and 93 deletions.
4 changes: 2 additions & 2 deletions keystone/tests/_test_import_auth_token.py
Expand Up @@ -8,10 +8,10 @@
"""

import unittest
import testtools


class TestAuthToken(unittest.TestCase):
class TestAuthToken(testtools.TestCase):
def test_import(self):
# a consuming service like nova would import oslo.config first
from oslo.config import cfg
Expand Down
47 changes: 42 additions & 5 deletions keystone/tests/core.py
Expand Up @@ -14,9 +14,9 @@
# License for the specific language governing permissions and limitations
# under the License.

import datetime
import errno
import os
import re
import shutil
import socket
import StringIO
Expand All @@ -28,7 +28,7 @@
import nose.exc
from paste import deploy
import stubout
import unittest2 as unittest
import testtools

from keystone.common import environment
environment.use_eventlet()
Expand Down Expand Up @@ -203,7 +203,7 @@ def find_module(self, fullname, path):
sys.meta_path.insert(0, finder)


class TestCase(NoModule, unittest.TestCase):
class TestCase(NoModule, testtools.TestCase):
def __init__(self, *args, **kw):
super(TestCase, self).__init__(*args, **kw)
self._paths = []
Expand Down Expand Up @@ -377,14 +377,51 @@ def assertCloseEnoughForGovernmentWork(self, a, b, delta=3):
:param delta: Maximum allowable time delta, defined in seconds.
"""
self.assertAlmostEqual(a, b, delta=datetime.timedelta(seconds=delta))
msg = '%s != %s within %s delta' % (a, b, delta)

self.assertTrue(abs(a - b).seconds <= delta, msg)

def assertNotEmpty(self, l):
self.assertTrue(len(l))

def assertDictEqual(self, d1, d2, msg=None):
self.assert_(isinstance(d1, dict), 'First argument is not a dict')
self.assert_(isinstance(d2, dict), 'Second argument is not a dict')
self.assertEqual(d1, d2, msg)

def assertRaisesRegexp(self, expected_exception, expected_regexp,
callable_obj, *args, **kwargs):
"""Asserts that the message in a raised exception matches a regexp.
"""
try:
callable_obj(*args, **kwargs)
except expected_exception as exc_value:
if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(str(exc_value)):
raise self.failureException(
'"%s" does not match "%s"' %
(expected_regexp.pattern, str(exc_value)))
else:
if hasattr(expected_exception, '__name__'):
excName = expected_exception.__name__
else:
excName = str(expected_exception)
raise self.failureException, "%s not raised" % excName

def assertDictContainsSubset(self, expected, actual, msg=None):
"""Checks whether actual is a superset of expected."""
safe_repr = unittest.util.safe_repr

def safe_repr(obj, short=False):
_MAX_LENGTH = 80
try:
result = repr(obj)
except Exception:
result = object.__repr__(obj)
if not short or len(result) < _MAX_LENGTH:
return result
return result[:_MAX_LENGTH] + ' [truncated]...'

missing = []
mismatched = []
for key, value in expected.iteritems():
Expand Down
18 changes: 12 additions & 6 deletions keystone/tests/test_backend.py
Expand Up @@ -2634,16 +2634,22 @@ def test_list_trusts(self):

class CommonHelperTests(test.TestCase):
def test_format_helper_raises_malformed_on_missing_key(self):
with self.assertRaises(exception.MalformedEndpoint):
core.format_url("http://%(foo)s/%(bar)s", {"foo": "1"})
self.assertRaises(exception.MalformedEndpoint,
core.format_url,
"http://%(foo)s/%(bar)s",
{"foo": "1"})

def test_format_helper_raises_malformed_on_wrong_type(self):
with self.assertRaises(exception.MalformedEndpoint):
core.format_url("http://%foo%s", {"foo": "1"})
self.assertRaises(exception.MalformedEndpoint,
core.format_url,
"http://%foo%s",
{"foo": "1"})

def test_format_helper_raises_malformed_on_incomplete_format(self):
with self.assertRaises(exception.MalformedEndpoint):
core.format_url("http://%(foo)", {"foo": "1"})
self.assertRaises(exception.MalformedEndpoint,
core.format_url,
"http://%(foo)",
{"foo": "1"})


class CatalogTests(object):
Expand Down
51 changes: 32 additions & 19 deletions keystone/tests/test_backend_ldap.py
Expand Up @@ -584,25 +584,36 @@ def test_parse_extra_attribute_mapping(self):
def test_domain_crud(self):
domain = {'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex,
'enabled': True, 'description': uuid.uuid4().hex}
with self.assertRaises(exception.Forbidden):
self.identity_api.create_domain(domain['id'], domain)
with self.assertRaises(exception.Conflict):
self.identity_api.create_domain(
CONF.identity.default_domain_id, domain)
with self.assertRaises(exception.DomainNotFound):
self.identity_api.get_domain(domain['id'])
with self.assertRaises(exception.DomainNotFound):
domain['description'] = uuid.uuid4().hex
self.identity_api.update_domain(domain['id'], domain)
with self.assertRaises(exception.Forbidden):
self.identity_api.update_domain(
CONF.identity.default_domain_id, domain)
with self.assertRaises(exception.DomainNotFound):
self.identity_api.get_domain(domain['id'])
with self.assertRaises(exception.DomainNotFound):
self.identity_api.delete_domain(domain['id'])
with self.assertRaises(exception.Forbidden):
self.identity_api.delete_domain(CONF.identity.default_domain_id)
self.assertRaises(exception.Forbidden,
self.identity_api.create_domain,
domain['id'],
domain)
self.assertRaises(exception.Conflict,
self.identity_api.create_domain,
CONF.identity.default_domain_id,
domain)
self.assertRaises(exception.DomainNotFound,
self.identity_api.get_domain,
domain['id'])

domain['description'] = uuid.uuid4().hex
self.assertRaises(exception.DomainNotFound,
self.identity_api.update_domain,
domain['id'],
domain)
self.assertRaises(exception.Forbidden,
self.identity_api.update_domain,
CONF.identity.default_domain_id,
domain)
self.assertRaises(exception.DomainNotFound,
self.identity_api.get_domain,
domain['id'])
self.assertRaises(exception.DomainNotFound,
self.identity_api.delete_domain,
domain['id'])
self.assertRaises(exception.Forbidden,
self.identity_api.delete_domain,
CONF.identity.default_domain_id)
self.assertRaises(exception.DomainNotFound,
self.identity_api.get_domain,
domain['id'])
Expand Down Expand Up @@ -770,6 +781,7 @@ def _set_config(self):
test.testsdir('backend_ldap_sql.conf')])

def setUp(self):
super(LdapIdentitySqlAssignment, self).setUp()
self._set_config()
self.clear_database()
self.load_backends()
Expand All @@ -783,6 +795,7 @@ def tearDown(self):
sql.ModelBase.metadata.drop_all(bind=self.engine)
self.engine.dispose()
sql.set_global_engine(None)
super(LdapIdentitySqlAssignment, self).tearDown()

def test_domain_crud(self):
pass
Expand Down
4 changes: 2 additions & 2 deletions keystone/tests/test_backend_memcache.py
Expand Up @@ -138,8 +138,8 @@ def test_list_tokens_unicode_user_id(self):
self.token_api.list_tokens(user_id)

def test_flush_expired_token(self):
with self.assertRaises(exception.NotImplemented):
self.token_api.flush_expired_tokens()
self.assertRaises(exception.NotImplemented,
self.token_api.flush_expired_tokens)

def test_cleanup_user_index_on_create(self):
valid_token_id = uuid.uuid4().hex
Expand Down
12 changes: 8 additions & 4 deletions keystone/tests/test_backend_sql.py
Expand Up @@ -357,8 +357,10 @@ def test_malformed_catalog_throws_error(self):
}
self.catalog_api.create_endpoint(endpoint['id'], endpoint.copy())

with self.assertRaises(exception.MalformedEndpoint):
self.catalog_api.get_catalog('fake-user', 'fake-tenant')
self.assertRaises(exception.MalformedEndpoint,
self.catalog_api.get_catalog,
'fake-user',
'fake-tenant')

def test_get_catalog_with_empty_public_url(self):
service = {
Expand Down Expand Up @@ -403,8 +405,10 @@ def test_create_endpoint_400(self):
'url': uuid.uuid4().hex,
}

with self.assertRaises(exception.StringLengthExceeded):
self.catalog_api.create_endpoint(endpoint['id'], endpoint.copy())
self.assertRaises(exception.StringLengthExceeded,
self.catalog_api.create_endpoint,
endpoint['id'],
endpoint.copy())


class SqlPolicy(SqlTests, test_backend.PolicyTests):
Expand Down
6 changes: 4 additions & 2 deletions keystone/tests/test_backend_templated.py
Expand Up @@ -63,5 +63,7 @@ def test_malformed_catalog_throws_error(self):
(self.catalog_api.driver.templates
['RegionOne']['compute']['adminURL']) = \
'http://localhost:$(compute_port)s/v1.1/$(tenant)s'
with self.assertRaises(exception.MalformedEndpoint):
self.catalog_api.get_catalog('fake-user', 'fake-tenant')
self.assertRaises(exception.MalformedEndpoint,
self.catalog_api.get_catalog,
'fake-user',
'fake-tenant')
7 changes: 3 additions & 4 deletions keystone/tests/test_drivers.py
@@ -1,5 +1,5 @@
import inspect
import unittest2 as unittest
import testtools

from keystone import assignment
from keystone import catalog
Expand All @@ -11,7 +11,7 @@
from keystone import token


class TestDrivers(unittest.TestCase):
class TestDrivers(testtools.TestCase):
"""Asserts that drivers are written as expected.
Public methods on drivers should raise keystone.exception.NotImplemented,
Expand All @@ -28,8 +28,7 @@ def assertMethodNotImplemented(self, f):
args = inspect.getargspec(f).args
args.remove('self')
kwargs = dict(zip(args, [None] * len(args)))
with self.assertRaises(exception.NotImplemented):
f(**kwargs)
self.assertRaises(exception.NotImplemented, f, **kwargs)

def assertInterfaceNotImplemented(self, interface):
"""Public methods on an interface class should not be implemented."""
Expand Down
6 changes: 0 additions & 6 deletions keystone/tests/test_exception.py
Expand Up @@ -28,12 +28,6 @@


class ExceptionTestCase(test.TestCase):
def setUp(self):
pass

def tearDown(self):
pass

def assertValidJsonRendering(self, e):
resp = wsgi.render_exception(e)
self.assertEqual(resp.status_int, e.code)
Expand Down
8 changes: 5 additions & 3 deletions keystone/tests/test_injection.py
Expand Up @@ -14,13 +14,13 @@
# License for the specific language governing permissions and limitations
# under the License.

import unittest2 as unittest
import testtools
import uuid

from keystone.common import dependency


class TestDependencyInjection(unittest.TestCase):
class TestDependencyInjection(testtools.TestCase):
def tearDown(self):
dependency.reset()
super(TestDependencyInjection, self).tearDown()
Expand Down Expand Up @@ -167,10 +167,12 @@ def test_unresolvable_dependency(self):
class Consumer(object):
pass

with self.assertRaises(dependency.UnresolvableDependencyException):
def for_test():
Consumer()
dependency.resolve_future_dependencies()

self.assertRaises(dependency.UnresolvableDependencyException, for_test)

def test_circular_dependency(self):
p1_name = uuid.uuid4().hex
p2_name = uuid.uuid4().hex
Expand Down
1 change: 1 addition & 0 deletions keystone/tests/test_no_admin_token_auth.py
Expand Up @@ -32,6 +32,7 @@ def setUp(self):
def tearDown(self):
self.admin_app = None
os.remove(test.tmpdir('no_admin_token_auth-paste.ini'))
super(TestNoAdminTokenAuth, self).tearDown()

def test_request_no_admin_token_auth(self):
# This test verifies that if the admin_token_auth middleware isn't
Expand Down
2 changes: 1 addition & 1 deletion keystone/tests/test_policy.py
Expand Up @@ -175,7 +175,7 @@ def _set_rules(self, default_rule):
common_policy.set_rules(these_rules)

def tearDown(self):
super(DefaultPolicyTestCase, self).setUp()
super(DefaultPolicyTestCase, self).tearDown()
rules.reset()

def test_policy_called(self):
Expand Down
6 changes: 3 additions & 3 deletions keystone/tests/test_s3_token_middleware.py
Expand Up @@ -14,7 +14,7 @@
# License for the specific language governing permissions and limitations
# under the License.

import unittest2 as unittest
import testtools
import webob

from keystone.middleware import s3_token
Expand Down Expand Up @@ -53,7 +53,7 @@ def request(self, method, path, **kwargs):
pass


class S3TokenMiddlewareTestBase(unittest.TestCase):
class S3TokenMiddlewareTestBase(testtools.TestCase):
def setUp(self):
super(S3TokenMiddlewareTestBase, self).setUp()

Expand Down Expand Up @@ -194,7 +194,7 @@ def request(self, method, path, **kwargs):
self.assertEqual(resp.status_int, s3_invalid_req.status_int)


class S3TokenMiddlewareTestUtil(unittest.TestCase):
class S3TokenMiddlewareTestUtil(testtools.TestCase):
def test_split_path_failed(self):
self.assertRaises(ValueError, s3_token.split_path, '')
self.assertRaises(ValueError, s3_token.split_path, '/')
Expand Down
6 changes: 2 additions & 4 deletions keystone/tests/test_v3.py
Expand Up @@ -45,6 +45,7 @@ def setUp(self, load_sample_data=True, app_conf='keystone'):
load_sample_data should be set to false.
"""
super(RestfulTestCase, self).setUp()
self.config(self.config_files())

self.setup_database()
Expand Down Expand Up @@ -130,15 +131,12 @@ def tearDown(self):
self.public_server = None
self.admin_server = None
self.teardown_database()
# NOTE(morganfainberg): The only way to reconfigure the
# CacheRegion object on each setUp() call is to remove the
# .backend property.
del cache.REGION.backend
# need to reset the plug-ins
auth.controllers.AUTH_METHODS = {}
#drop the policy rules
CONF.reset()
rules.reset()
super(RestfulTestCase, self).tearDown()

def new_ref(self):
"""Populates a ref with attributes common to all API entities."""
Expand Down

0 comments on commit 221851c

Please sign in to comment.