From 9930245f441bc7fcccfffa948e55fac67a203a3a Mon Sep 17 00:00:00 2001 From: Martin Hauser Date: Thu, 28 May 2026 16:57:45 +0200 Subject: [PATCH] test(extras): Use cleanup handlers for config test teardown Replace manual `clear_config()` and `cache.clear()` calls at test end with `addCleanup()` registered in `setUp()`. Ensures cleanup runs even if assertions fail mid-test, preventing Redis pollution across tests. Fixes #22290 --- netbox/netbox/tests/test_config.py | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/netbox/netbox/tests/test_config.py b/netbox/netbox/tests/test_config.py index ebdfdb166..4d2a0345e 100644 --- a/netbox/netbox/tests/test_config.py +++ b/netbox/netbox/tests/test_config.py @@ -10,22 +10,28 @@ CACHES = settings.CACHES CACHES['default'].update({'KEY_PREFIX': 'TEST-'}) +@override_settings(CACHES=CACHES) class ConfigTestCase(TestCase): - @override_settings(CACHES=CACHES) - def test_config_init_empty(self): + def setUp(self): + super().setUp() + # Register cleanup so it runs after each test, even on assertion failure. + # clear_config drops the thread-local Config; cache.clear wipes the Redis + # entries that configrevision.activate writes. + self.addCleanup(cache.clear) + self.addCleanup(clear_config) + + # Defensive reset against pre-existing state from outside this class. + clear_config() cache.clear() + def test_config_init_empty(self): config = get_config() self.assertEqual(config.config, {}) self.assertEqual(config.version, None) - clear_config() - - @override_settings(CACHES=CACHES) def test_config_init_from_db(self): CONFIG_DATA = {'BANNER_TOP': 'A'} - cache.clear() # Create a config but don't load it into the cache configrevision = ConfigRevision.objects.create(data=CONFIG_DATA) @@ -34,12 +40,8 @@ class ConfigTestCase(TestCase): self.assertEqual(config.config, CONFIG_DATA) self.assertEqual(config.version, configrevision.pk) - clear_config() - - @override_settings(CACHES=CACHES) def test_config_init_from_cache(self): CONFIG_DATA = {'BANNER_TOP': 'B'} - cache.clear() # Create a config and load it into the cache configrevision = ConfigRevision.objects.create(data=CONFIG_DATA) @@ -49,12 +51,9 @@ class ConfigTestCase(TestCase): self.assertEqual(config.config, CONFIG_DATA) self.assertEqual(config.version, configrevision.pk) - clear_config() - - @override_settings(CACHES=CACHES, BANNER_TOP='Z') + @override_settings(BANNER_TOP='Z') def test_settings_override(self): CONFIG_DATA = {'BANNER_TOP': 'A'} - cache.clear() # Create a config and load it into the cache configrevision = ConfigRevision.objects.create(data=CONFIG_DATA) @@ -63,5 +62,3 @@ class ConfigTestCase(TestCase): config = get_config() self.assertEqual(config.BANNER_TOP, 'Z') self.assertEqual(config.version, configrevision.pk) - - clear_config()