diff --git a/neutron_lib/fixture.py b/neutron_lib/fixture.py index fc8409732..ccbbc47d4 100644 --- a/neutron_lib/fixture.py +++ b/neutron_lib/fixture.py @@ -286,3 +286,25 @@ class DBResourceExtendFixture(fixtures.Fixture): def _restore(self): resource_extend._resource_extend_functions = self._backup + + +class OpenFixture(fixtures.Fixture): + """Mock access to a specific file while preserving open for others.""" + + def __init__(self, filepath, contents=''): + self.path = filepath + self.contents = contents + + def _setUp(self): + self.mock_open = mock.mock_open(read_data=self.contents) + self._orig_open = open + + def replacement_open(name, *args, **kwargs): + if name == self.path: + return self.mock_open(name, *args, **kwargs) + return self._orig_open(name, *args, **kwargs) + + self._patch = mock.patch('six.moves.builtins.open', + new=replacement_open) + self._patch.start() + self.addCleanup(self._patch.stop) diff --git a/neutron_lib/tests/tools.py b/neutron_lib/tests/tools.py index 770ad251d..0ddd1362c 100644 --- a/neutron_lib/tests/tools.py +++ b/neutron_lib/tests/tools.py @@ -13,8 +13,10 @@ # License for the specific language governing permissions and limitations # under the License. +import os import platform import random +import time import warnings import fixtures @@ -66,3 +68,13 @@ def get_random_cidr(version=4): random.randint(3, 254), 24) return '2001:db8:%x::/%d' % (random.getrandbits(16), 64) + + +def reset_random_seed(): + # reset random seed to make sure other processes extracting values from RNG + # don't get the same results (useful especially when you then use the + # random values to allocate system resources from global pool, like ports + # to listen). Use both current time and pid to make sure no tests started + # at the same time get the same values from RNG + seed = time.time() + os.getpid() + random.seed(seed) diff --git a/releasenotes/notes/rehome-testools-6fba053249e14d42.yaml b/releasenotes/notes/rehome-testools-6fba053249e14d42.yaml new file mode 100644 index 000000000..3303de718 --- /dev/null +++ b/releasenotes/notes/rehome-testools-6fba053249e14d42.yaml @@ -0,0 +1,5 @@ +--- +features: + - The ``OpenFixture`` class is now available in ``neutron_lib.fixtures``. + - The ``reset_random_seed`` function is now available in + ``neutron_lib.tests.tools``.