1- from collections .abc import Iterator
21import contextlib
32import importlib
43import io
@@ -1462,6 +1461,7 @@ def test_parse_error(self):
14621461 with self .subTest (code = code ):
14631462 self .assertEqual (actual , None )
14641463
1464+ @patch .dict (sys .modules )
14651465 def test_suggestions_and_messages (self ) -> None :
14661466 # more unitary tests checking the exact suggestions provided
14671467 # (sorting, de-duplication, import action...)
@@ -1522,27 +1522,27 @@ def test_suggestions_and_messages(self) -> None:
15221522 new_imports = sys .modules .keys () - _imported
15231523 self .assertSetEqual (new_imports , expected_imports )
15241524
1525- class TestModuleCompleterAutomaticImports (TestCase ):
1526- """Out of TestPyReplModuleCompleter case because it blocks module import."""
1527-
1528- @classmethod
1529- def setUpClass (cls ) -> None :
1530- super ().setUpClass ()
1531- cls ._audit_events : set [str ] | None = None
1532- def _hook (name : str , _args : tuple ):
1533- if cls ._audit_events is not None :
1534- cls ._audit_events .add (name )
1535- sys .addaudithook (_hook )
1536-
1537- @classmethod
1538- @contextlib .contextmanager
1539- def _capture_audit_events (cls ) -> Iterator [set [str ]]:
1540- cls ._audit_events = set ()
1541- try :
1542- yield cls ._audit_events
1543- finally :
1544- cls ._audit_events = None
15451525
1526+ # Audit hook used to check for stdlib modules import side-effects
1527+ # Defined globally to avoid adding one hook per test run (refleak)
1528+ _audit_events : set [str ] | None = None
1529+ def _hook (name : str , _args : tuple ):
1530+ if _audit_events is not None : # No-op when not activated
1531+ _audit_events .add (name )
1532+ sys .addaudithook (_hook )
1533+
1534+
1535+ @contextlib .contextmanager
1536+ def _capture_audit_events ():
1537+ global _audit_events
1538+ _audit_events = set ()
1539+ try :
1540+ yield _audit_events
1541+ finally :
1542+ _audit_events = None
1543+
1544+
1545+ class TestModuleCompleterAutomaticImports (TestCase ):
15461546 def test_no_side_effects (self ):
15471547 from test .test___all__ import AllTest # TODO: extract to a helper?
15481548
@@ -1551,11 +1551,10 @@ def test_no_side_effects(self):
15511551 with self .subTest (modname = modname ):
15521552 with (captured_stdout () as out ,
15531553 captured_stderr () as err ,
1554- self . _capture_audit_events () as audit_events ,
1554+ _capture_audit_events () as audit_events ,
15551555 (patch ("tkinter._tkinter.create" ) if tkinter
15561556 else contextlib .nullcontext ()) as tk_mock ,
1557- warnings .catch_warnings (action = "ignore" ),
1558- patch .dict (sys .modules )):
1557+ warnings .catch_warnings (action = "ignore" )):
15591558 completer ._maybe_import_module (modname )
15601559 # Test no module is imported that
15611560 # 1. prints any text
0 commit comments