| 1 |
# Copyright 2010-2011 OpenStack Foundation |
| 2 |
# All Rights Reserved. |
| 3 |
# |
| 4 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 5 |
# not use this file except in compliance with the License. You may obtain |
| 6 |
# a copy of the License at |
| 7 |
# |
| 8 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
# |
| 10 |
# Unless required by applicable law or agreed to in writing, software |
| 11 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 |
# License for the specific language governing permissions and limitations |
| 14 |
# under the License. |
| 15 |
|
| 16 |
import logging as std_logging |
| 17 |
import os |
| 18 |
import os.path |
| 19 |
import random |
| 20 |
from unittest import mock |
| 21 |
|
| 22 |
import fixtures |
| 23 |
from oslo_config import cfg |
| 24 |
from oslo_db import options as db_options |
| 25 |
from oslo_utils import strutils |
| 26 |
import pbr.version |
| 27 |
import testtools |
| 28 |
|
| 29 |
from neutron_lib._i18n import _ |
| 30 |
from neutron_lib import constants |
| 31 |
from neutron_lib import exceptions |
| 32 |
from neutron_lib import fixture |
| 33 |
|
| 34 |
from neutron_lib.tests import _post_mortem_debug as post_mortem_debug |
| 35 |
|
| 36 |
|
| 37 |
CONF = cfg.CONF |
| 38 |
LOG_FORMAT = "%(asctime)s %(levelname)8s [%(name)s] %(message)s" |
| 39 |
|
| 40 |
ROOTDIR = os.path.dirname(__file__) |
| 41 |
ETCDIR = os.path.join(ROOTDIR, 'etc') |
| 42 |
|
| 43 |
|
| 44 |
def etcdir(*p): |
| 45 |
return os.path.join(ETCDIR, *p) |
| 46 |
|
| 47 |
|
| 48 |
def fake_use_fatal_exceptions(*args): |
| 49 |
return True |
| 50 |
|
| 51 |
|
| 52 |
def get_rand_name(max_length=None, prefix='test'): |
| 53 |
"""Return a random string. |
| 54 |
|
| 55 |
The string will start with 'prefix' and will be exactly 'max_length'. |
| 56 |
If 'max_length' is None, then exactly 8 random characters, each |
| 57 |
hexadecimal, will be added. In case len(prefix) <= len(max_length), |
| 58 |
ValueError will be raised to indicate the problem. |
| 59 |
""" |
| 60 |
|
| 61 |
if max_length: |
| 62 |
length = max_length - len(prefix) |
| 63 |
if length <= 0: |
| 64 |
raise ValueError("'max_length' must be bigger than 'len(prefix)'.") |
| 65 |
|
| 66 |
suffix = ''.join(str(random.randint(0, 9)) for i in range(length)) |
| 67 |
else: |
| 68 |
suffix = hex(random.randint(0x10000000, 0x7fffffff))[2:] |
| 69 |
return prefix + suffix |
| 70 |
|
| 71 |
|
| 72 |
def get_rand_device_name(prefix='test'): |
| 73 |
return get_rand_name( |
| 74 |
max_length=constants.DEVICE_NAME_MAX_LEN, prefix=prefix) |
| 75 |
|
| 76 |
|
| 77 |
def bool_from_env(key, strict=False, default=False): |
| 78 |
value = os.environ.get(key) |
| 79 |
return strutils.bool_from_string(value, strict=strict, default=default) |
| 80 |
|
| 81 |
|
| 82 |
def get_test_timeout(default=0): |
| 83 |
return int(os.environ.get('OS_TEST_TIMEOUT', default)) |
| 84 |
|
| 85 |
|
| 86 |
def sanitize_log_path(path): |
| 87 |
# Sanitize the string so that its log path is shell friendly |
| 88 |
return path.replace(' ', '-').replace('(', '_').replace(')', '_') |
| 89 |
|
| 90 |
|
| 91 |
class AttributeDict(dict): |
| 92 |
|
| 93 |
"""Provide attribute access (dict.key) to dictionary values.""" |
| 94 |
|
| 95 |
def __getattr__(self, name): |
| 96 |
"""Allow attribute access for all keys in the dict.""" |
| 97 |
if name in self: |
| 98 |
return self[name] |
| 99 |
raise AttributeError(_("Unknown attribute '%s'.") % name) |
| 100 |
|
| 101 |
|
| 102 |
class BaseTestCase(testtools.TestCase): |
| 103 |
|
| 104 |
@staticmethod |
| 105 |
def config_parse(conf=None, args=None): |
| 106 |
"""Create the default configurations.""" |
| 107 |
if args is None: |
| 108 |
args = [] |
| 109 |
args += ['--config-file', etcdir('neutron_lib.conf')] |
| 110 |
if conf is None: |
| 111 |
version_info = pbr.version.VersionInfo('neutron-lib') |
| 112 |
cfg.CONF(args=args, project='neutron_lib', |
| 113 |
version=f'%(prog)s {version_info.release_string()}') |
| 114 |
else: |
| 115 |
conf(args) |
| 116 |
|
| 117 |
def setUp(self): |
| 118 |
super().setUp() |
| 119 |
self.useFixture(fixture.PluginDirectoryFixture()) |
| 120 |
|
| 121 |
# Enabling 'use_fatal_exceptions' allows us to catch string |
| 122 |
# substitution format errors in exception messages. |
| 123 |
mock.patch.object(exceptions.NeutronException, 'use_fatal_exceptions', |
| 124 |
return_value=True).start() |
| 125 |
|
| 126 |
db_options.set_defaults(cfg.CONF, connection='sqlite://') |
| 127 |
|
| 128 |
self.useFixture(fixtures.MonkeyPatch( |
| 129 |
'oslo_config.cfg.find_config_files', |
| 130 |
lambda project=None, prog=None, extension=None: [])) |
| 131 |
|
| 132 |
self.setup_config() |
| 133 |
|
| 134 |
# Configure this first to ensure pm debugging support for setUp() |
| 135 |
debugger = os.environ.get('OS_POST_MORTEM_DEBUGGER') |
| 136 |
if debugger: |
| 137 |
self.addOnException(post_mortem_debug.get_exception_handler( |
| 138 |
debugger)) |
| 139 |
|
| 140 |
# Make sure we see all relevant deprecation warnings when running tests |
| 141 |
self.useFixture(fixture.WarningsFixture()) |
| 142 |
|
| 143 |
if bool_from_env('OS_DEBUG'): |
| 144 |
_level = std_logging.DEBUG |
| 145 |
else: |
| 146 |
_level = std_logging.INFO |
| 147 |
capture_logs = bool_from_env('OS_LOG_CAPTURE') |
| 148 |
if not capture_logs: |
| 149 |
std_logging.basicConfig(format=LOG_FORMAT, level=_level) |
| 150 |
self.log_fixture = self.useFixture( |
| 151 |
fixtures.FakeLogger( |
| 152 |
format=LOG_FORMAT, |
| 153 |
level=_level, |
| 154 |
nuke_handlers=capture_logs, |
| 155 |
)) |
| 156 |
|
| 157 |
test_timeout = get_test_timeout() |
| 158 |
if test_timeout == -1: |
| 159 |
test_timeout = 0 |
| 160 |
if test_timeout > 0: |
| 161 |
self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) |
| 162 |
|
| 163 |
# If someone does use tempfile directly, ensure that it's cleaned up |
| 164 |
self.useFixture(fixtures.NestedTempfile()) |
| 165 |
self.useFixture(fixtures.TempHomeDir()) |
| 166 |
|
| 167 |
self.addCleanup(mock.patch.stopall) |
| 168 |
|
| 169 |
if bool_from_env('OS_STDOUT_CAPTURE'): |
| 170 |
stdout = self.useFixture(fixtures.StringStream('stdout')).stream |
| 171 |
self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) |
| 172 |
if bool_from_env('OS_STDERR_CAPTURE'): |
| 173 |
stderr = self.useFixture(fixtures.StringStream('stderr')).stream |
| 174 |
self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) |
| 175 |
|
| 176 |
self.addOnException(self.check_for_systemexit) |
| 177 |
self.orig_pid = os.getpid() |
| 178 |
|
| 179 |
def get_new_temp_dir(self): |
| 180 |
"""Create a new temporary directory. |
| 181 |
|
| 182 |
:returns fixtures.TempDir |
| 183 |
""" |
| 184 |
return self.useFixture(fixtures.TempDir()) |
| 185 |
|
| 186 |
def get_default_temp_dir(self): |
| 187 |
"""Create a default temporary directory. |
| 188 |
|
| 189 |
Returns the same directory during the whole test case. |
| 190 |
|
| 191 |
:returns fixtures.TempDir |
| 192 |
""" |
| 193 |
if not hasattr(self, '_temp_dir'): |
| 194 |
self._temp_dir = self.get_new_temp_dir() |
| 195 |
return self._temp_dir |
| 196 |
|
| 197 |
def check_for_systemexit(self, exc_info): |
| 198 |
if isinstance(exc_info[1], SystemExit): |
| 199 |
if os.getpid() != self.orig_pid: |
| 200 |
# Subprocess - let it just exit |
| 201 |
raise exc_info[1] |
| 202 |
# This makes sys.exit(0) still a failure |
| 203 |
self.force_failure = True |
| 204 |
|
| 205 |
def assertOrderedEqual(self, expected, actual): |
| 206 |
expect_val = self.sort_dict_lists(expected) |
| 207 |
actual_val = self.sort_dict_lists(actual) |
| 208 |
self.assertEqual(expect_val, actual_val) |
| 209 |
|
| 210 |
def sort_dict_lists(self, dic): |
| 211 |
for key, value in dic.items(): |
| 212 |
if isinstance(value, list): |
| 213 |
dic[key] = sorted(value) |
| 214 |
elif isinstance(value, dict): |
| 215 |
dic[key] = self.sort_dict_lists(value) |
| 216 |
return dic |
| 217 |
|
| 218 |
def assertDictSupersetOf(self, expected_subset, actual_superset): |
| 219 |
"""Checks that actual dict contains the expected dict. |
| 220 |
|
| 221 |
After checking that the arguments are of the right type, this checks |
| 222 |
that each item in expected_subset is in, and matches, what is in |
| 223 |
actual_superset. Separate tests are done, so that detailed info can |
| 224 |
be reported upon failure. |
| 225 |
""" |
| 226 |
if not isinstance(expected_subset, dict): |
| 227 |
self.fail( |
| 228 |
f"expected_subset ({type(expected_subset)}) is not " |
| 229 |
"an instance of dict") |
| 230 |
if not isinstance(actual_superset, dict): |
| 231 |
self.fail( |
| 232 |
f"actual_superset ({type(actual_superset)}) is not " |
| 233 |
"an instance of dict") |
| 234 |
for k, v in expected_subset.items(): |
| 235 |
self.assertIn(k, actual_superset) |
| 236 |
self.assertEqual(v, actual_superset[k], |
| 237 |
f"Key {k} expected: {v!r}, actual " |
| 238 |
f"{actual_superset[k]!r}") |
| 239 |
|
| 240 |
def setup_config(self, args=None): |
| 241 |
"""Tests that need a non-default config can override this method.""" |
| 242 |
self.config_parse(args=args) |