Skip to content

Commit

Permalink
bug(tests): mock reads of host's /sys/class/net via get_sys_class_path
Browse files Browse the repository at this point in the history
Avoid leaking reads to the underlying host's /sys/class/net files.
Some test environments contain virtual network hardware and
configuration such as Calico network devices which provide
duplicated MAC addresses for each device in /sys/class/net. This
results in errors from unittests calling cloudinit.net.get_interfaces.

Provide a disable_sysfs_net` fixture and use it in net-related
modules or functions to avoid unrelated test failures due to
environmental differences.

Provide the ability to turn off this fixture for tests which
need to write to the mocked sysfs tmp directory so test artifacts
do not pollute other tests.

This fixture can be disabled by passing False to the disable_sysfs_net
via request.param. We want to avoid polluting tox.ini with pytest.marks
for infrequently used cases like this.

Also fix whitespace in tox.ini
  • Loading branch information
blackboxsw committed Mar 6, 2024
1 parent 67685d6 commit 463d36c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
20 changes: 20 additions & 0 deletions tests/unittests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,26 @@ def fake_filesystem(mocker, tmpdir):
yield str(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
mock_sysfs = f"{tmpdir_factory.mktemp('sysfs')}/"
with mock.patch(
"cloudinit.net.get_sys_class_path", return_value=mock_sysfs
):
yield mock_sysfs


@pytest.fixture(autouse=True)
def disable_dns_lookup(request):
if "allow_dns_lookup" in request.keywords:
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ markers =
serial: tests that do not work in parallel, skipped with py3-fast
unstable: skip this test because it is flakey
user_data: the user data to be passed to the test instance
allow_dns_lookup: disable autochecking for host network configuration
allow_dns_lookup: disable autochecking for host network configuration

[coverage:paths]
source =
Expand Down

0 comments on commit 463d36c

Please sign in to comment.