summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSean Dague <sean@dague.net>2014-12-09 08:35:14 -0500
committerSean Dague <sean@dague.net>2014-12-09 14:05:45 -0500
commitf96ec4411ce89606cf52211061003c14306dcfa1 (patch)
treebd6fb460881eea14be7f5d3a3ec327876883b4cd
parentee718d226570feeff722b1d3ea3cd19784252270 (diff)
downloadnova-f96ec4411ce89606cf52211061003c14306dcfa1.tar.gz
extract fixtures from nova.test to nova.test.fixtures
Start extracting all the setup code in note.test into fixtures which will let us decompose test setup (and have test base classes that don't setup everything). This creates new OutputStreamCapture fixture and StandardLogging fixture and unit tests for both of them plus tests for the exiting Conf fixture. H305/306 have to be turned off because hacking import rules are broken and continue to believe that fixtures is a nova module not the absolute one. Change-Id: I97fdacdf5a6ad2957b0efa1e21ae084d4eb04ab9
-rw-r--r--nova/test.py63
-rw-r--r--nova/tests/fixtures.py130
-rw-r--r--nova/tests/unit/test_fixtures.py126
-rw-r--r--tox.ini3
4 files changed, 262 insertions, 60 deletions
diff --git a/nova/test.py b/nova/test.py
index 7db4847f79..b040c82f5d 100644
--- a/nova/test.py
+++ b/nova/test.py
@@ -55,6 +55,7 @@ from nova.openstack.common import log as nova_logging
from nova import paths
from nova import rpc
from nova import service
+from nova.tests import fixtures as nova_fixtures
from nova.tests.unit import conf_fixture
from nova.tests.unit import policy_fixture
from nova import utils
@@ -274,57 +275,6 @@ class TestCase(testtools.TestCase):
if test_timeout > 0:
self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
- def _setup_logging(self):
- """Setup Logging redirection for tests.
-
- There are a number of things we want to handle with logging in tests:
-
- * Redirect the logging to somewhere that we can test or dump it later.
-
- * Ensure that as many DEBUG messages as possible are actually
- executed, to ensure they are actually syntactically valid
- (they often have not been).
-
- * Ensure that we create useful output for tests that doesn't
- overwhelm the testing system (which means we can't capture
- the 100 MB of debug logging on every run).
-
- To do this we create a logger fixture at the root level, which
- defaults to INFO and create a Null Logger at DEBUG which lets
- us execute log messages at DEBUG but not keep the output.
-
- To support local debugging OS_DEBUG=True can be set in the
- environment, which will print out the full debug logging.
-
- There are also a set of overrides for particularly verbose
- modules to be even less than INFO.
-
- """
- # set root logger to debug
- root = logging.getLogger()
- root.setLevel(logging.DEBUG)
-
- # supports collecting debug level for local runs
- if os.environ.get('OS_DEBUG') in _TRUE_VALUES:
- level = logging.DEBUG
- else:
- level = logging.INFO
-
- # Collect logs
- fs = '%(asctime)s %(levelname)s [%(name)s] %(message)s'
- self.useFixture(fixtures.FakeLogger(format=fs, level=None))
- root.handlers[0].setLevel(level)
-
- if level > logging.DEBUG:
- # Just attempt to format debug level logs, but don't save them
- handler = NullHandler()
- self.useFixture(fixtures.LogHandler(handler, nuke_handlers=False))
- handler.setLevel(logging.DEBUG)
-
- # Don't log every single DB migration step
- logging.getLogger(
- 'migrate.versioning.api').setLevel(logging.WARNING)
-
def setUp(self):
"""Run before each test method to initialize test environment."""
super(TestCase, self).setUp()
@@ -335,19 +285,14 @@ class TestCase(testtools.TestCase):
self.useFixture(TranslationFixture())
self.useFixture(log_fixture.get_logging_handle_error_fixture())
- if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
- stdout = self.useFixture(fixtures.StringStream('stdout')).stream
- self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
- if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
- stderr = self.useFixture(fixtures.StringStream('stderr')).stream
- self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
+ self.useFixture(nova_fixtures.OutputStreamCapture())
+
+ self.useFixture(nova_fixtures.StandardLogging())
rpc.add_extra_exmods('nova.test')
self.addCleanup(rpc.clear_extra_exmods)
self.addCleanup(rpc.cleanup)
- self._setup_logging()
-
# NOTE(sdague): because of the way we were using the lock
# wrapper we eneded up with a lot of tests that started
# relying on global external locking being set up for them. We
diff --git a/nova/tests/fixtures.py b/nova/tests/fixtures.py
new file mode 100644
index 0000000000..0754a24f3b
--- /dev/null
+++ b/nova/tests/fixtures.py
@@ -0,0 +1,130 @@
+# 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.
+
+"""Fixtures for Nova tests."""
+from __future__ import absolute_import
+
+import logging
+import os
+
+import fixtures
+
+_TRUE_VALUES = ('True', 'true', '1', 'yes')
+
+
+class NullHandler(logging.Handler):
+ """custom default NullHandler to attempt to format the record.
+
+ Used in conjunction with
+ log_fixture.get_logging_handle_error_fixture to detect formatting errors in
+ debug level logs without saving the logs.
+ """
+ def handle(self, record):
+ self.format(record)
+
+ def emit(self, record):
+ pass
+
+ def createLock(self):
+ self.lock = None
+
+
+class StandardLogging(fixtures.Fixture):
+ """Setup Logging redirection for tests.
+
+ There are a number of things we want to handle with logging in tests:
+
+ * Redirect the logging to somewhere that we can test or dump it later.
+
+ * Ensure that as many DEBUG messages as possible are actually
+ executed, to ensure they are actually syntactically valid (they
+ often have not been).
+
+ * Ensure that we create useful output for tests that doesn't
+ overwhelm the testing system (which means we can't capture the
+ 100 MB of debug logging on every run).
+
+ To do this we create a logger fixture at the root level, which
+ defaults to INFO and create a Null Logger at DEBUG which lets
+ us execute log messages at DEBUG but not keep the output.
+
+ To support local debugging OS_DEBUG=True can be set in the
+ environment, which will print out the full debug logging.
+
+ There are also a set of overrides for particularly verbose
+ modules to be even less than INFO.
+
+ """
+
+ def setUp(self):
+ super(StandardLogging, self).setUp()
+
+ # set root logger to debug
+ root = logging.getLogger()
+ root.setLevel(logging.DEBUG)
+
+ # supports collecting debug level for local runs
+ if os.environ.get('OS_DEBUG') in _TRUE_VALUES:
+ level = logging.DEBUG
+ else:
+ level = logging.INFO
+
+ # Collect logs
+ fs = '%(asctime)s %(levelname)s [%(name)s] %(message)s'
+ self.logger = self.useFixture(
+ fixtures.FakeLogger(format=fs, level=None))
+ # TODO(sdague): why can't we send level through the fake
+ # logger? Tests prove that it breaks, but it's worth getting
+ # to the bottom of.
+ root.handlers[0].setLevel(level)
+
+ if level > logging.DEBUG:
+ # Just attempt to format debug level logs, but don't save them
+ handler = NullHandler()
+ self.useFixture(fixtures.LogHandler(handler, nuke_handlers=False))
+ handler.setLevel(logging.DEBUG)
+
+ # Don't log every single DB migration step
+ logging.getLogger(
+ 'migrate.versioning.api').setLevel(logging.WARNING)
+
+
+class OutputStreamCapture(fixtures.Fixture):
+ """Capture output streams during tests.
+
+ This fixture captures errant printing to stderr / stdout during
+ the tests and lets us see those streams at the end of the test
+ runs instead. Useful to see what was happening during failed
+ tests.
+ """
+ def setUp(self):
+ super(OutputStreamCapture, self).setUp()
+ if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
+ self.out = self.useFixture(fixtures.StringStream('stdout'))
+ self.useFixture(
+ fixtures.MonkeyPatch('sys.stdout', self.out.stream))
+ if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
+ self.err = self.useFixture(fixtures.StringStream('stderr'))
+ self.useFixture(
+ fixtures.MonkeyPatch('sys.stderr', self.err.stream))
+
+ @property
+ def stderr(self):
+ return self.err._details["stderr"].as_text()
+
+ @property
+ def stdout(self):
+ return self.out._details["stdout"].as_text()
diff --git a/nova/tests/unit/test_fixtures.py b/nova/tests/unit/test_fixtures.py
new file mode 100644
index 0000000000..e667486968
--- /dev/null
+++ b/nova/tests/unit/test_fixtures.py
@@ -0,0 +1,126 @@
+# 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.
+
+import logging
+import sys
+
+import fixtures as fx
+from oslo.config import cfg
+import testtools
+
+from nova.tests.unit import conf_fixture
+from nova.tests import fixtures
+
+CONF = cfg.CONF
+
+
+class TestConfFixture(testtools.TestCase):
+ """Test the Conf fixtures in Nova.
+
+ This is a basic test that this fixture works like we expect.
+
+ Expectations:
+
+ 1. before using the fixture, a default value (api_paste_config)
+ comes through untouched.
+
+ 2. before using the fixture, a known default value that we
+ override is correct.
+
+ 3. after using the fixture a known value that we override is the
+ new value.
+
+ 4. after using the fixture we can set a default value to something
+ random, and it will be reset once we are done.
+
+ There are 2 copies of this test so that you can verify they do the
+ right thing with:
+
+ tox -e py27 test_fixtures -- --concurrency=1
+
+ As regardless of run order, their initial asserts would be
+ impacted if the reset behavior isn't working correctly.
+
+ """
+ def _test_override(self):
+ self.assertEqual(CONF.api_paste_config, 'api-paste.ini')
+ self.assertEqual(CONF.fake_network, False)
+ self.useFixture(conf_fixture.ConfFixture())
+ CONF.set_default('api_paste_config', 'foo')
+ self.assertEqual(CONF.fake_network, True)
+
+ def test_override1(self):
+ self._test_override()
+
+ def test_override2(self):
+ self._test_override()
+
+
+class TestOutputStream(testtools.TestCase):
+ """Ensure Output Stream capture works as expected.
+
+ This has the added benefit of providing a code example of how you
+ can manipulate the output stream in your own tests.
+ """
+ def test_output(self):
+ self.useFixture(fx.EnvironmentVariable('OS_STDOUT_CAPTURE', '1'))
+ self.useFixture(fx.EnvironmentVariable('OS_STDERR_CAPTURE', '1'))
+
+ out = self.useFixture(fixtures.OutputStreamCapture())
+ sys.stdout.write("foo")
+ sys.stderr.write("bar")
+ self.assertEqual(out.stdout, "foo")
+ self.assertEqual(out.stderr, "bar")
+ # TODO(sdague): nuke the out and err buffers so it doesn't
+ # make it to testr
+
+
+class TestLogging(testtools.TestCase):
+ def test_default_logging(self):
+ stdlog = self.useFixture(fixtures.StandardLogging())
+ root = logging.getLogger()
+ # there should be a null handler as well at DEBUG
+ self.assertEqual(len(root.handlers), 2, root.handlers)
+ log = logging.getLogger(__name__)
+ log.info("at info")
+ log.debug("at debug")
+ self.assertIn("at info", stdlog.logger.output)
+ self.assertNotIn("at debug", stdlog.logger.output)
+
+ # broken debug messages should still explode, even though we
+ # aren't logging them in the regular handler
+ self.assertRaises(TypeError, log.debug, "this is broken %s %s", "foo")
+
+ # and, ensure that one of the terrible log messages isn't
+ # output at info
+ warn_log = logging.getLogger('migrate.versioning.api')
+ warn_log.info("warn_log at info, should be skipped")
+ warn_log.error("warn_log at error")
+ self.assertIn("warn_log at error", stdlog.logger.output)
+ self.assertNotIn("warn_log at info", stdlog.logger.output)
+
+ def test_debug_logging(self):
+ self.useFixture(fx.EnvironmentVariable('OS_DEBUG', '1'))
+
+ stdlog = self.useFixture(fixtures.StandardLogging())
+ root = logging.getLogger()
+ # there should no longer be a null handler
+ self.assertEqual(len(root.handlers), 1, root.handlers)
+ log = logging.getLogger(__name__)
+ log.info("at info")
+ log.debug("at debug")
+ self.assertIn("at info", stdlog.logger.output)
+ self.assertIn("at debug", stdlog.logger.output)
diff --git a/tox.ini b/tox.ini
index 9140769c66..54b714d6f4 100644
--- a/tox.ini
+++ b/tox.ini
@@ -70,8 +70,9 @@ commands = python setup.py build_sphinx
# The rest of the ignores are TODOs
# New from hacking 0.9: E129, E131, H407, H405, H904
# E251 Skipped due to https://github.com/jcrocholl/pep8/issues/301
+# H305,H306 Skipped due to inability to handle absolute_import
-ignore = E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E251,H405,H803,H904
+ignore = E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E251,H305,H306,H405,H803,H904
exclude = .venv,.git,.tox,dist,doc,*openstack/common*,*lib/python*,*egg,build,tools/xenserver*
# To get a list of functions that are more complex than 25, set max-complexity
# to 25 and run 'tox -epep8'.