Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion tcli/command_response_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__()
Expand Down
18 changes: 8 additions & 10 deletions tcli/end_to_end_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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'
)
Expand Down
118 changes: 118 additions & 0 deletions tcli/fixture_isolation_test.py
Original file line number Diff line number Diff line change
@@ -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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is pretty involved and I'd rather avoid a subprocess if possible.

Either move the probe into a module or consider using pytest -p randomly

[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()
7 changes: 6 additions & 1 deletion tcli/inventory_base_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
25 changes: 8 additions & 17 deletions tcli/tcli_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__,
Expand All @@ -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)
Expand All @@ -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(
Expand All @@ -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.
Expand Down
Loading