From 854a10dc8daa2ca21fd1d5a49318445b16dd503d Mon Sep 17 00:00:00 2001 From: vinsymoyya <186405436+vinsymoyya@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:36:51 +0530 Subject: [PATCH] Restore shared state after test fixtures --- tcli/command_response_test.py | 6 +- tcli/end_to_end_test.py | 18 +++-- tcli/fixture_isolation_test.py | 118 +++++++++++++++++++++++++++++++++ tcli/inventory_base_test.py | 7 +- tcli/tcli_test.py | 25 +++---- 5 files changed, 145 insertions(+), 29 deletions(-) create mode 100644 tcli/fixture_isolation_test.py diff --git a/tcli/command_response_test.py b/tcli/command_response_test.py index 660ea7a..3f95206 100644 --- a/tcli/command_response_test.py +++ b/tcli/command_response_test.py @@ -75,7 +75,11 @@ class UnitTestCmdResponse(unittest.TestCase): def setUp(self): super(UnitTestCmdResponse, self).setUp() - command_response.threading.Lock = mock.MagicMock() + threading_stub = mock.Mock(wraps=command_response.threading) + threading_stub.Lock = mock.MagicMock() + self.enterContext( + mock.patch.object(command_response, 'threading', threading_stub) + ) self.cmd_response = command_response.CmdResponse() # Set class variables to defaults. self.cmd_response.__init__() diff --git a/tcli/end_to_end_test.py b/tcli/end_to_end_test.py index 9e0b523..b047169 100644 --- a/tcli/end_to_end_test.py +++ b/tcli/end_to_end_test.py @@ -14,16 +14,16 @@ """End to end system test of TCLI, includes dependency on libraries.""" -import importlib import os import unittest from unittest import mock from absl import flags +from absl.testing import flagsaver +from tcli import accessor_canned +from tcli import inventory_csv from tcli import tcli_lib as tcli -tcli.inventory = importlib.import_module('tcli.inventory_csv') -tcli.accessor = importlib.import_module('tcli.accessor_canned') FLAGS = flags.FLAGS # Test outputs. @@ -42,19 +42,17 @@ class UnitTestTCLIEndToEnd(unittest.TestCase): @classmethod def setUpClass(cls): super(UnitTestTCLIEndToEnd, cls).setUpClass() + cls.enterClassContext(flagsaver.flagsaver()) + cls.enterClassContext(mock.patch.object(tcli, 'inventory', inventory_csv)) + cls.enterClassContext(mock.patch.object(tcli, 'accessor', accessor_canned)) + cls.enterClassContext(mock.patch.object(tcli.command_response, 'tqdm')) tcli.FLAGS([ __file__, ]) - # Stub out as little as possible. - tcli.command_response.tqdm = mock.MagicMock() - - @classmethod - def tearDownClass(cls): - tcli.inventory = importlib.import_module('tcli.inventory_base') - super(UnitTestTCLIEndToEnd, cls).tearDownClass() def setUp(self): super(UnitTestTCLIEndToEnd, self).setUp() + self.enterContext(flagsaver.flagsaver()) tcli.FLAGS.template_dir = os.path.join( os.path.dirname(__file__), 'testdata' ) diff --git a/tcli/fixture_isolation_test.py b/tcli/fixture_isolation_test.py new file mode 100644 index 0000000..e6b84c6 --- /dev/null +++ b/tcli/fixture_isolation_test.py @@ -0,0 +1,118 @@ +# Copyright 2026 Google Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. +"""Ensure test fixtures release their process-wide state after cleanup.""" + +import subprocess +import sys +import unittest + +_PROBE = r""" +import importlib +import sys +import threading +from absl import flags +from tcli import accessor_base, command_response, inventory_base, tcli_lib + +module_name, class_name = { + 'response': ('tcli.command_response_test', 'UnitTestCmdResponse'), + 'inventory': ('tcli.inventory_base_test', 'InventoryBaseTest'), + 'tcli': ('tcli.tcli_test', 'UnitTestTCLI'), + 'end_to_end': ('tcli.end_to_end_test', 'UnitTestTCLIEndToEnd'), +}[sys.argv[1]] +original = { + 'lock': threading.Lock, + 'event': threading.Event, + 'fetch': inventory_base.Inventory._FetchDevices, + 'send': accessor_base.SendRequests, + 'tqdm': command_response.tqdm, + 'flags': flags.FLAGS, + 'inventory_module': tcli_lib.inventory, + 'accessor_module': tcli_lib.accessor, +} +flag_values = { + name: flags.FLAGS[name].value + for name in ('template_dir', 'color', 'config_file', 'display', 'filter') + if name in flags.FLAGS +} +fixture = getattr(importlib.import_module(module_name), class_name) +fixture.setUpClass() +try: + case = fixture() + try: + case.setUp() + if getattr(case, 'inv', None) is not None: + assert case.inv._loaded.wait(2), 'Inventory did not finish loading' + case.tearDown() + finally: + case.doCleanups() +finally: + try: + fixture.tearDownClass() + finally: + fixture.doClassCleanups() + +leaks = [] +for name, actual in { + 'lock': threading.Lock, + 'event': threading.Event, + 'fetch': inventory_base.Inventory._FetchDevices, + 'send': accessor_base.SendRequests, + 'tqdm': command_response.tqdm, + 'flags': tcli_lib.FLAGS, + 'inventory_module': tcli_lib.inventory, + 'accessor_module': tcli_lib.accessor, +}.items(): + if actual is not original[name]: + leaks.append(name) +for name, value in flag_values.items(): + if flags.FLAGS[name].value != value: + leaks.append('flag value: ' + name) +assert not leaks, 'Fixture leaked process state: ' + ', '.join(leaks) + +# An unrelated caller can still use the real synchronization primitives. +event = threading.Event() +worker = threading.Thread(target=event.set) +worker.start() +worker.join(2) +assert not worker.is_alive() and event.is_set() +""" + + +class FixtureIsolationTest(unittest.TestCase): + + def assertFixtureIsolated(self, name): + result = subprocess.run( + [sys.executable, '-c', _PROBE, name], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + + def testCommandResponseFixture(self): + self.assertFixtureIsolated('response') + + def testInventoryFixture(self): + self.assertFixtureIsolated('inventory') + + def testTcliFixture(self): + self.assertFixtureIsolated('tcli') + + def testEndToEndFixture(self): + self.assertFixtureIsolated('end_to_end') + + +if __name__ == '__main__': + unittest.main() diff --git a/tcli/inventory_base_test.py b/tcli/inventory_base_test.py index 6361707..f653bad 100644 --- a/tcli/inventory_base_test.py +++ b/tcli/inventory_base_test.py @@ -54,7 +54,11 @@ def _FetchDevicesStub(self): } return - inventory_base.Inventory._FetchDevices = _FetchDevicesStub + cls.enterClassContext( + mock.patch.object( + inventory_base.Inventory, '_FetchDevices', _FetchDevicesStub + ) + ) @classmethod def tearDownClass(cls): @@ -82,6 +86,7 @@ def setUp(self): ), } self.inv = inventory_base.Inventory() + self.addCleanup(self.inv._devices_thread.join) self._ClearFilters(self.inv) def tearDown(self): diff --git a/tcli/tcli_test.py b/tcli/tcli_test.py index 8beb223..5aa578a 100644 --- a/tcli/tcli_test.py +++ b/tcli/tcli_test.py @@ -23,6 +23,7 @@ from unittest import mock from absl import flags +from absl.testing import flagsaver from tcli import accessor_base as accessor from tcli import command_register from tcli import inventory_base as inventory @@ -81,21 +82,16 @@ class UnitTestTCLI(unittest.TestCase): @classmethod def setUpClass(cls): - cls.flags_orig = copy.deepcopy(tcli.FLAGS) - tcli.command_response.threading.Event = mock.MagicMock() - tcli.command_response.threading.Lock = mock.MagicMock() - tcli.command_response.tqdm = mock.MagicMock() + super().setUpClass() + cls.enterClassContext(flagsaver.flagsaver()) + cls.enterClassContext(mock.patch.object(tcli.command_response, 'threading')) + cls.enterClassContext(mock.patch.object(tcli.command_response, 'tqdm')) tcli.FLAGS.template_dir = os.path.join( os.path.dirname(__file__), 'testdata' ) - return super().setUpClass() - - @classmethod - def tearDownClass(cls): - tcli.FLAGS = cls.flags_orig - return super().tearDownClass() def setUp(self): + self.enterContext(flagsaver.flagsaver()) # Instantiate FLAGS global var. tcli.FLAGS([ __file__, @@ -106,8 +102,7 @@ def setUp(self): tcli.FLAGS.display = 'raw' tcli.FLAGS.filter = None - self.orig_dev_attr = tcli.inventory.DEVICE_ATTRIBUTES - tcli.inventory.DEVICE_ATTRIBUTES = {} + self.enterContext(mock.patch.object(tcli.inventory, 'DEVICE_ATTRIBUTES', {})) with mock.patch.object(tcli.inventory, 'Inventory'): self.tcli_obj = tcli.TCLI(interactive=False) @@ -120,7 +115,7 @@ def setUp(self): } self.tcli_obj.inventory.targets = '' self.tcli_obj._Print = mock.Mock() - accessor.SendRequests = mock.Mock() + self.enterContext(mock.patch.object(accessor, 'SendRequests')) command_register.RegisterCommands(self.tcli_obj, self.tcli_obj.cli_parser) self.tcli_obj.cli_parser.RegisterCommand( @@ -136,10 +131,6 @@ def setUp(self): self.tcli_obj.timeout = 1 return super().setUp() - def tearDown(self): - tcli.inventory.DEVICE_ATTRIBUTES = self.orig_dev_attr - return super().tearDown() - def testInlineOnly(self): """Tests that only inline supported commands are ruin when inline.""" # TODO: Add tests here.