Debian Codegraph @

Lib/test/support/warnings_helper.py

raw
1 import contextlib
2 import functools
3 import importlib
4 import re
5 import sys
6 import warnings
7
8
9 def import_deprecated(name):
10 """Import *name* while suppressing DeprecationWarning."""
11 with warnings.catch_warnings():
12 warnings.simplefilter('ignore', category=DeprecationWarning)
13 return importlib.import_module(name)
14
15
16 def check_syntax_warning(testcase, statement, errtext='',
17 *, lineno=1, offset=None):
18 # Test also that a warning is emitted only once.
19 from test.support import check_syntax_error
20 with warnings.catch_warnings(record=True) as warns:
21 warnings.simplefilter('always', SyntaxWarning)
22 compile(statement, '<testcase>', 'exec')
23 testcase.assertEqual(len(warns), 1, warns)
24
25 warn, = warns
26 testcase.assertIsSubclass(warn.category, SyntaxWarning)
27 if errtext:
28 testcase.assertRegex(str(warn.message), errtext)
29 testcase.assertEqual(warn.filename, '<testcase>')
30 testcase.assertIsNotNone(warn.lineno)
31 if lineno is not None:
32 testcase.assertEqual(warn.lineno, lineno)
33
34 # SyntaxWarning should be converted to SyntaxError when raised,
35 # since the latter contains more information and provides better
36 # error report.
37 with warnings.catch_warnings(record=True) as warns:
38 warnings.simplefilter('error', SyntaxWarning)
39 check_syntax_error(testcase, statement, errtext,
40 lineno=lineno, offset=offset)
41 # No warnings are leaked when a SyntaxError is raised.
42 testcase.assertEqual(warns, [])
43
44
45 def ignore_warnings(*, category):
46 """Decorator to suppress warnings.
47
48 Use of context managers to hide warnings make diffs
49 more noisy and tools like 'git blame' less useful.
50 """
51 def decorator(test):
52 @functools.wraps(test)
53 def wrapper(self, *args, **kwargs):
54 with warnings.catch_warnings():
55 warnings.simplefilter('ignore', category=category)
56 return test(self, *args, **kwargs)
57 return wrapper
58 return decorator
59
60
61 class WarningsRecorder(object):
62 """Convenience wrapper for the warnings list returned on
63 entry to the warnings.catch_warnings() context manager.
64 """
65 def __init__(self, warnings_list):
66 self._warnings = warnings_list
67 self._last = 0
68
69 def __getattr__(self, attr):
70 if len(self._warnings) > self._last:
71 return getattr(self._warnings[-1], attr)
72 elif attr in warnings.WarningMessage._WARNING_DETAILS:
73 return None
74 raise AttributeError("%r has no attribute %r" % (self, attr))
75
76 @property
77 def warnings(self):
78 return self._warnings[self._last:]
79
80 def reset(self):
81 self._last = len(self._warnings)
82
83
84 @contextlib.contextmanager
85 def check_warnings(*filters, **kwargs):
86 """Context manager to silence warnings.
87
88 Accept 2-tuples as positional arguments:
89 ("message regexp", WarningCategory)
90
91 Optional argument:
92 - if 'quiet' is True, it does not fail if a filter catches nothing
93 (default True without argument,
94 default False if some filters are defined)
95
96 Without argument, it defaults to:
97 check_warnings(("", Warning), quiet=True)
98 """
99 quiet = kwargs.get('quiet')
100 if not filters:
101 filters = (("", Warning),)
102 # Preserve backward compatibility
103 if quiet is None:
104 quiet = True
105 return _filterwarnings(filters, quiet)
106
107
108 @contextlib.contextmanager
109 def check_no_warnings(testcase, message='', category=Warning, force_gc=False):
110 """Context manager to check that no warnings are emitted.
111
112 This context manager enables a given warning within its scope
113 and checks that no warnings are emitted even with that warning
114 enabled.
115
116 If force_gc is True, a garbage collection is attempted before checking
117 for warnings. This may help to catch warnings emitted when objects
118 are deleted, such as ResourceWarning.
119
120 Other keyword arguments are passed to warnings.filterwarnings().
121 """
122 from test.support import gc_collect
123 with warnings.catch_warnings(record=True) as warns:
124 warnings.filterwarnings('always',
125 message=message,
126 category=category)
127 yield
128 if force_gc:
129 gc_collect()
130 testcase.assertEqual(warns, [])
131
132
133 @contextlib.contextmanager
134 def check_no_resource_warning(testcase):
135 """Context manager to check that no ResourceWarning is emitted.
136
137 Usage:
138
139 with check_no_resource_warning(self):
140 f = open(...)
141 ...
142 del f
143
144 You must remove the object which may emit ResourceWarning before
145 the end of the context manager.
146 """
147 with check_no_warnings(testcase, category=ResourceWarning, force_gc=True):
148 yield
149
150
151 def _filterwarnings(filters, quiet=False):
152 """Catch the warnings, then check if all the expected
153 warnings have been raised and re-raise unexpected warnings.
154 If 'quiet' is True, only re-raise the unexpected warnings.
155 """
156 # Clear the warning registry of the calling module
157 # in order to re-raise the warnings.
158 frame = sys._getframe(2)
159 registry = frame.f_globals.get('__warningregistry__')
160 if registry:
161 registry.clear()
162 # Because test_warnings swap the module, we need to look up in the
163 # sys.modules dictionary.
164 wmod = sys.modules['warnings']
165 with wmod.catch_warnings(record=True) as w:
166 # Set filter "always" to record all warnings.
167 wmod.simplefilter("always")
168 yield WarningsRecorder(w)
169 # Filter the recorded warnings
170 reraise = list(w)
171 missing = []
172 for msg, cat in filters:
173 seen = False
174 for w in reraise[:]:
175 warning = w.message
176 # Filter out the matching messages
177 if (re.match(msg, str(warning), re.I) and
178 issubclass(warning.__class__, cat)):
179 seen = True
180 reraise.remove(w)
181 if not seen and not quiet:
182 # This filter caught nothing
183 missing.append((msg, cat.__name__))
184 if reraise:
185 raise AssertionError("unhandled warning %s" % reraise[0])
186 if missing:
187 raise AssertionError("filter (%r, %s) did not catch any warning" %
188 missing[0])
189
190
191 @contextlib.contextmanager
192 def save_restore_warnings_filters():
193 old_filters = warnings.filters[:]
194 try:
195 yield
196 finally:
197 warnings.filters[:] = old_filters
198
199
200 def _warn_about_deprecation():
201 warnings.warn(
202 "This is used in test_support test to ensure"
203 " support.ignore_deprecations_from() works as expected."
204 " You should not be seeing this.",
205 DeprecationWarning,
206 stacklevel=0,
207 )