From 463d36cc237435084e5ddb4d7468f5546e7ece28 Mon Sep 17 00:00:00 2001 From: Chad Smith Date: Wed, 6 Mar 2024 07:51:34 -0700 Subject: [PATCH] bug(tests): mock reads of host's /sys/class/net via get_sys_class_path 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 --- tests/unittests/conftest.py | 20 ++++++++++++++++++++ tox.ini | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/unittests/conftest.py b/tests/unittests/conftest.py index 91dbd06..22bc189 100644 --- a/tests/unittests/conftest.py +++ b/tests/unittests/conftest.py @@ -61,6 +61,26 @@ def fake_filesystem(mocker, tmpdir): mocker.patch.object(mod, f, trap_func) +@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: diff --git a/tox.ini b/tox.ini index 5f01a9a..cd261f3 100644 --- a/tox.ini +++ b/tox.ini @@ -323,4 +323,4 @@ 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 -- 2.33.0