From b7344e8ac33b29449ad15fcadd40a79019d7966f Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Mon, 28 Jun 2021 09:30:53 -0700 Subject: [PATCH] [sonic-py-common] Clear environment variables before running device_info tests (#7273) #### Why I did it To ensure any environment variables which are configured in the build/test environment do not influence the behavior of sonic-py-common during unit tests. For example, variables which might be set by continuous integration pipelines. #### How I did it Add class-scoped pytest fixture to `TestDeviceInfo` class which stashes the current environment variables, clears them and yields. Once all the test cases in the class finish, the fixture will restore the original environment variables. Also remove unnecessary unittest-style setup and teardown functions from interface_test.py --- src/sonic-py-common/tests/device_info_test.py | 11 ++++++++--- src/sonic-py-common/tests/interface_test.py | 8 -------- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/sonic-py-common/tests/device_info_test.py b/src/sonic-py-common/tests/device_info_test.py index f3b14b0a5f..df94d147aa 100644 --- a/src/sonic-py-common/tests/device_info_test.py +++ b/src/sonic-py-common/tests/device_info_test.py @@ -9,6 +9,8 @@ else: # https://pypi.python.org/pypi/mock import mock +import pytest + from sonic_py_common import device_info @@ -51,9 +53,12 @@ EXPECTED_GET_MACHINE_INFO_RESULT = { class TestDeviceInfo(object): - @classmethod - def setup_class(cls): - print("SETUP") + @pytest.fixture(scope="class", autouse=True) + def sanitize_environment(self): + # Clear environment variables, in case a variable is set in the test + # environment (e.g., PLATFORM) which could modify the behavior of sonic-py-common + with mock.patch.dict(os.environ, {}, clear=True): + yield def test_get_machine_info(self): with mock.patch("os.path.isfile") as mock_isfile: diff --git a/src/sonic-py-common/tests/interface_test.py b/src/sonic-py-common/tests/interface_test.py index bb90479733..5e5b81b040 100644 --- a/src/sonic-py-common/tests/interface_test.py +++ b/src/sonic-py-common/tests/interface_test.py @@ -4,10 +4,6 @@ import sys from sonic_py_common import interface class TestInterface(object): - @classmethod - def setup_class(cls): - print("SETUP") - def test_get_interface_table_name(self): result = interface.get_interface_table_name("Ethernet0") assert result == "INTERFACE" @@ -35,7 +31,3 @@ class TestInterface(object): assert result == "VLAN_INTERFACE" result = interface.get_port_table_name("Loopback0") assert result == "LOOPBACK_INTERFACE" - - @classmethod - def teardown_class(cls): - print("TEARDOWN")