Skip to content

Commit ce340bc

Browse files
committed
gh-156570: handle lazy warnings import in test helper
1 parent f973bd9 commit ce340bc

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

Lib/test/support/warnings_helper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def _filterwarnings(filters, quiet=False):
173173
registry.clear()
174174
# Because test_warnings swap the module, we need to look up in the
175175
# sys.modules dictionary.
176-
wmod = sys.modules['warnings']
176+
wmod = sys.modules.get('warnings', warnings)
177177
with wmod.catch_warnings(record=True) as w:
178178
# Set filter "always" to record all warnings.
179179
wmod.simplefilter("always")

Lib/test/test_warnings_helper.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import sys
2+
import unittest
3+
from contextlib import contextmanager
4+
from unittest.mock import patch
5+
6+
from test.support import warnings_helper
7+
8+
9+
class WarningsHelperTests(unittest.TestCase):
10+
def test_check_warnings_when_module_is_not_in_sys_modules(self):
11+
warnings_module = sys.modules.pop("warnings", None)
12+
try:
13+
@contextmanager
14+
def catch_warnings(*, record):
15+
self.assertTrue(record)
16+
yield []
17+
18+
with patch.object(
19+
warnings_helper.warnings, "catch_warnings", catch_warnings
20+
):
21+
with warnings_helper.check_warnings(quiet=True):
22+
pass
23+
finally:
24+
if warnings_module is not None:
25+
sys.modules["warnings"] = warnings_module
26+
27+
28+
if __name__ == "__main__":
29+
unittest.main()

0 commit comments

Comments
 (0)