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
This commit is contained in:
Martin Hauser 2026-05-28 16:57:45 +02:00 committed by Jeremy Stretch
parent 4b1dc729e0
commit 9930245f44
1 changed files with 13 additions and 16 deletions

View File

@ -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()