@@ -410,13 +410,16 @@ def test_message_matching(self):
410410 self .assertEqual (w , [])
411411
412412 def test_mutate_filter_list (self ):
413- class X :
414- def match (self , a , start = 0 ):
415- L [:] = []
416-
417- L = [("default" ,X (),UserWarning ,X (),0 ) for i in range (2 )]
418413 with self .module .catch_warnings (record = True ) as w :
419- self .module .filters = L
414+ # In context-aware mode the active filter list is the current
415+ # context's own list, not warnings.filters, so mutate that list
416+ # directly. (Assigning warnings.filters would leave the ambient
417+ # filters -- e.g. an "error" filter from -W error -- in effect.)
418+ L = self .module ._get_filters ()
419+ class X :
420+ def match (self , a , start = 0 ):
421+ L [:] = []
422+ L [:] = [("default" ,X (),UserWarning ,X (),0 ) for i in range (2 )]
420423 self .module .warn_explicit (UserWarning ("b" ), None , "f.py" , 42 )
421424 self .assertEqual (str (w [- 1 ].message ), "b" )
422425
@@ -1720,8 +1723,22 @@ class AsyncTests(BaseTest):
17201723
17211724 def setUp (self ):
17221725 super ().setUp ()
1726+ # Reset the filters for this test, but restore the module's filter list
1727+ # in tearDown. These tests exercise the C 'warnings' module, whose
1728+ # filters list is the interpreter-global one that regrtest checks for
1729+ # modification; leaving it cleared triggers a spurious "env changed".
1730+ # Save and restore the list contents directly rather than using
1731+ # catch_warnings(): that manipulates the warnings context variable and,
1732+ # combined with the threads/tasks these tests spawn, can leave a stale
1733+ # context active for later tests.
1734+ self ._saved_filters = self .module .filters [:]
17231735 self .module .resetwarnings ()
17241736
1737+ def tearDown (self ):
1738+ self .module .filters [:] = self ._saved_filters
1739+ self .module ._filters_mutated ()
1740+ super ().tearDown ()
1741+
17251742 @unittest .skipIf (not sys .flags .context_aware_warnings ,
17261743 "requires context aware warnings" )
17271744 def test_async_context (self ):
@@ -1816,8 +1833,15 @@ class ThreadTests(BaseTest):
18161833
18171834 def setUp (self ):
18181835 super ().setUp ()
1836+ self ._saved_filters = self .module .filters [:]
18191837 self .module .resetwarnings ()
18201838
1839+ def tearDown (self ):
1840+ # Restore module filters after test run to ensure a clean global state
1841+ self .module .filters [:] = self ._saved_filters
1842+ self .module ._filters_mutated ()
1843+ super ().tearDown ()
1844+
18211845 @unittest .skipIf (not ENABLE_THREAD_TESTS ,
18221846 "requires thread-safe warnings flags" )
18231847 def test_threaded_context (self ):
0 commit comments