From 827547a0b3da411441bf691ddbc94867001a3311 Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Tue, 22 Jan 2013 19:54:57 -0500 Subject: Use testtools as test base class. On the path to testr migration, we need to replace the unittest base classes with testtools. Replace tearDown with addCleanup, addCleanup is more resilient than tearDown. The fixtures library has excellent support for managing and cleaning tempfiles. Use it. Replace skip_ with testtools.skipTest Part of blueprint grizzly-testtools. Change-Id: I45e11bbb1ff9b31f3278d3b016737dcb7850cd98 --- HACKING.rst | 2 +- openstack/common/testutils.py | 68 ------------------------------- tests/unit/middleware/test_context.py | 6 +-- tests/unit/rpc/common.py | 7 +--- tests/unit/rpc/test_dispatcher.py | 9 ++-- tests/unit/rpc/test_fake.py | 5 +-- tests/unit/rpc/test_kombu.py | 54 ++++++------------------ tests/unit/rpc/test_kombu_ssl.py | 4 +- tests/unit/rpc/test_matchmaker.py | 4 +- tests/unit/rpc/test_proxy.py | 12 ++---- tests/unit/rpc/test_qpid.py | 33 +++++---------- tests/unit/rpc/test_zmq.py | 23 +++++------ tests/unit/scheduler/test_host_filters.py | 6 +-- tests/unit/scheduler/test_weights.py | 4 +- tests/unit/test_authutils.py | 4 +- tests/unit/test_cfg.py | 38 ++++++++--------- tests/unit/test_cliutils.py | 4 +- tests/unit/test_context.py | 4 +- tests/unit/test_exception.py | 12 +++--- tests/unit/test_excutils.py | 4 +- tests/unit/test_fileutils.py | 4 +- tests/unit/test_gettext.py | 4 +- tests/unit/test_importutils.py | 4 +- tests/unit/test_iniparser.py | 10 +++-- tests/unit/test_jsonutils.py | 6 +-- tests/unit/test_local.py | 4 +- tests/unit/test_lockutils.py | 3 +- tests/unit/test_log.py | 7 +--- tests/unit/test_loopingcall.py | 5 ++- tests/unit/test_network_utils.py | 4 +- tests/unit/test_notifier.py | 11 +---- tests/unit/test_pastedeploy.py | 17 +++----- tests/unit/test_plugin.py | 14 +------ tests/unit/test_policy.py | 54 ++++++++++++------------ tests/unit/test_processutils.py | 6 +-- tests/unit/test_rootwrap.py | 4 +- tests/unit/test_service.py | 9 ++-- tests/unit/test_setup.py | 22 +++++----- tests/unit/test_strutils.py | 4 +- tests/unit/test_testutils.py | 43 ------------------- tests/unit/test_timeutils.py | 11 +++-- tests/unit/test_uuidutils.py | 4 +- tests/unit/test_version.py | 9 ++-- tests/unit/test_wsgi.py | 42 +++++++++---------- tests/utils.py | 14 +++---- 45 files changed, 208 insertions(+), 410 deletions(-) delete mode 100644 openstack/common/testutils.py delete mode 100644 tests/unit/test_testutils.py diff --git a/HACKING.rst b/HACKING.rst index 39f94df..7dda11a 100644 --- a/HACKING.rst +++ b/HACKING.rst @@ -65,9 +65,9 @@ Example:: import random import StringIO import time - import unittest import eventlet + import testtools import webob.exc import nova.api.ec2 diff --git a/openstack/common/testutils.py b/openstack/common/testutils.py deleted file mode 100644 index 5c438e3..0000000 --- a/openstack/common/testutils.py +++ /dev/null @@ -1,68 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2010 United States Government as represented by the -# Administrator of the National Aeronautics and Space Administration. -# 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. - -"""Utilities for unit tests.""" - -import functools -import nose - - -class skip_test(object): - """Decorator that skips a test.""" - # TODO(tr3buchet): remember forever what comstud did here - def __init__(self, msg): - self.message = msg - - def __call__(self, func): - @functools.wraps(func) - def _skipper(*args, **kw): - """Wrapped skipper function.""" - raise nose.SkipTest(self.message) - return _skipper - - -class skip_if(object): - """Decorator that skips a test if condition is true.""" - def __init__(self, condition, msg): - self.condition = condition - self.message = msg - - def __call__(self, func): - @functools.wraps(func) - def _skipper(*args, **kw): - """Wrapped skipper function.""" - if self.condition: - raise nose.SkipTest(self.message) - func(*args, **kw) - return _skipper - - -class skip_unless(object): - """Decorator that skips a test if condition is not true.""" - def __init__(self, condition, msg): - self.condition = condition - self.message = msg - - def __call__(self, func): - @functools.wraps(func) - def _skipper(*args, **kw): - """Wrapped skipper function.""" - if not self.condition: - raise nose.SkipTest(self.message) - func(*args, **kw) - return _skipper diff --git a/tests/unit/middleware/test_context.py b/tests/unit/middleware/test_context.py index 68ae0ad..3d48c23 100644 --- a/tests/unit/middleware/test_context.py +++ b/tests/unit/middleware/test_context.py @@ -15,7 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools import mock @@ -24,7 +24,7 @@ import openstack.common.context from openstack.common.middleware import context -class ContextMiddlewareTest(unittest.TestCase): +class ContextMiddlewareTest(testtools.TestCase): def test_process_request(self): req = mock.Mock() @@ -60,7 +60,7 @@ class ContextMiddlewareTest(unittest.TestCase): import_class.assert_called_with(mock.sentinel.arg) -class FilterFactoryTest(unittest.TestCase): +class FilterFactoryTest(testtools.TestCase): def test_filter_factory(self): global_conf = dict(sentinel=mock.sentinel.global_conf) diff --git a/tests/unit/rpc/common.py b/tests/unit/rpc/common.py index 5aed7bf..404937d 100644 --- a/tests/unit/rpc/common.py +++ b/tests/unit/rpc/common.py @@ -41,6 +41,7 @@ LOG = logging.getLogger(__name__) class BaseRpcTestCase(test_utils.BaseTestCase): + def setUp(self, supports_timeouts=True, topic='test', topic_nested='nested'): super(BaseRpcTestCase, self).setUp() @@ -53,11 +54,7 @@ class BaseRpcTestCase(test_utils.BaseTestCase): if self.rpc: receiver = TestReceiver() self.conn = self._create_consumer(receiver, self.topic) - - def tearDown(self): - if self.rpc: - self.conn.close() - super(BaseRpcTestCase, self).tearDown() + self.addCleanup(self.conn.close) def _create_consumer(self, proxy, topic, fanout=False): dispatcher = rpc_dispatcher.RpcDispatcher([proxy]) diff --git a/tests/unit/rpc/test_dispatcher.py b/tests/unit/rpc/test_dispatcher.py index 10cf933..f41abdf 100644 --- a/tests/unit/rpc/test_dispatcher.py +++ b/tests/unit/rpc/test_dispatcher.py @@ -18,14 +18,14 @@ Unit Tests for rpc.dispatcher """ -import unittest +import testtools from openstack.common import context from openstack.common.rpc import common as rpc_common from openstack.common.rpc import dispatcher -class RpcDispatcherTestCase(unittest.TestCase): +class RpcDispatcherTestCase(testtools.TestCase): class API1(object): RPC_API_VERSION = '1.0' @@ -60,11 +60,8 @@ class RpcDispatcherTestCase(unittest.TestCase): self.test_method_arg1 = arg1 def setUp(self): - self.ctxt = context.RequestContext('fake_user', 'fake_project') super(RpcDispatcherTestCase, self).setUp() - - def tearDown(self): - super(RpcDispatcherTestCase, self).tearDown() + self.ctxt = context.RequestContext('fake_user', 'fake_project') def _test_dispatch(self, version, expectations): v2 = self.API2() diff --git a/tests/unit/rpc/test_fake.py b/tests/unit/rpc/test_fake.py index b3079d6..17e4a68 100644 --- a/tests/unit/rpc/test_fake.py +++ b/tests/unit/rpc/test_fake.py @@ -32,9 +32,8 @@ CONF = cfg.CONF class RpcFakeTestCase(common.BaseRpcTestCase): - def setUp(self): - self.rpc = impl_fake - super(RpcFakeTestCase, self).setUp() + + rpc = impl_fake def test_non_primitive_raises(self): class Foo(object): diff --git a/tests/unit/rpc/test_kombu.py b/tests/unit/rpc/test_kombu.py index d3edbdf..c8e41ff 100644 --- a/tests/unit/rpc/test_kombu.py +++ b/tests/unit/rpc/test_kombu.py @@ -24,15 +24,15 @@ eventlet.monkey_patch() import contextlib import logging -import unittest +import testtools import stubout from openstack.common import cfg from openstack.common import exception +from openstack.common.fixture import moxstubout from openstack.common.rpc import amqp as rpc_amqp from openstack.common.rpc import common as rpc_common -from openstack.common import testutils from tests.unit.rpc import common from tests import utils @@ -69,32 +69,23 @@ def _raise_exc_stub(stubs, times, obj, method, exc_msg, class KombuStubs: @staticmethod def setUp(self): - self.stubs = stubout.StubOutForTesting() + self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs if kombu: self.config(fake_rabbit=True) self.config(rpc_response_timeout=5) self.rpc = impl_kombu + self.addCleanup(impl_kombu.cleanup) else: self.rpc = None - @staticmethod - def tearDown(self): - self.stubs.UnsetAll() - self.stubs.SmartUnsetAll() - if kombu: - impl_kombu.cleanup() - class RpcKombuTestCase(common.BaseRpcAMQPTestCase): def setUp(self): KombuStubs.setUp(self) - common.BaseRpcAMQPTestCase.setUp(self) - - def tearDown(self): - common.BaseRpcAMQPTestCase.tearDown(self) - KombuStubs.tearDown(self) + super(RpcKombuTestCase, self).setUp() + if kombu is None: + self.skipTest("Test requires kombu") - @testutils.skip_if(kombu is None, "Test requires kombu") def test_reusing_connection(self): """Test that reusing a connection returns same one.""" conn_context = self.rpc.create_connection(FLAGS, new=False) @@ -105,7 +96,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): conn_context.close() self.assertEqual(conn1, conn2) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_topic_send_receive(self): """Test sending to a topic exchange/queue""" @@ -124,7 +114,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(self.received_message, message) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_topic_send_receive_exchange_name(self): """Test sending to a topic exchange/queue with an exchange name""" @@ -144,7 +133,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(self.received_message, message) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_topic_multiple_queues(self): """Test sending to a topic exchange with multiple queues""" @@ -169,7 +157,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(self.received_message_1, message) self.assertEqual(self.received_message_2, message) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_topic_multiple_queues_specify_exchange(self): """Test sending to a topic exchange with multiple queues and one exchange @@ -199,7 +186,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(self.received_message_1, message) self.assertEqual(self.received_message_2, message) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_topic_one_queues_multiple_exchange(self): """Test sending to a topic exchange with one queues and several exchanges @@ -229,7 +215,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(self.received_message_1, message) self.assertEqual(self.received_message_2, message) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_direct_send_receive(self): """Test sending to a direct exchange/queue""" conn = self.rpc.create_connection(FLAGS) @@ -247,7 +232,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(self.received_message, message) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_cast_interface_uses_default_options(self): """Test kombu rpc.cast""" @@ -274,7 +258,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): impl_kombu.cast(FLAGS, ctxt, 'fake_topic', {'msg': 'fake'}) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_cast_to_server_uses_server_params(self): """Test kombu rpc.cast""" @@ -308,12 +291,12 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): impl_kombu.cast_to_server(FLAGS, ctxt, server_params, 'fake_topic', {'msg': 'fake'}) - @testutils.skip_test("kombu memory transport seems buggy with " - "fanout queues as this test passes when " - "you use rabbit (fake_rabbit=False)") def test_fanout_send_receive(self): """Test sending to a fanout exchange and consuming from 2 queues""" + self.skipTest("kombu memory transport seems buggy with " + "fanout queues as this test passes when " + "you use rabbit (fake_rabbit=False)") conn = self.rpc.create_connection() conn2 = self.rpc.create_connection() message = 'fanout test message' @@ -336,7 +319,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): conn2.close() self.assertEqual(self.received_message, message) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_declare_consumer_errors_will_reconnect(self): # Test that any exception with 'timeout' in it causes a # reconnection @@ -366,7 +348,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(info['called'], 2) self.assertTrue(isinstance(result, self.rpc.DirectConsumer)) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_declare_consumer_ioerrors_will_reconnect(self): """Test that an IOError exception causes a reconnection""" info = _raise_exc_stub(self.stubs, 2, self.rpc.DirectConsumer, @@ -379,7 +360,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(info['called'], 3) self.assertTrue(isinstance(result, self.rpc.DirectConsumer)) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_publishing_errors_will_reconnect(self): # Test that any exception with 'timeout' in it causes a # reconnection when declaring the publisher class and when @@ -427,7 +407,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(info['called'], 2) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_iterconsume_errors_will_reconnect(self): conn = self.rpc.Connection(FLAGS) message = 'reconnect test message' @@ -448,7 +427,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): self.assertEqual(self.received_message, message) # Only called once, because our stub goes away during reconnection - @testutils.skip_if(kombu is None, "Test requires kombu") def test_call_exception(self): """Test that exception gets passed back properly. @@ -476,7 +454,6 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): #Traceback should be included in exception message self.assertTrue('raise NotImplementedError(value)' in unicode(exc)) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_call_converted_exception(self): """Test that exception gets passed back properly. @@ -507,15 +484,10 @@ class RpcKombuTestCase(common.BaseRpcAMQPTestCase): class RpcKombuHATestCase(utils.BaseTestCase): def setUp(self): - utils.BaseTestCase.setUp(self) + super(RpcKombuHATestCase, self).setUp() KombuStubs.setUp(self) + self.addCleanup(FLAGS.reset) - def tearDown(self): - FLAGS.reset() - KombuStubs.tearDown(self) - utils.BaseTestCase.tearDown(self) - - @testutils.skip_if(kombu is None, "Test requires kombu") def test_roundrobin_reconnect(self): """Test that rabbits are tried in roundrobin at connection failures.""" self.config(rabbit_hosts=[ @@ -576,7 +548,6 @@ class RpcKombuHATestCase(utils.BaseTestCase): self.assertEqual(info['attempt'], 5) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_queue_not_declared_ha_if_ha_off(self): self.config(rabbit_ha_queues=False) @@ -591,7 +562,6 @@ class RpcKombuHATestCase(utils.BaseTestCase): with contextlib.closing(self.rpc.create_connection(FLAGS)) as conn: conn.declare_topic_consumer('a_topic', lambda *args: None) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_queue_declared_ha_if_ha_on(self): self.config(rabbit_ha_queues=True) diff --git a/tests/unit/rpc/test_kombu_ssl.py b/tests/unit/rpc/test_kombu_ssl.py index 6d9265b..5507f91 100644 --- a/tests/unit/rpc/test_kombu_ssl.py +++ b/tests/unit/rpc/test_kombu_ssl.py @@ -23,7 +23,6 @@ import eventlet eventlet.monkey_patch() from openstack.common import cfg -from openstack.common import testutils from tests import utils as test_utils @@ -48,6 +47,8 @@ class RpcKombuSslTestCase(test_utils.BaseTestCase): def setUp(self): super(RpcKombuSslTestCase, self).setUp() + if kombu is None: + self.skipTest("Test requires kombu") self.config(kombu_ssl_keyfile=SSL_KEYFILE, kombu_ssl_ca_certs=SSL_CA_CERT, kombu_ssl_certfile=SSL_CERT, @@ -55,7 +56,6 @@ class RpcKombuSslTestCase(test_utils.BaseTestCase): rabbit_use_ssl=True, fake_rabbit=True) - @testutils.skip_if(kombu is None, "Test requires kombu") def test_ssl_on_extended(self): rpc = impl_kombu conn = rpc.create_connection(FLAGS, True) diff --git a/tests/unit/rpc/test_matchmaker.py b/tests/unit/rpc/test_matchmaker.py index 8a48608..ddfb776 100644 --- a/tests/unit/rpc/test_matchmaker.py +++ b/tests/unit/rpc/test_matchmaker.py @@ -15,7 +15,7 @@ # under the License. import logging -import unittest +import testtools from openstack.common.rpc import matchmaker @@ -23,7 +23,7 @@ from openstack.common.rpc import matchmaker LOG = logging.getLogger(__name__) -class _MatchMakerTestCase(unittest.TestCase): +class _MatchMakerTestCase(testtools.TestCase): def test_valid_host_matches(self): queues = self.driver.queues(self.topic) matched_hosts = map(lambda x: x[1], queues) diff --git a/tests/unit/rpc/test_proxy.py b/tests/unit/rpc/test_proxy.py index 393f328..ae05b3f 100644 --- a/tests/unit/rpc/test_proxy.py +++ b/tests/unit/rpc/test_proxy.py @@ -20,23 +20,19 @@ Unit Tests for rpc.proxy import copy import stubout -import unittest +import testtools from openstack.common import context +from openstack.common.fixture import moxstubout from openstack.common import rpc from openstack.common.rpc import proxy -class RpcProxyTestCase(unittest.TestCase): +class RpcProxyTestCase(testtools.TestCase): def setUp(self): - self.stubs = stubout.StubOutForTesting() super(RpcProxyTestCase, self).setUp() - - def tearDown(self): - self.stubs.UnsetAll() - self.stubs.SmartUnsetAll() - super(RpcProxyTestCase, self).tearDown() + self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs def _test_rpc_method(self, rpc_method, has_timeout=False, has_retval=False, server_params=None, supports_topic_override=True): diff --git a/tests/unit/rpc/test_qpid.py b/tests/unit/rpc/test_qpid.py index ad779f3..391d554 100644 --- a/tests/unit/rpc/test_qpid.py +++ b/tests/unit/rpc/test_qpid.py @@ -26,12 +26,12 @@ eventlet.monkey_patch() import logging import mox import stubout -import unittest +import testtools from openstack.common import cfg from openstack.common import context +from openstack.common.fixture import moxstubout from openstack.common.rpc import amqp as rpc_amqp -from openstack.common import testutils try: from openstack.common.rpc import impl_qpid @@ -45,7 +45,7 @@ FLAGS = cfg.CONF LOG = logging.getLogger(__name__) -class RpcQpidTestCase(unittest.TestCase): +class RpcQpidTestCase(testtools.TestCase): """ Exercise the public API of impl_qpid utilizing mox. @@ -65,8 +65,12 @@ class RpcQpidTestCase(unittest.TestCase): def setUp(self): super(RpcQpidTestCase, self).setUp() - self.stubs = stubout.StubOutForTesting() - self.mox = mox.Mox() + if qpid is None: + self.skipTest("Test required qpid") + + mox_fixture = self.useFixture(moxstubout.MoxStubout) + self.stubs = mox_fixture.stubs + self.mox = mox_fixture.mox self.mock_connection = None self.mock_session = None @@ -82,11 +86,9 @@ class RpcQpidTestCase(unittest.TestCase): qpid.messaging.Session = lambda *_x, **_y: self.mock_session qpid.messaging.Sender = lambda *_x, **_y: self.mock_sender qpid.messaging.Receiver = lambda *_x, **_y: self.mock_receiver + self.addCleanup(self._close_qpid) - def tearDown(self): - self.mox.UnsetStubs() - self.stubs.UnsetAll() - self.stubs.SmartUnsetAll() + def _close_qpid(self): if qpid: qpid.messaging.Connection = self.orig_connection qpid.messaging.Session = self.orig_session @@ -97,9 +99,6 @@ class RpcQpidTestCase(unittest.TestCase): # in self._setup_to_server_tests() impl_qpid.Connection.pool.connection_cls = impl_qpid.Connection - super(RpcQpidTestCase, self).tearDown() - - @testutils.skip_if(qpid is None, "Test requires qpid") def test_create_connection(self): self.mock_connection = self.mox.CreateMock(self.orig_connection) self.mock_session = self.mox.CreateMock(self.orig_session) @@ -151,15 +150,12 @@ class RpcQpidTestCase(unittest.TestCase): fanout) connection.close() - @testutils.skip_if(qpid is None, "Test requires qpid") def test_create_consumer(self): self._test_create_consumer(fanout=False) - @testutils.skip_if(qpid is None, "Test requires qpid") def test_create_consumer_fanout(self): self._test_create_consumer(fanout=True) - @testutils.skip_if(qpid is None, "Test requires qpid") def test_create_worker(self): self.mock_connection = self.mox.CreateMock(self.orig_connection) self.mock_session = self.mox.CreateMock(self.orig_session) @@ -188,7 +184,6 @@ class RpcQpidTestCase(unittest.TestCase): ) connection.close() - @testutils.skip_if(qpid is None, "Test requires qpid") def test_topic_consumer(self): self.mock_connection = self.mox.CreateMock(self.orig_connection) self.mock_session = self.mox.CreateMock(self.orig_session) @@ -273,11 +268,9 @@ class RpcQpidTestCase(unittest.TestCase): # that it doesn't mess up other test cases. impl_qpid.Connection.pool.get() - @testutils.skip_if(qpid is None, "Test requires qpid") def test_cast(self): self._test_cast(fanout=False) - @testutils.skip_if(qpid is None, "Test requires qpid") def test_fanout_cast(self): self._test_cast(fanout=True) @@ -296,7 +289,6 @@ class RpcQpidTestCase(unittest.TestCase): MyConnection.pool = rpc_amqp.Pool(FLAGS, MyConnection) self.stubs.Set(impl_qpid, 'Connection', MyConnection) - @testutils.skip_if(qpid is None, "Test requires qpid") def test_cast_to_server(self): server_params = {'username': 'fake_username', 'password': 'fake_password', @@ -305,7 +297,6 @@ class RpcQpidTestCase(unittest.TestCase): self._setup_to_server_tests(server_params) self._test_cast(fanout=False, server_params=server_params) - @testutils.skip_if(qpid is None, "Test requires qpid") def test_fanout_cast_to_server(self): server_params = {'username': 'fake_username', 'password': 'fake_password', @@ -387,11 +378,9 @@ class RpcQpidTestCase(unittest.TestCase): # that it doesn't mess up other test cases. impl_qpid.Connection.pool.get() - @testutils.skip_if(qpid is None, "Test requires qpid") def test_call(self): self._test_call(multi=False) - @testutils.skip_if(qpid is None, "Test requires qpid") def test_multicall(self): self._test_call(multi=True) diff --git a/tests/unit/rpc/test_zmq.py b/tests/unit/rpc/test_zmq.py index 1fb624c..2f0c20d 100644 --- a/tests/unit/rpc/test_zmq.py +++ b/tests/unit/rpc/test_zmq.py @@ -24,12 +24,13 @@ eventlet.monkey_patch() import logging import os +import fixtures + from openstack.common import cfg from openstack.common import exception from openstack.common.gettextutils import _ from openstack.common import processutils from openstack.common import rpc -from openstack.common import testutils from tests.unit.rpc import common try: @@ -47,9 +48,11 @@ class _RpcZmqBaseTestCase(common.BaseRpcTestCase): # TESTCNT needs to be a class var as each run # by subclasses must have a unique identifier TESTCNT = 0 + rpc = impl_zmq - @testutils.skip_if(not impl_zmq, "ZeroMQ library required") def setUp(self, topic='test', topic_nested='nested'): + if not impl_zmq: + self.skipTest("ZeroMQ library required") _RpcZmqBaseTestCase.TESTCNT += 1 testcnt = _RpcZmqBaseTestCase.TESTCNT @@ -69,33 +72,27 @@ class _RpcZmqBaseTestCase(common.BaseRpcTestCase): # increment to avoid async socket # closing/wait delays causing races # between tearDown() and setUp() + # TODO(mordred): replace this with testresources once we're on + # testr self.config(rpc_zmq_port=9500 + testcnt) - internal_ipc_dir = "/tmp/openstack-zmq.ipc.test.%s" % testcnt + internal_ipc_dir = self.useFixture(fixtures.TempDir()).path self.config(rpc_zmq_ipc_dir=internal_ipc_dir) LOG.info(_("Running internal zmq receiver.")) reactor = impl_zmq.ZmqProxy(FLAGS) + self.addCleanup(self._close_reactor) reactor.consume_in_thread() else: LOG.warning(_("Detected zmq-receiver socket.")) LOG.warning(_("Assuming nova-rpc-zmq-receiver is running.")) LOG.warning(_("Using system zmq receiver deamon.")) - super(_RpcZmqBaseTestCase, self).setUp( topic=topic, topic_nested=topic_nested) - @testutils.skip_if(not impl_zmq, "ZeroMQ library required") - def tearDown(self): + def _close_reactor(self): if self.reactor: self.reactor.close() - try: - processutils.execute('rm', '-rf', FLAGS.rpc_zmq_ipc_dir) - except exception.Error: - pass - - super(_RpcZmqBaseTestCase, self).tearDown() - class RpcZmqBaseTopicTestCase(_RpcZmqBaseTestCase): """ diff --git a/tests/unit/scheduler/test_host_filters.py b/tests/unit/scheduler/test_host_filters.py index d855742..999e1c0 100644 --- a/tests/unit/scheduler/test_host_filters.py +++ b/tests/unit/scheduler/test_host_filters.py @@ -16,7 +16,7 @@ Tests For Scheduler Host Filters. """ import stubout -import unittest +import testtools from openstack.common import context from openstack.common import jsonutils @@ -34,7 +34,7 @@ class TestBogusFilter(object): pass -class ExtraSpecsOpsTestCase(unittest.TestCase): +class ExtraSpecsOpsTestCase(testtools.TestCase): def _do_extra_specs_ops_test(self, value, req, matches): assertion = self.assertTrue if matches else self.assertFalse assertion(extra_specs_ops.match(value, req)) @@ -220,7 +220,7 @@ class ExtraSpecsOpsTestCase(unittest.TestCase): matches=False) -class HostFiltersTestCase(unittest.TestCase): +class HostFiltersTestCase(testtools.TestCase): """Test case for host filters.""" def setUp(self): diff --git a/tests/unit/scheduler/test_weights.py b/tests/unit/scheduler/test_weights.py index 478a143..ca61c00 100644 --- a/tests/unit/scheduler/test_weights.py +++ b/tests/unit/scheduler/test_weights.py @@ -16,13 +16,13 @@ Tests For Scheduler weights. """ -import unittest +import testtools from openstack.common.scheduler import weight from tests.unit import fakes -class TestWeightHandler(unittest.TestCase): +class TestWeightHandler(testtools.TestCase): def test_get_all_classes(self): namespace = "openstack.common.tests.fakes.weights" handler = weight.BaseWeightHandler(weight.BaseWeigher, namespace) diff --git a/tests/unit/test_authutils.py b/tests/unit/test_authutils.py index 1e1d26f..64e241a 100644 --- a/tests/unit/test_authutils.py +++ b/tests/unit/test_authutils.py @@ -15,12 +15,12 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools from openstack.common import authutils -class AuthUtilsTest(unittest.TestCase): +class AuthUtilsTest(testtools.TestCase): def test_auth_str_equal(self): self.assertTrue(authutils.auth_str_equal('abc123', 'abc123')) diff --git a/tests/unit/test_cfg.py b/tests/unit/test_cfg.py index 8eaaf67..7e12a03 100644 --- a/tests/unit/test_cfg.py +++ b/tests/unit/test_cfg.py @@ -19,14 +19,16 @@ import shutil import StringIO import sys import tempfile -import unittest +import fixtures import stubout +import testtools from openstack.common.cfg import * +from openstack.common.fixture import moxstubout -class ExceptionsTestCase(unittest.TestCase): +class ExceptionsTestCase(testtools.TestCase): def test_error(self): msg = str(Error('foobar')) @@ -73,7 +75,7 @@ class ExceptionsTestCase(unittest.TestCase): self.assertEquals(msg, 'Failed to parse foo: foobar') -class BaseTestCase(unittest.TestCase): +class BaseTestCase(testtools.TestCase): class TestConfigOpts(ConfigOpts): def __call__(self, args=None): @@ -85,35 +87,27 @@ class BaseTestCase(unittest.TestCase): default_config_files=[]) def setUp(self): + super(BaseTestCase, self).setUp() + self.useFixture(fixtures.NestedTempfile()) self.conf = self.TestConfigOpts() - self.tempfiles = [] self.tempdirs = [] - self.stubs = stubout.StubOutForTesting() - - def tearDown(self): - self.remove_tempfiles() - self.stubs.UnsetAll() + self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs def create_tempfiles(self, files, ext='.conf'): + tempfiles = [] for (basename, contents) in files: if not os.path.isabs(basename): (fd, path) = tempfile.mkstemp(prefix=basename, suffix=ext) else: path = basename + ext fd = os.open(path, os.O_CREAT | os.O_WRONLY) - self.tempfiles.append(path) + tempfiles.append(path) try: os.write(fd, contents) finally: os.close(fd) - return self.tempfiles[-len(files):] - - def remove_tempfiles(self): - for p in self.tempfiles: - os.remove(p) - for d in self.tempdirs: - shutil.rmtree(d, ignore_errors=True) + return tempfiles class UsageTestCase(BaseTestCase): @@ -1428,12 +1422,12 @@ class SadPathTestCase(BaseTestCase): self._do_test_bad_cli_value(FloatOpt) def test_conf_file_not_found(self): - paths = self.create_tempfiles([('test', '')]) - os.remove(paths[0]) - self.tempfiles.remove(paths[0]) + (fd, path) = tempfile.mkstemp() + + os.remove(path) self.assertRaises(ConfigFilesNotFoundError, - self.conf, ['--config-file', paths[0]]) + self.conf, ['--config-file', path]) def test_conf_file_broken(self): paths = self.create_tempfiles([('test', 'foo')]) @@ -1573,7 +1567,7 @@ class OptDumpingTestCase(BaseTestCase): ]) -class ConfigParserTestCase(unittest.TestCase): +class ConfigParserTestCase(testtools.TestCase): def test_no_section(self): with tempfile.NamedTemporaryFile() as tmpfile: tmpfile.write('foo = bar') diff --git a/tests/unit/test_cliutils.py b/tests/unit/test_cliutils.py index 49339a0..c9ab0f5 100644 --- a/tests/unit/test_cliutils.py +++ b/tests/unit/test_cliutils.py @@ -14,12 +14,12 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools from openstack.common.cliutils import * -class ValidateArgsTest(unittest.TestCase): +class ValidateArgsTest(testtools.TestCase): def test_lambda_no_args(self): validate_args(lambda: None) diff --git a/tests/unit/test_context.py b/tests/unit/test_context.py index e946dc7..3437475 100644 --- a/tests/unit/test_context.py +++ b/tests/unit/test_context.py @@ -15,12 +15,12 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools from openstack.common import context -class ContextTest(unittest.TestCase): +class ContextTest(testtools.TestCase): def test_context(self): ctx = context.RequestContext() diff --git a/tests/unit/test_exception.py b/tests/unit/test_exception.py index c683da0..ecfadb6 100644 --- a/tests/unit/test_exception.py +++ b/tests/unit/test_exception.py @@ -15,7 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools from openstack.common import exception @@ -32,7 +32,7 @@ def bad_function_exception(): raise Exception() -class WrapExceptionTest(unittest.TestCase): +class WrapExceptionTest(testtools.TestCase): def test_wrap_exception_good_return(self): wrapped = exception.wrap_exception @@ -47,7 +47,7 @@ class WrapExceptionTest(unittest.TestCase): self.assertRaises(Exception, wrapped(bad_function_exception)) -class ApiErrorTest(unittest.TestCase): +class ApiErrorTest(testtools.TestCase): def test_without_code(self): err = exception.ApiError('fake error') @@ -62,7 +62,7 @@ class ApiErrorTest(unittest.TestCase): self.assertEqual(err.message, 'fake error') -class BadStoreUriTest(unittest.TestCase): +class BadStoreUriTest(testtools.TestCase): def test(self): uri = 'http:///etc/passwd' @@ -72,7 +72,7 @@ class BadStoreUriTest(unittest.TestCase): self.assertTrue(reason in str(err.message)) -class UnknownSchemeTest(unittest.TestCase): +class UnknownSchemeTest(testtools.TestCase): def test(self): scheme = 'http' @@ -80,7 +80,7 @@ class UnknownSchemeTest(unittest.TestCase): self.assertTrue(scheme in str(err.message)) -class OpenstackExceptionTest(unittest.TestCase): +class OpenstackExceptionTest(testtools.TestCase): class TestException(exception.OpenstackException): message = '%(test)s' diff --git a/tests/unit/test_excutils.py b/tests/unit/test_excutils.py index 0b4093b..35ce5be 100644 --- a/tests/unit/test_excutils.py +++ b/tests/unit/test_excutils.py @@ -14,12 +14,12 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools from openstack.common import excutils -class SaveAndReraiseTest(unittest.TestCase): +class SaveAndReraiseTest(testtools.TestCase): def test_save_and_reraise_exception(self): e = None diff --git a/tests/unit/test_fileutils.py b/tests/unit/test_fileutils.py index de5719e..1f8ccd6 100644 --- a/tests/unit/test_fileutils.py +++ b/tests/unit/test_fileutils.py @@ -15,7 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools import os import shutil @@ -24,7 +24,7 @@ import tempfile from openstack.common import fileutils -class EnsureTree(unittest.TestCase): +class EnsureTree(testtools.TestCase): def test_ensure_tree(self): tmpdir = tempfile.mkdtemp() try: diff --git a/tests/unit/test_gettext.py b/tests/unit/test_gettext.py index 73ecbf7..ddaca16 100644 --- a/tests/unit/test_gettext.py +++ b/tests/unit/test_gettext.py @@ -16,7 +16,7 @@ # under the License. import logging -import unittest +import testtools from openstack.common.gettextutils import _ @@ -24,7 +24,7 @@ from openstack.common.gettextutils import _ LOG = logging.getLogger(__name__) -class GettextTest(unittest.TestCase): +class GettextTest(testtools.TestCase): def test_gettext_does_not_blow_up(self): LOG.info(_('test')) diff --git a/tests/unit/test_importutils.py b/tests/unit/test_importutils.py index 3544fe4..4fb894c 100644 --- a/tests/unit/test_importutils.py +++ b/tests/unit/test_importutils.py @@ -17,12 +17,12 @@ import datetime import sys -import unittest +import testtools from openstack.common import importutils -class ImportUtilsTest(unittest.TestCase): +class ImportUtilsTest(testtools.TestCase): # NOTE(jkoelker) There has GOT to be a way to test this. But mocking # __import__ is the devil. Right now we just make diff --git a/tests/unit/test_iniparser.py b/tests/unit/test_iniparser.py index 9e119e7..6742b19 100644 --- a/tests/unit/test_iniparser.py +++ b/tests/unit/test_iniparser.py @@ -14,7 +14,7 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools from openstack.common import iniparser @@ -38,8 +38,9 @@ class TestParser(iniparser.BaseParser): self.comment_called = True -class BaseParserTestCase(unittest.TestCase): +class BaseParserTestCase(testtools.TestCase): def setUp(self): + super(BaseParserTestCase, self).setUp() self.parser = iniparser.BaseParser() def _assertParseError(self, *lines): @@ -61,8 +62,9 @@ class BaseParserTestCase(unittest.TestCase): self._assertParseError("[]") -class ParserTestCase(unittest.TestCase): +class ParserTestCase(testtools.TestCase): def setUp(self): + super(ParserTestCase, self).setUp() self.parser = TestParser() def test_blank_line(self): @@ -120,7 +122,7 @@ class ParserTestCase(unittest.TestCase): self.assertEquals(self.parser.values, {'': {'foo': [' bar ']}}) -class ExceptionTestCase(unittest.TestCase): +class ExceptionTestCase(testtools.TestCase): def test_parseerror(self): exc = iniparser.ParseError('test', 42, 'example') self.assertEquals(str(exc), "at line 42, test: 'example'") diff --git a/tests/unit/test_jsonutils.py b/tests/unit/test_jsonutils.py index cc8d26a..eebbfb8 100644 --- a/tests/unit/test_jsonutils.py +++ b/tests/unit/test_jsonutils.py @@ -17,13 +17,13 @@ import datetime import StringIO -import unittest +import testtools import xmlrpclib from openstack.common import jsonutils -class JSONUtilsTestCase(unittest.TestCase): +class JSONUtilsTestCase(testtools.TestCase): def test_dumps(self): self.assertEqual(jsonutils.dumps({'a': 'b'}), '{"a": "b"}') @@ -36,7 +36,7 @@ class JSONUtilsTestCase(unittest.TestCase): self.assertEqual(jsonutils.load(x), {'a': 'b'}) -class ToPrimitiveTestCase(unittest.TestCase): +class ToPrimitiveTestCase(testtools.TestCase): def test_list(self): self.assertEquals(jsonutils.to_primitive([1, 2, 3]), [1, 2, 3]) diff --git a/tests/unit/test_local.py b/tests/unit/test_local.py index 08e77af..7031e6f 100644 --- a/tests/unit/test_local.py +++ b/tests/unit/test_local.py @@ -16,7 +16,7 @@ # under the License. import eventlet -import unittest +import testtools from openstack.common import local @@ -26,7 +26,7 @@ class Dict(dict): pass -class LocalStoreTestCase(unittest.TestCase): +class LocalStoreTestCase(testtools.TestCase): v1 = Dict(a='1') v2 = Dict(a='2') v3 = Dict(a='3') diff --git a/tests/unit/test_lockutils.py b/tests/unit/test_lockutils.py index 85dce05..dc8e413 100644 --- a/tests/unit/test_lockutils.py +++ b/tests/unit/test_lockutils.py @@ -21,14 +21,13 @@ import select import shutil import tempfile import time -import unittest +import testtools import eventlet from eventlet import greenpool from eventlet import greenthread from openstack.common import lockutils -from openstack.common import testutils from tests import utils as test_utils diff --git a/tests/unit/test_log.py b/tests/unit/test_log.py index 451fb4f..3ea5943 100644 --- a/tests/unit/test_log.py +++ b/tests/unit/test_log.py @@ -201,13 +201,10 @@ class LegacyFormatterTestCase(test_utils.BaseTestCase): self.handler = logging.StreamHandler(self.stream) self.handler.setFormatter(log.LegacyFormatter()) self.log.logger.addHandler(self.handler) + self.addCleanup(self.log.logger.removeHandler, self.handler) self.level = self.log.logger.getEffectiveLevel() self.log.logger.setLevel(logging.DEBUG) - - def tearDown(self): - self.log.logger.setLevel(self.level) - self.log.logger.removeHandler(self.handler) - super(LegacyFormatterTestCase, self).tearDown() + self.addCleanup(self.log.logger.setLevel, self.level) def test_uncontextualized_log(self): self.log.info("foo") diff --git a/tests/unit/test_loopingcall.py b/tests/unit/test_loopingcall.py index 8307a11..0407668 100644 --- a/tests/unit/test_loopingcall.py +++ b/tests/unit/test_loopingcall.py @@ -15,7 +15,7 @@ # under the License. import datetime -import unittest +import testtools from eventlet import greenthread import mox @@ -24,9 +24,10 @@ from openstack.common import loopingcall from openstack.common import timeutils -class LoopingCallTestCase(unittest.TestCase): +class LoopingCallTestCase(testtools.TestCase): def setUp(self): + super(LoopingCallTestCase, self).setUp() self.num_runs = 0 def test_return_true(self): diff --git a/tests/unit/test_network_utils.py b/tests/unit/test_network_utils.py index 2641d2d..b5b649a 100644 --- a/tests/unit/test_network_utils.py +++ b/tests/unit/test_network_utils.py @@ -15,14 +15,14 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools import mock from openstack.common import network_utils as utils -class NetworkUtilsTest(unittest.TestCase): +class NetworkUtilsTest(testtools.TestCase): def test_parse_host_port(self): self.assertEqual(('server01', 80), diff --git a/tests/unit/test_notifier.py b/tests/unit/test_notifier.py index 1783d06..a777fe8 100644 --- a/tests/unit/test_notifier.py +++ b/tests/unit/test_notifier.py @@ -37,10 +37,7 @@ class NotifierTestCase(test_utils.BaseTestCase): ] self.config(notification_driver=notification_driver) self.config(default_publisher_id='publisher') - - def tearDown(self): - notifier_api._reset_drivers() - super(NotifierTestCase, self).tearDown() + self.addCleanup(notifier_api._reset_drivers) def test_send_notification(self): self.notify_called = False @@ -241,11 +238,7 @@ class MultiNotifierTestCase(test_utils.BaseTestCase): raise RuntimeError("Bad notifier.") self.stubs.Set(log_notifier, 'notify', mock_notify2) - notifier_api._reset_drivers() - - def tearDown(self): - notifier_api._reset_drivers() - super(MultiNotifierTestCase, self).tearDown() + self.addCleanup(notifier_api._reset_drivers) def test_send_notifications_successfully(self): notification_driver = [ diff --git a/tests/unit/test_pastedeploy.py b/tests/unit/test_pastedeploy.py index 9746fe5..817eb47 100644 --- a/tests/unit/test_pastedeploy.py +++ b/tests/unit/test_pastedeploy.py @@ -16,7 +16,9 @@ import os import tempfile -import unittest + +import fixtures +import testtools from openstack.common import pastedeploy @@ -41,27 +43,20 @@ class Filter(object): self.data = data -class PasteTestCase(unittest.TestCase): +class PasteTestCase(testtools.TestCase): def setUp(self): - self.tempfiles = [] - - def tearDown(self): - self.remove_tempfiles() + super(PasteTestCase, self).setUp() + self.useFixture(fixtures.NestedTempfile()) def create_tempfile(self, contents): (fd, path) = tempfile.mkstemp() - self.tempfiles.append(path) try: os.write(fd, contents) finally: os.close(fd) return path - def remove_tempfiles(self): - for p in self.tempfiles: - os.remove(p) - def test_app_factory(self): data = 'test_app_factory' diff --git a/tests/unit/test_plugin.py b/tests/unit/test_plugin.py index b68d6f5..efebead 100644 --- a/tests/unit/test_plugin.py +++ b/tests/unit/test_plugin.py @@ -14,7 +14,7 @@ # under the License. import pkg_resources -import unittest +import testtools from openstack.common import cfg from openstack.common.notifier import api as notifier_api @@ -33,9 +33,6 @@ class SimpleNotifier(object): class ManagerTestCase(test_utils.BaseTestCase): - def tearDown(self): - super(ManagerTestCase, self).tearDown() - def test_constructs(self): manager1 = pluginmanager.PluginManager("testproject", "testservice") self.assertNotEqual(manager1, False) @@ -43,12 +40,6 @@ class ManagerTestCase(test_utils.BaseTestCase): class NotifyTestCase(test_utils.BaseTestCase): """Test case for the plugin notification interface""" - def setUp(self): - super(NotifyTestCase, self).setUp() - - def tearDown(self): - super(NotifyTestCase, self).tearDown() - notifier_api._reset_drivers() def test_add_notifier(self): notifier1 = SimpleNotifier() @@ -111,9 +102,6 @@ class MockExtManager(): class APITestCase(test_utils.BaseTestCase): """Test case for the plugin api extension interface""" - def tearDown(self): - super(APITestCase, self).tearDown() - def test_add_extension(self): def mock_load(_s): return TestPluginClass() diff --git a/tests/unit/test_policy.py b/tests/unit/test_policy.py index 684a113..2ffa7f8 100644 --- a/tests/unit/test_policy.py +++ b/tests/unit/test_policy.py @@ -19,7 +19,7 @@ import os.path import StringIO -import unittest +import testtools import urllib import mock @@ -35,7 +35,7 @@ class TestException(Exception): self.kwargs = kwargs -class RulesTestCase(unittest.TestCase): +class RulesTestCase(testtools.TestCase): def test_init_basic(self): rules = policy.Rules() @@ -105,10 +105,12 @@ class RulesTestCase(unittest.TestCase): self.assertEqual(str(rules), exemplar) -class PolicySetAndResetTestCase(unittest.TestCase): - def tearDown(self): +class PolicySetAndResetTestCase(testtools.TestCase): + + def setUp(self): + super(PolicySetAndResetTestCase, self).setUp() # Make sure the policy rules are reset for remaining tests - policy._rules = None + self.addCleanup(setattr, policy, '_rules', None) def test_set_rules(self): # Make sure the rules are set properly @@ -136,10 +138,12 @@ class FakeCheck(policy.BaseCheck): return (target, creds) -class CheckFunctionTestCase(unittest.TestCase): - def tearDown(self): +class CheckFunctionTestCase(testtools.TestCase): + + def setUp(self): + super(CheckFunctionTestCase, self).setUp() # Make sure the policy rules are reset for remaining tests - policy._rules = None + self.addCleanup(setattr, policy, '_rules', None) def test_check_explicit(self): policy._rules = None @@ -181,7 +185,7 @@ class CheckFunctionTestCase(unittest.TestCase): self.fail("policy.check() failed to raise requested exception") -class FalseCheckTestCase(unittest.TestCase): +class FalseCheckTestCase(testtools.TestCase): def test_str(self): check = policy.FalseCheck() @@ -193,7 +197,7 @@ class FalseCheckTestCase(unittest.TestCase): self.assertEqual(check('target', 'creds'), False) -class TrueCheckTestCase(unittest.TestCase): +class TrueCheckTestCase(testtools.TestCase): def test_str(self): check = policy.TrueCheck() @@ -210,7 +214,7 @@ class CheckForTest(policy.Check): pass -class CheckTestCase(unittest.TestCase): +class CheckTestCase(testtools.TestCase): def test_init(self): check = CheckForTest('kind', 'match') @@ -223,7 +227,7 @@ class CheckTestCase(unittest.TestCase): self.assertEqual(str(check), 'kind:match') -class NotCheckTestCase(unittest.TestCase): +class NotCheckTestCase(testtools.TestCase): def test_init(self): check = policy.NotCheck('rule') @@ -249,7 +253,7 @@ class NotCheckTestCase(unittest.TestCase): rule.assert_called_once_with('target', 'cred') -class OrCheckTestCase(unittest.TestCase): +class OrCheckTestCase(testtools.TestCase): def test_init(self): check = policy.OrCheck(['rule1', 'rule2']) @@ -291,7 +295,7 @@ class OrCheckTestCase(unittest.TestCase): rules[1].assert_called_once_with('target', 'cred') -class ParseCheckTestCase(unittest.TestCase): +class ParseCheckTestCase(testtools.TestCase): def test_false(self): result = policy._parse_check('!') @@ -334,7 +338,7 @@ class ParseCheckTestCase(unittest.TestCase): policy._checks[None].assert_called_once_with('spam', 'handler') -class ParseListRuleTestCase(unittest.TestCase): +class ParseListRuleTestCase(testtools.TestCase): def test_empty(self): result = policy._parse_list_rule([]) @@ -404,7 +408,7 @@ class ParseListRuleTestCase(unittest.TestCase): '((rule1 and rule2) or (rule3 and rule4))') -class ParseTokenizeTestCase(unittest.TestCase): +class ParseTokenizeTestCase(testtools.TestCase): @mock.patch.object(policy, '_parse_check', lambda x: x) def test_tokenize(self): exemplar = ("(( ( ((() And)) or ) (check:%(miss)s) not)) " @@ -424,7 +428,7 @@ class ParseTokenizeTestCase(unittest.TestCase): self.assertEqual(result, expected) -class ParseStateMetaTestCase(unittest.TestCase): +class ParseStateMetaTestCase(testtools.TestCase): def test_reducer(self): @policy.reducer('a', 'b', 'c') @policy.reducer('d', 'e', 'f') @@ -458,7 +462,7 @@ class ParseStateMetaTestCase(unittest.TestCase): self.fail("Unrecognized reducer discovered") -class ParseStateTestCase(unittest.TestCase): +class ParseStateTestCase(testtools.TestCase): def test_init(self): state = policy.ParseState() @@ -623,7 +627,7 @@ class ParseStateTestCase(unittest.TestCase): self.assertEqual(result, [('check', 'not check')]) -class ParseTextRuleTestCase(unittest.TestCase): +class ParseTextRuleTestCase(testtools.TestCase): def test_empty(self): result = policy._parse_text_rule('') @@ -649,7 +653,7 @@ class ParseTextRuleTestCase(unittest.TestCase): mock_parse_tokenize.assert_called_once_with('test rule') -class ParseRuleTestCase(unittest.TestCase): +class ParseRuleTestCase(testtools.TestCase): @mock.patch.object(policy, '_parse_text_rule', return_value='text rule') @mock.patch.object(policy, '_parse_list_rule', return_value='list rule') def test_parse_rule_string(self, mock_parse_list_rule, @@ -670,7 +674,7 @@ class ParseRuleTestCase(unittest.TestCase): mock_parse_list_rule.assert_called_once_with([['a'], ['list']]) -class CheckRegisterTestCase(unittest.TestCase): +class CheckRegisterTestCase(testtools.TestCase): @mock.patch.object(policy, '_checks', {}) def test_register_check(self): class TestCheck(policy.Check): @@ -689,7 +693,7 @@ class CheckRegisterTestCase(unittest.TestCase): self.assertEqual(policy._checks, dict(spam=TestCheck)) -class RuleCheckTestCase(unittest.TestCase): +class RuleCheckTestCase(testtools.TestCase): @mock.patch.object(policy, '_rules', {}) def test_rule_missing(self): check = policy.RuleCheck('rule', 'spam') @@ -713,7 +717,7 @@ class RuleCheckTestCase(unittest.TestCase): policy._rules['spam'].assert_called_once_with('target', 'creds') -class RoleCheckTestCase(unittest.TestCase): +class RoleCheckTestCase(testtools.TestCase): def test_accept(self): check = policy.RoleCheck('role', 'sPaM') @@ -725,7 +729,7 @@ class RoleCheckTestCase(unittest.TestCase): self.assertEqual(check('target', dict(roles=[])), False) -class HttpCheckTestCase(unittest.TestCase): +class HttpCheckTestCase(testtools.TestCase): def decode_post_data(self, post_data): result = {} for item in post_data.split('&'): @@ -771,7 +775,7 @@ class HttpCheckTestCase(unittest.TestCase): )) -class GenericCheckTestCase(unittest.TestCase): +class GenericCheckTestCase(testtools.TestCase): def test_no_cred(self): check = policy.GenericCheck('name', '%(name)s') diff --git a/tests/unit/test_processutils.py b/tests/unit/test_processutils.py index ffe1232..a140aaa 100644 --- a/tests/unit/test_processutils.py +++ b/tests/unit/test_processutils.py @@ -15,14 +15,14 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools import mock from openstack.common import processutils -class UtilsTest(unittest.TestCase): +class UtilsTest(testtools.TestCase): # NOTE(jkoelker) Moar tests from nova need to be ported. But they # need to be mock'd out. Currently they requre actually # running code. @@ -32,7 +32,7 @@ class UtilsTest(unittest.TestCase): hozer=True) -class ProcessExecutionErrorTest(unittest.TestCase): +class ProcessExecutionErrorTest(testtools.TestCase): def test_defaults(self): err = processutils.ProcessExecutionError() diff --git a/tests/unit/test_rootwrap.py b/tests/unit/test_rootwrap.py index 2391005..30708d3 100644 --- a/tests/unit/test_rootwrap.py +++ b/tests/unit/test_rootwrap.py @@ -20,13 +20,13 @@ import logging.handlers import os import stubout import subprocess -import unittest +import testtools from openstack.common.rootwrap import filters from openstack.common.rootwrap import wrapper -class RootwrapTestCase(unittest.TestCase): +class RootwrapTestCase(testtools.TestCase): def setUp(self): super(RootwrapTestCase, self).setUp() diff --git a/tests/unit/test_service.py b/tests/unit/test_service.py index c7455e0..824e553 100644 --- a/tests/unit/test_service.py +++ b/tests/unit/test_service.py @@ -121,10 +121,11 @@ class ServiceLauncherTest(utils.BaseTestCase): CONF.unregister_opts(notifier_api.notifier_opts) # NOTE(markmc): ConfigOpts.log_opt_values() uses CONF.config-file CONF(args=[], default_config_files=[]) + self.addCleanup(CONF.reset) + self.addCleanup(CONF.register_opts, notifier_api.notifier_opts) + self.addCleanup(self._reap_pid) - def tearDown(self): - CONF.reset() - CONF.register_opts(notifier_api.notifier_opts) + def _reap_pid(self): if self.pid: # Make sure all processes are stopped os.kill(self.pid, signal.SIGTERM) @@ -132,8 +133,6 @@ class ServiceLauncherTest(utils.BaseTestCase): # Make sure we reap our test process self._reap_test() - super(ServiceLauncherTest, self).tearDown() - def _reap_test(self): pid, status = os.waitpid(self.pid, 0) self.pid = None diff --git a/tests/unit/test_setup.py b/tests/unit/test_setup.py index 74ade5c..0632823 100644 --- a/tests/unit/test_setup.py +++ b/tests/unit/test_setup.py @@ -18,12 +18,14 @@ import os import sys from tempfile import mkstemp -import unittest + +import fixtures +import testtools from openstack.common.setup import * -class EmailTestCase(unittest.TestCase): +class EmailTestCase(testtools.TestCase): def test_str_dict_replace(self): string = 'Johnnie T. Hozer' @@ -32,15 +34,13 @@ class EmailTestCase(unittest.TestCase): canonicalize_emails(string, mapping)) -class MailmapTestCase(unittest.TestCase): +class MailmapTestCase(testtools.TestCase): def setUp(self): + super(MailmapTestCase, self).setUp() + self.useFixture(fixtures.NestedTempfile()) (fd, self.mailmap) = mkstemp(prefix='openstack', suffix='.setup') - def tearDown(self): - if os.path.exists(self.mailmap): - os.remove(self.mailmap) - def test_mailmap_with_fullname(self): with open(self.mailmap, 'w') as mm_fh: mm_fh.write("Foo Bar Foo Bar \n") @@ -60,15 +60,13 @@ class MailmapTestCase(unittest.TestCase): parse_mailmap(self.mailmap)) -class ParseRequirementsTest(unittest.TestCase): +class ParseRequirementsTest(testtools.TestCase): def setUp(self): + super(ParseRequirementsTest, self).setUp() + self.useFixture(fixtures.NestedTempfile()) (fd, self.tmp_file) = mkstemp(prefix='openstack', suffix='.setup') - def tearDown(self): - if os.path.exists(self.tmp_file): - os.remove(self.tmp_file) - def test_parse_requirements_normal(self): with open(self.tmp_file, 'w') as fh: fh.write("foo\nbar") diff --git a/tests/unit/test_strutils.py b/tests/unit/test_strutils.py index 0eb5f5e..88ab9c1 100644 --- a/tests/unit/test_strutils.py +++ b/tests/unit/test_strutils.py @@ -15,7 +15,7 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools import mock @@ -23,7 +23,7 @@ from openstack.common import exception from openstack.common import strutils -class StrUtilsTest(unittest.TestCase): +class StrUtilsTest(testtools.TestCase): def test_bool_bool_from_string(self): self.assertTrue(strutils.bool_from_string(True)) diff --git a/tests/unit/test_testutils.py b/tests/unit/test_testutils.py deleted file mode 100644 index b3088ee..0000000 --- a/tests/unit/test_testutils.py +++ /dev/null @@ -1,43 +0,0 @@ -# vim: tabstop=4 shiftwidth=4 softtabstop=4 - -# Copyright 2012 Red Hat, 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. - -import unittest - -from openstack.common import testutils - - -class TestUtilsTestCase(unittest.TestCase): - - @testutils.skip_test('test should be skipped') - def test_skip_test(self): - raise Exception('should have been skipped') - - @testutils.skip_if(True, 'test should be skipped') - def test_skip_if_true(self): - raise Exception('should have been skipped') - - @testutils.skip_if(False, 'test should not be skipped') - def test_skip_if_false(self): - pass - - @testutils.skip_unless(True, 'test should not be skipped') - def test_skip_unless_true(self): - pass - - @testutils.skip_unless(False, 'test should be skipped') - def test_skip_unless_false(self): - raise Exception('should have been skipped') diff --git a/tests/unit/test_timeutils.py b/tests/unit/test_timeutils.py index 1407f29..0c3c7b4 100644 --- a/tests/unit/test_timeutils.py +++ b/tests/unit/test_timeutils.py @@ -16,17 +16,18 @@ # under the License. import datetime -import unittest import iso8601 import mock +import testtools from openstack.common import timeutils -class TimeUtilsTest(unittest.TestCase): +class TimeUtilsTest(testtools.TestCase): def setUp(self): + super(TimeUtilsTest, self).setUp() self.skynet_self_aware_time_str = '1997-08-29T06:14:00Z' self.skynet_self_aware_time = datetime.datetime(1997, 8, 29, 6, 14, 0) self.one_minute_before = datetime.datetime(1997, 8, 29, 6, 13, 0) @@ -34,9 +35,7 @@ class TimeUtilsTest(unittest.TestCase): self.skynet_self_aware_time_perfect_str = '1997-08-29T06:14:00.000000' self.skynet_self_aware_time_perfect = datetime.datetime(1997, 8, 29, 6, 14, 0) - - def tearDown(self): - timeutils.clear_time_override() + self.addCleanup(timeutils.clear_time_override) def test_isotime(self): with mock.patch('datetime.datetime') as datetime_mock: @@ -149,7 +148,7 @@ class TimeUtilsTest(unittest.TestCase): timeutils.delta_seconds(before, after)) -class TestIso8601Time(unittest.TestCase): +class TestIso8601Time(testtools.TestCase): def _instaneous(self, timestamp, yr, mon, day, hr, min, sec, micro): self.assertEquals(timestamp.year, yr) diff --git a/tests/unit/test_uuidutils.py b/tests/unit/test_uuidutils.py index bcf2c3d..088f4b0 100644 --- a/tests/unit/test_uuidutils.py +++ b/tests/unit/test_uuidutils.py @@ -15,13 +15,13 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest +import testtools import uuid from openstack.common import uuidutils -class UUIDUtilsTest(unittest.TestCase): +class UUIDUtilsTest(testtools.TestCase): def test_generate_uuid(self): uuid_string = uuidutils.generate_uuid() diff --git a/tests/unit/test_version.py b/tests/unit/test_version.py index 21ee094..3b2f3db 100644 --- a/tests/unit/test_version.py +++ b/tests/unit/test_version.py @@ -20,7 +20,7 @@ import shutil import StringIO import sys import tempfile -import unittest +import testtools import stubout @@ -28,13 +28,12 @@ from openstack.common.cfg import * from openstack.common import version -class BaseTestCase(unittest.TestCase): +class BaseTestCase(testtools.TestCase): def setUp(self): + super(BaseTestCase, self).setUp() self.stubs = stubout.StubOutForTesting() - - def tearDown(self): - self.stubs.UnsetAll() + self.addCleanup(self.stubs.UnsetAll) class DeferredVersionTestCase(BaseTestCase): diff --git a/tests/unit/test_wsgi.py b/tests/unit/test_wsgi.py index c621a8c..f40fba5 100644 --- a/tests/unit/test_wsgi.py +++ b/tests/unit/test_wsgi.py @@ -15,16 +15,15 @@ # License for the specific language governing permissions and limitations # under the License. -import unittest -import webob - import mock +import testtools +import webob from openstack.common import exception from openstack.common import wsgi -class RequestTest(unittest.TestCase): +class RequestTest(testtools.TestCase): def test_content_type_missing(self): request = wsgi.Request.blank('/tests/123', method='POST') @@ -105,7 +104,7 @@ class RequestTest(unittest.TestCase): self.assertEqual(result, "application/new_type") -class ActionDispatcherTest(unittest.TestCase): +class ActionDispatcherTest(testtools.TestCase): def test_dispatch(self): serializer = wsgi.ActionDispatcher() @@ -128,7 +127,7 @@ class ActionDispatcherTest(unittest.TestCase): 'Two trousers') -class ResponseHeadersSerializerTest(unittest.TestCase): +class ResponseHeadersSerializerTest(testtools.TestCase): def test_default(self): serializer = wsgi.ResponseHeadersSerializer() @@ -148,14 +147,14 @@ class ResponseHeadersSerializerTest(unittest.TestCase): self.assertEqual(response.headers['X-Custom-Header'], '123') -class DictSerializerTest(unittest.TestCase): +class DictSerializerTest(testtools.TestCase): def test_dispatch_default(self): serializer = wsgi.DictSerializer() self.assertEqual(serializer.serialize({}, 'NonExistantAction'), '') -class XMLDictSerializerTest(unittest.TestCase): +class XMLDictSerializerTest(testtools.TestCase): def test_xml(self): input_dict = dict(servers=dict(a=(2, 3))) @@ -169,7 +168,7 @@ class XMLDictSerializerTest(unittest.TestCase): self.assertEqual(result, expected_xml) -class JSONDictSerializerTest(unittest.TestCase): +class JSONDictSerializerTest(testtools.TestCase): def test_json(self): input_dict = dict(servers=dict(a=(2, 3))) @@ -191,14 +190,14 @@ class JSONDictSerializerTest(unittest.TestCase): self.assertEqual(result, expected_str) -class TextDeserializerTest(unittest.TestCase): +class TextDeserializerTest(testtools.TestCase): def test_dispatch_default(self): deserializer = wsgi.TextDeserializer() self.assertEqual(deserializer.deserialize({}, 'update'), {}) -class JSONDeserializerTest(unittest.TestCase): +class JSONDeserializerTest(testtools.TestCase): def test_json(self): data = """{"a": { @@ -222,7 +221,7 @@ class JSONDeserializerTest(unittest.TestCase): self.assertEqual(deserializer.deserialize(data), as_dict) -class XMLDeserializerTest(unittest.TestCase): +class XMLDeserializerTest(testtools.TestCase): def test_xml(self): xml = """ @@ -254,7 +253,7 @@ class XMLDeserializerTest(unittest.TestCase): self.assertEqual(deserializer.deserialize(xml), as_dict) -class RequestHeadersDeserializerTest(unittest.TestCase): +class RequestHeadersDeserializerTest(testtools.TestCase): def test_default(self): deserializer = wsgi.RequestHeadersDeserializer() @@ -271,9 +270,11 @@ class RequestHeadersDeserializerTest(unittest.TestCase): self.assertEqual(deserializer.deserialize(req, 'update'), {'a': 'b'}) -class ResponseSerializerTest(unittest.TestCase): +class ResponseSerializerTest(testtools.TestCase): def setUp(self): + super(ResponseSerializerTest, self).setUp() + class JSONSerializer(object): def serialize(self, data, action='default'): return 'pew_json' @@ -294,9 +295,6 @@ class ResponseSerializerTest(unittest.TestCase): self.serializer = wsgi.ResponseSerializer(self.body_serializers, HeadersSerializer()) - def tearDown(self): - pass - def test_get_serializer(self): ctype = 'application/json' self.assertEqual(self.serializer.get_body_serializer(ctype), @@ -332,9 +330,11 @@ class ResponseSerializerTest(unittest.TestCase): {}, 'application/unknown') -class RequestDeserializerTest(unittest.TestCase): +class RequestDeserializerTest(testtools.TestCase): def setUp(self): + super(RequestDeserializerTest, self).setUp() + class JSONDeserializer(object): def deserialize(self, data, action='default'): return 'pew_json' @@ -399,7 +399,7 @@ class RequestDeserializerTest(unittest.TestCase): self.assertEqual(expected, deserialized) -class ResourceTest(unittest.TestCase): +class ResourceTest(testtools.TestCase): def test_dispatch(self): class Controller(object): @@ -439,7 +439,7 @@ class ResourceTest(unittest.TestCase): self.assertEqual(response.status, '415 Unsupported Media Type') -class ServerTest(unittest.TestCase): +class ServerTest(testtools.TestCase): def test_run_server(self): listen_patcher = mock.patch('eventlet.listen') @@ -457,7 +457,7 @@ class ServerTest(unittest.TestCase): server_patcher.stop() -class WSGIServerTest(unittest.TestCase): +class WSGIServerTest(testtools.TestCase): def test_pool(self): server = wsgi.Service('fake', 9000) diff --git a/tests/utils.py b/tests/utils.py index 883e5f6..2cbcd5b 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -19,24 +19,20 @@ import stubout import subprocess -import unittest +import testtools from openstack.common import cfg +from openstack.common.fixture import moxstubout CONF = cfg.CONF -class BaseTestCase(unittest.TestCase): +class BaseTestCase(testtools.TestCase): def setUp(self): super(BaseTestCase, self).setUp() - self.stubs = stubout.StubOutForTesting() - - def tearDown(self): - super(BaseTestCase, self).tearDown() - CONF.reset() - self.stubs.UnsetAll() - self.stubs.SmartUnsetAll() + self.stubs = self.useFixture(moxstubout.MoxStubout()).stubs + self.addCleanup(CONF.reset) def config(self, **kw): """ -- cgit