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
This commit is contained in:
Sean Dague
2014-12-09 08:35:14 -05:00
parent 8580f80f30
commit 105d6b1d8e
3 changed files with 136 additions and 60 deletions

View File

@@ -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

130
nova/tests/fixtures.py Normal file
View File

@@ -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()

View File

@@ -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'.