Skip to content
This repository has been archived by the owner on Nov 15, 2024. It is now read-only.

Commit

Permalink
test: fix disable_sysfs_net mock (canonical#5065)
Browse files Browse the repository at this point in the history
The fixture parametrization ability added in 9baf31c doesn't work
as expected. When you have a session-wide fixture, the setup is run
once, then further invocations of the fixture (including autouse) uses a
cached version of the fixture.  Teardown for the session fixture happens
at the end of all test runs. This also applies to mock patching. Since
the mock patching happens only once, parametrizing the fixture to yield
without patching doesn't undo the initial mock setup; the
parametrization of `disable_sys_net` effectively does nothing.

The good news is that patches stack, so current tests that patch
`get_sys_class_path` differently will still work fine. If we need to
disable the patching entirely, that is also possible by saving the
original `get_sys_class_path` before applying the global disable mock,
then having a separate mock that has a side effect of calling
the original function.
  • Loading branch information
TheRealFalcon committed Mar 20, 2024
1 parent 5062bee commit dc0eafb
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 16 deletions.
14 changes: 2 additions & 12 deletions tests/unittests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,8 @@ def fake_filesystem(mocker, tmpdir):


@pytest.fixture(scope="session", autouse=True)
def disable_sysfs_net(request, tmpdir_factory):
"""Avoid tests which read the undertying host's /syc/class/net.
To allow unobscured reads of /sys/class/net on the host we can
parametrize the fixture with:
@pytest.mark.parametrize("disable_sysfs_net", [False], indirect=True)
"""
if hasattr(request, "param") and getattr(request, "param") is False:
# Test disabled this fixture, perform no mocks.
yield
return
def disable_sysfs_net(tmpdir_factory):
"""Avoid tests which read the underlying host's /syc/class/net."""
mock_sysfs = f"{tmpdir_factory.mktemp('sysfs')}/"
with mock.patch(
"cloudinit.net.get_sys_class_path", return_value=mock_sysfs
Expand Down
5 changes: 1 addition & 4 deletions tests/unittests/net/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ def test_sys_dev_path_without_path(self):

class TestReadSysNet:
@pytest.fixture(autouse=True)
@pytest.mark.parametrize(
"disable_sysfs_net", [False], indirect=["disable_sysfs_net"]
)
def setup(self, disable_sysfs_net, tmpdir_factory):
def setup(self, tmpdir_factory):
# We mock invididual numbered tmpdirs here because these tests write
# to the sysfs directory and stale test artifacts break later tests.
mock_sysfs = f"{tmpdir_factory.mktemp('sysfs', numbered=True)}/"
Expand Down

0 comments on commit dc0eafb

Please sign in to comment.