diff --git a/Lib/test/support/warnings_helper.py b/Lib/test/support/warnings_helper.py index c046f39fbff511d..93b3053a0100890 100644 --- a/Lib/test/support/warnings_helper.py +++ b/Lib/test/support/warnings_helper.py @@ -173,7 +173,7 @@ def _filterwarnings(filters, quiet=False): registry.clear() # Because test_warnings swap the module, we need to look up in the # sys.modules dictionary. - wmod = sys.modules['warnings'] + wmod = sys.modules.get('warnings', warnings) with wmod.catch_warnings(record=True) as w: # Set filter "always" to record all warnings. wmod.simplefilter("always") diff --git a/Lib/test/test_warnings_helper.py b/Lib/test/test_warnings_helper.py new file mode 100644 index 000000000000000..14f3cb79ef97215 --- /dev/null +++ b/Lib/test/test_warnings_helper.py @@ -0,0 +1,29 @@ +import sys +import unittest +from contextlib import contextmanager +from unittest.mock import patch + +from test.support import warnings_helper + + +class WarningsHelperTests(unittest.TestCase): + def test_check_warnings_when_module_is_not_in_sys_modules(self): + warnings_module = sys.modules.pop("warnings", None) + try: + @contextmanager + def catch_warnings(*, record): + self.assertTrue(record) + yield [] + + with patch.object( + warnings_helper.warnings, "catch_warnings", catch_warnings + ): + with warnings_helper.check_warnings(quiet=True): + pass + finally: + if warnings_module is not None: + sys.modules["warnings"] = warnings_module + + +if __name__ == "__main__": + unittest.main() diff --git a/Misc/NEWS.d/next/Tests/2026-08-29-20-15-00.gh-issue-156570.codex.rst b/Misc/NEWS.d/next/Tests/2026-08-29-20-15-00.gh-issue-156570.codex.rst new file mode 100644 index 000000000000000..3a7cd1492a3f855 --- /dev/null +++ b/Misc/NEWS.d/next/Tests/2026-08-29-20-15-00.gh-issue-156570.codex.rst @@ -0,0 +1,2 @@ +Fix ``test.support.warnings_helper.check_warnings()`` failing with a +``KeyError`` when lazy imports have not populated ``sys.modules``.