1 | n/a | from contextlib import contextmanager |
---|
2 | n/a | import linecache |
---|
3 | n/a | import os |
---|
4 | n/a | from io import StringIO |
---|
5 | n/a | import re |
---|
6 | n/a | import sys |
---|
7 | n/a | import textwrap |
---|
8 | n/a | import unittest |
---|
9 | n/a | from test import support |
---|
10 | n/a | from test.support.script_helper import assert_python_ok, assert_python_failure |
---|
11 | n/a | |
---|
12 | n/a | from test.test_warnings.data import stacklevel as warning_tests |
---|
13 | n/a | |
---|
14 | n/a | import warnings as original_warnings |
---|
15 | n/a | |
---|
16 | n/a | py_warnings = support.import_fresh_module('warnings', blocked=['_warnings']) |
---|
17 | n/a | c_warnings = support.import_fresh_module('warnings', fresh=['_warnings']) |
---|
18 | n/a | |
---|
19 | n/a | @contextmanager |
---|
20 | n/a | def warnings_state(module): |
---|
21 | n/a | """Use a specific warnings implementation in warning_tests.""" |
---|
22 | n/a | global __warningregistry__ |
---|
23 | n/a | for to_clear in (sys, warning_tests): |
---|
24 | n/a | try: |
---|
25 | n/a | to_clear.__warningregistry__.clear() |
---|
26 | n/a | except AttributeError: |
---|
27 | n/a | pass |
---|
28 | n/a | try: |
---|
29 | n/a | __warningregistry__.clear() |
---|
30 | n/a | except NameError: |
---|
31 | n/a | pass |
---|
32 | n/a | original_warnings = warning_tests.warnings |
---|
33 | n/a | original_filters = module.filters |
---|
34 | n/a | try: |
---|
35 | n/a | module.filters = original_filters[:] |
---|
36 | n/a | module.simplefilter("once") |
---|
37 | n/a | warning_tests.warnings = module |
---|
38 | n/a | yield |
---|
39 | n/a | finally: |
---|
40 | n/a | warning_tests.warnings = original_warnings |
---|
41 | n/a | module.filters = original_filters |
---|
42 | n/a | |
---|
43 | n/a | |
---|
44 | n/a | class BaseTest: |
---|
45 | n/a | |
---|
46 | n/a | """Basic bookkeeping required for testing.""" |
---|
47 | n/a | |
---|
48 | n/a | def setUp(self): |
---|
49 | n/a | self.old_unittest_module = unittest.case.warnings |
---|
50 | n/a | # The __warningregistry__ needs to be in a pristine state for tests |
---|
51 | n/a | # to work properly. |
---|
52 | n/a | if '__warningregistry__' in globals(): |
---|
53 | n/a | del globals()['__warningregistry__'] |
---|
54 | n/a | if hasattr(warning_tests, '__warningregistry__'): |
---|
55 | n/a | del warning_tests.__warningregistry__ |
---|
56 | n/a | if hasattr(sys, '__warningregistry__'): |
---|
57 | n/a | del sys.__warningregistry__ |
---|
58 | n/a | # The 'warnings' module must be explicitly set so that the proper |
---|
59 | n/a | # interaction between _warnings and 'warnings' can be controlled. |
---|
60 | n/a | sys.modules['warnings'] = self.module |
---|
61 | n/a | # Ensure that unittest.TestCase.assertWarns() uses the same warnings |
---|
62 | n/a | # module than warnings.catch_warnings(). Otherwise, |
---|
63 | n/a | # warnings.catch_warnings() will be unable to remove the added filter. |
---|
64 | n/a | unittest.case.warnings = self.module |
---|
65 | n/a | super(BaseTest, self).setUp() |
---|
66 | n/a | |
---|
67 | n/a | def tearDown(self): |
---|
68 | n/a | sys.modules['warnings'] = original_warnings |
---|
69 | n/a | unittest.case.warnings = self.old_unittest_module |
---|
70 | n/a | super(BaseTest, self).tearDown() |
---|
71 | n/a | |
---|
72 | n/a | class PublicAPITests(BaseTest): |
---|
73 | n/a | |
---|
74 | n/a | """Ensures that the correct values are exposed in the |
---|
75 | n/a | public API. |
---|
76 | n/a | """ |
---|
77 | n/a | |
---|
78 | n/a | def test_module_all_attribute(self): |
---|
79 | n/a | self.assertTrue(hasattr(self.module, '__all__')) |
---|
80 | n/a | target_api = ["warn", "warn_explicit", "showwarning", |
---|
81 | n/a | "formatwarning", "filterwarnings", "simplefilter", |
---|
82 | n/a | "resetwarnings", "catch_warnings"] |
---|
83 | n/a | self.assertSetEqual(set(self.module.__all__), |
---|
84 | n/a | set(target_api)) |
---|
85 | n/a | |
---|
86 | n/a | class CPublicAPITests(PublicAPITests, unittest.TestCase): |
---|
87 | n/a | module = c_warnings |
---|
88 | n/a | |
---|
89 | n/a | class PyPublicAPITests(PublicAPITests, unittest.TestCase): |
---|
90 | n/a | module = py_warnings |
---|
91 | n/a | |
---|
92 | n/a | class FilterTests(BaseTest): |
---|
93 | n/a | |
---|
94 | n/a | """Testing the filtering functionality.""" |
---|
95 | n/a | |
---|
96 | n/a | def test_error(self): |
---|
97 | n/a | with original_warnings.catch_warnings(module=self.module) as w: |
---|
98 | n/a | self.module.resetwarnings() |
---|
99 | n/a | self.module.filterwarnings("error", category=UserWarning) |
---|
100 | n/a | self.assertRaises(UserWarning, self.module.warn, |
---|
101 | n/a | "FilterTests.test_error") |
---|
102 | n/a | |
---|
103 | n/a | def test_error_after_default(self): |
---|
104 | n/a | with original_warnings.catch_warnings(module=self.module) as w: |
---|
105 | n/a | self.module.resetwarnings() |
---|
106 | n/a | message = "FilterTests.test_ignore_after_default" |
---|
107 | n/a | def f(): |
---|
108 | n/a | self.module.warn(message, UserWarning) |
---|
109 | n/a | |
---|
110 | n/a | with support.captured_stderr() as stderr: |
---|
111 | n/a | f() |
---|
112 | n/a | stderr = stderr.getvalue() |
---|
113 | n/a | self.assertIn("UserWarning: FilterTests.test_ignore_after_default", |
---|
114 | n/a | stderr) |
---|
115 | n/a | self.assertIn("self.module.warn(message, UserWarning)", |
---|
116 | n/a | stderr) |
---|
117 | n/a | |
---|
118 | n/a | self.module.filterwarnings("error", category=UserWarning) |
---|
119 | n/a | self.assertRaises(UserWarning, f) |
---|
120 | n/a | |
---|
121 | n/a | def test_ignore(self): |
---|
122 | n/a | with original_warnings.catch_warnings(record=True, |
---|
123 | n/a | module=self.module) as w: |
---|
124 | n/a | self.module.resetwarnings() |
---|
125 | n/a | self.module.filterwarnings("ignore", category=UserWarning) |
---|
126 | n/a | self.module.warn("FilterTests.test_ignore", UserWarning) |
---|
127 | n/a | self.assertEqual(len(w), 0) |
---|
128 | n/a | |
---|
129 | n/a | def test_ignore_after_default(self): |
---|
130 | n/a | with original_warnings.catch_warnings(record=True, |
---|
131 | n/a | module=self.module) as w: |
---|
132 | n/a | self.module.resetwarnings() |
---|
133 | n/a | message = "FilterTests.test_ignore_after_default" |
---|
134 | n/a | def f(): |
---|
135 | n/a | self.module.warn(message, UserWarning) |
---|
136 | n/a | f() |
---|
137 | n/a | self.module.filterwarnings("ignore", category=UserWarning) |
---|
138 | n/a | f() |
---|
139 | n/a | f() |
---|
140 | n/a | self.assertEqual(len(w), 1) |
---|
141 | n/a | |
---|
142 | n/a | def test_always(self): |
---|
143 | n/a | with original_warnings.catch_warnings(record=True, |
---|
144 | n/a | module=self.module) as w: |
---|
145 | n/a | self.module.resetwarnings() |
---|
146 | n/a | self.module.filterwarnings("always", category=UserWarning) |
---|
147 | n/a | message = "FilterTests.test_always" |
---|
148 | n/a | self.module.warn(message, UserWarning) |
---|
149 | n/a | self.assertTrue(message, w[-1].message) |
---|
150 | n/a | self.module.warn(message, UserWarning) |
---|
151 | n/a | self.assertTrue(w[-1].message, message) |
---|
152 | n/a | |
---|
153 | n/a | def test_always_after_default(self): |
---|
154 | n/a | with original_warnings.catch_warnings(record=True, |
---|
155 | n/a | module=self.module) as w: |
---|
156 | n/a | self.module.resetwarnings() |
---|
157 | n/a | message = "FilterTests.test_always_after_ignore" |
---|
158 | n/a | def f(): |
---|
159 | n/a | self.module.warn(message, UserWarning) |
---|
160 | n/a | f() |
---|
161 | n/a | self.assertEqual(len(w), 1) |
---|
162 | n/a | self.assertEqual(w[-1].message.args[0], message) |
---|
163 | n/a | f() |
---|
164 | n/a | self.assertEqual(len(w), 1) |
---|
165 | n/a | self.module.filterwarnings("always", category=UserWarning) |
---|
166 | n/a | f() |
---|
167 | n/a | self.assertEqual(len(w), 2) |
---|
168 | n/a | self.assertEqual(w[-1].message.args[0], message) |
---|
169 | n/a | f() |
---|
170 | n/a | self.assertEqual(len(w), 3) |
---|
171 | n/a | self.assertEqual(w[-1].message.args[0], message) |
---|
172 | n/a | |
---|
173 | n/a | def test_default(self): |
---|
174 | n/a | with original_warnings.catch_warnings(record=True, |
---|
175 | n/a | module=self.module) as w: |
---|
176 | n/a | self.module.resetwarnings() |
---|
177 | n/a | self.module.filterwarnings("default", category=UserWarning) |
---|
178 | n/a | message = UserWarning("FilterTests.test_default") |
---|
179 | n/a | for x in range(2): |
---|
180 | n/a | self.module.warn(message, UserWarning) |
---|
181 | n/a | if x == 0: |
---|
182 | n/a | self.assertEqual(w[-1].message, message) |
---|
183 | n/a | del w[:] |
---|
184 | n/a | elif x == 1: |
---|
185 | n/a | self.assertEqual(len(w), 0) |
---|
186 | n/a | else: |
---|
187 | n/a | raise ValueError("loop variant unhandled") |
---|
188 | n/a | |
---|
189 | n/a | def test_module(self): |
---|
190 | n/a | with original_warnings.catch_warnings(record=True, |
---|
191 | n/a | module=self.module) as w: |
---|
192 | n/a | self.module.resetwarnings() |
---|
193 | n/a | self.module.filterwarnings("module", category=UserWarning) |
---|
194 | n/a | message = UserWarning("FilterTests.test_module") |
---|
195 | n/a | self.module.warn(message, UserWarning) |
---|
196 | n/a | self.assertEqual(w[-1].message, message) |
---|
197 | n/a | del w[:] |
---|
198 | n/a | self.module.warn(message, UserWarning) |
---|
199 | n/a | self.assertEqual(len(w), 0) |
---|
200 | n/a | |
---|
201 | n/a | def test_once(self): |
---|
202 | n/a | with original_warnings.catch_warnings(record=True, |
---|
203 | n/a | module=self.module) as w: |
---|
204 | n/a | self.module.resetwarnings() |
---|
205 | n/a | self.module.filterwarnings("once", category=UserWarning) |
---|
206 | n/a | message = UserWarning("FilterTests.test_once") |
---|
207 | n/a | self.module.warn_explicit(message, UserWarning, "__init__.py", |
---|
208 | n/a | 42) |
---|
209 | n/a | self.assertEqual(w[-1].message, message) |
---|
210 | n/a | del w[:] |
---|
211 | n/a | self.module.warn_explicit(message, UserWarning, "__init__.py", |
---|
212 | n/a | 13) |
---|
213 | n/a | self.assertEqual(len(w), 0) |
---|
214 | n/a | self.module.warn_explicit(message, UserWarning, "test_warnings2.py", |
---|
215 | n/a | 42) |
---|
216 | n/a | self.assertEqual(len(w), 0) |
---|
217 | n/a | |
---|
218 | n/a | def test_inheritance(self): |
---|
219 | n/a | with original_warnings.catch_warnings(module=self.module) as w: |
---|
220 | n/a | self.module.resetwarnings() |
---|
221 | n/a | self.module.filterwarnings("error", category=Warning) |
---|
222 | n/a | self.assertRaises(UserWarning, self.module.warn, |
---|
223 | n/a | "FilterTests.test_inheritance", UserWarning) |
---|
224 | n/a | |
---|
225 | n/a | def test_ordering(self): |
---|
226 | n/a | with original_warnings.catch_warnings(record=True, |
---|
227 | n/a | module=self.module) as w: |
---|
228 | n/a | self.module.resetwarnings() |
---|
229 | n/a | self.module.filterwarnings("ignore", category=UserWarning) |
---|
230 | n/a | self.module.filterwarnings("error", category=UserWarning, |
---|
231 | n/a | append=True) |
---|
232 | n/a | del w[:] |
---|
233 | n/a | try: |
---|
234 | n/a | self.module.warn("FilterTests.test_ordering", UserWarning) |
---|
235 | n/a | except UserWarning: |
---|
236 | n/a | self.fail("order handling for actions failed") |
---|
237 | n/a | self.assertEqual(len(w), 0) |
---|
238 | n/a | |
---|
239 | n/a | def test_filterwarnings(self): |
---|
240 | n/a | # Test filterwarnings(). |
---|
241 | n/a | # Implicitly also tests resetwarnings(). |
---|
242 | n/a | with original_warnings.catch_warnings(record=True, |
---|
243 | n/a | module=self.module) as w: |
---|
244 | n/a | self.module.filterwarnings("error", "", Warning, "", 0) |
---|
245 | n/a | self.assertRaises(UserWarning, self.module.warn, 'convert to error') |
---|
246 | n/a | |
---|
247 | n/a | self.module.resetwarnings() |
---|
248 | n/a | text = 'handle normally' |
---|
249 | n/a | self.module.warn(text) |
---|
250 | n/a | self.assertEqual(str(w[-1].message), text) |
---|
251 | n/a | self.assertTrue(w[-1].category is UserWarning) |
---|
252 | n/a | |
---|
253 | n/a | self.module.filterwarnings("ignore", "", Warning, "", 0) |
---|
254 | n/a | text = 'filtered out' |
---|
255 | n/a | self.module.warn(text) |
---|
256 | n/a | self.assertNotEqual(str(w[-1].message), text) |
---|
257 | n/a | |
---|
258 | n/a | self.module.resetwarnings() |
---|
259 | n/a | self.module.filterwarnings("error", "hex*", Warning, "", 0) |
---|
260 | n/a | self.assertRaises(UserWarning, self.module.warn, 'hex/oct') |
---|
261 | n/a | text = 'nonmatching text' |
---|
262 | n/a | self.module.warn(text) |
---|
263 | n/a | self.assertEqual(str(w[-1].message), text) |
---|
264 | n/a | self.assertTrue(w[-1].category is UserWarning) |
---|
265 | n/a | |
---|
266 | n/a | def test_message_matching(self): |
---|
267 | n/a | with original_warnings.catch_warnings(record=True, |
---|
268 | n/a | module=self.module) as w: |
---|
269 | n/a | self.module.simplefilter("ignore", UserWarning) |
---|
270 | n/a | self.module.filterwarnings("error", "match", UserWarning) |
---|
271 | n/a | self.assertRaises(UserWarning, self.module.warn, "match") |
---|
272 | n/a | self.assertRaises(UserWarning, self.module.warn, "match prefix") |
---|
273 | n/a | self.module.warn("suffix match") |
---|
274 | n/a | self.assertEqual(w, []) |
---|
275 | n/a | self.module.warn("something completely different") |
---|
276 | n/a | self.assertEqual(w, []) |
---|
277 | n/a | |
---|
278 | n/a | def test_mutate_filter_list(self): |
---|
279 | n/a | class X: |
---|
280 | n/a | def match(self, a): |
---|
281 | n/a | L[:] = [] |
---|
282 | n/a | |
---|
283 | n/a | L = [("default",X(),UserWarning,X(),0) for i in range(2)] |
---|
284 | n/a | with original_warnings.catch_warnings(record=True, |
---|
285 | n/a | module=self.module) as w: |
---|
286 | n/a | self.module.filters = L |
---|
287 | n/a | self.module.warn_explicit(UserWarning("b"), None, "f.py", 42) |
---|
288 | n/a | self.assertEqual(str(w[-1].message), "b") |
---|
289 | n/a | |
---|
290 | n/a | def test_filterwarnings_duplicate_filters(self): |
---|
291 | n/a | with original_warnings.catch_warnings(module=self.module): |
---|
292 | n/a | self.module.resetwarnings() |
---|
293 | n/a | self.module.filterwarnings("error", category=UserWarning) |
---|
294 | n/a | self.assertEqual(len(self.module.filters), 1) |
---|
295 | n/a | self.module.filterwarnings("ignore", category=UserWarning) |
---|
296 | n/a | self.module.filterwarnings("error", category=UserWarning) |
---|
297 | n/a | self.assertEqual( |
---|
298 | n/a | len(self.module.filters), 2, |
---|
299 | n/a | "filterwarnings inserted duplicate filter" |
---|
300 | n/a | ) |
---|
301 | n/a | self.assertEqual( |
---|
302 | n/a | self.module.filters[0][0], "error", |
---|
303 | n/a | "filterwarnings did not promote filter to " |
---|
304 | n/a | "the beginning of list" |
---|
305 | n/a | ) |
---|
306 | n/a | |
---|
307 | n/a | def test_simplefilter_duplicate_filters(self): |
---|
308 | n/a | with original_warnings.catch_warnings(module=self.module): |
---|
309 | n/a | self.module.resetwarnings() |
---|
310 | n/a | self.module.simplefilter("error", category=UserWarning) |
---|
311 | n/a | self.assertEqual(len(self.module.filters), 1) |
---|
312 | n/a | self.module.simplefilter("ignore", category=UserWarning) |
---|
313 | n/a | self.module.simplefilter("error", category=UserWarning) |
---|
314 | n/a | self.assertEqual( |
---|
315 | n/a | len(self.module.filters), 2, |
---|
316 | n/a | "simplefilter inserted duplicate filter" |
---|
317 | n/a | ) |
---|
318 | n/a | self.assertEqual( |
---|
319 | n/a | self.module.filters[0][0], "error", |
---|
320 | n/a | "simplefilter did not promote filter to the beginning of list" |
---|
321 | n/a | ) |
---|
322 | n/a | def test_append_duplicate(self): |
---|
323 | n/a | with original_warnings.catch_warnings(module=self.module, |
---|
324 | n/a | record=True) as w: |
---|
325 | n/a | self.module.resetwarnings() |
---|
326 | n/a | self.module.simplefilter("ignore") |
---|
327 | n/a | self.module.simplefilter("error", append=True) |
---|
328 | n/a | self.module.simplefilter("ignore", append=True) |
---|
329 | n/a | self.module.warn("test_append_duplicate", category=UserWarning) |
---|
330 | n/a | self.assertEqual(len(self.module.filters), 2, |
---|
331 | n/a | "simplefilter inserted duplicate filter" |
---|
332 | n/a | ) |
---|
333 | n/a | self.assertEqual(len(w), 0, |
---|
334 | n/a | "appended duplicate changed order of filters" |
---|
335 | n/a | ) |
---|
336 | n/a | |
---|
337 | n/a | class CFilterTests(FilterTests, unittest.TestCase): |
---|
338 | n/a | module = c_warnings |
---|
339 | n/a | |
---|
340 | n/a | class PyFilterTests(FilterTests, unittest.TestCase): |
---|
341 | n/a | module = py_warnings |
---|
342 | n/a | |
---|
343 | n/a | |
---|
344 | n/a | class WarnTests(BaseTest): |
---|
345 | n/a | |
---|
346 | n/a | """Test warnings.warn() and warnings.warn_explicit().""" |
---|
347 | n/a | |
---|
348 | n/a | def test_message(self): |
---|
349 | n/a | with original_warnings.catch_warnings(record=True, |
---|
350 | n/a | module=self.module) as w: |
---|
351 | n/a | self.module.simplefilter("once") |
---|
352 | n/a | for i in range(4): |
---|
353 | n/a | text = 'multi %d' %i # Different text on each call. |
---|
354 | n/a | self.module.warn(text) |
---|
355 | n/a | self.assertEqual(str(w[-1].message), text) |
---|
356 | n/a | self.assertTrue(w[-1].category is UserWarning) |
---|
357 | n/a | |
---|
358 | n/a | # Issue 3639 |
---|
359 | n/a | def test_warn_nonstandard_types(self): |
---|
360 | n/a | # warn() should handle non-standard types without issue. |
---|
361 | n/a | for ob in (Warning, None, 42): |
---|
362 | n/a | with original_warnings.catch_warnings(record=True, |
---|
363 | n/a | module=self.module) as w: |
---|
364 | n/a | self.module.simplefilter("once") |
---|
365 | n/a | self.module.warn(ob) |
---|
366 | n/a | # Don't directly compare objects since |
---|
367 | n/a | # ``Warning() != Warning()``. |
---|
368 | n/a | self.assertEqual(str(w[-1].message), str(UserWarning(ob))) |
---|
369 | n/a | |
---|
370 | n/a | def test_filename(self): |
---|
371 | n/a | with warnings_state(self.module): |
---|
372 | n/a | with original_warnings.catch_warnings(record=True, |
---|
373 | n/a | module=self.module) as w: |
---|
374 | n/a | warning_tests.inner("spam1") |
---|
375 | n/a | self.assertEqual(os.path.basename(w[-1].filename), |
---|
376 | n/a | "stacklevel.py") |
---|
377 | n/a | warning_tests.outer("spam2") |
---|
378 | n/a | self.assertEqual(os.path.basename(w[-1].filename), |
---|
379 | n/a | "stacklevel.py") |
---|
380 | n/a | |
---|
381 | n/a | def test_stacklevel(self): |
---|
382 | n/a | # Test stacklevel argument |
---|
383 | n/a | # make sure all messages are different, so the warning won't be skipped |
---|
384 | n/a | with warnings_state(self.module): |
---|
385 | n/a | with original_warnings.catch_warnings(record=True, |
---|
386 | n/a | module=self.module) as w: |
---|
387 | n/a | warning_tests.inner("spam3", stacklevel=1) |
---|
388 | n/a | self.assertEqual(os.path.basename(w[-1].filename), |
---|
389 | n/a | "stacklevel.py") |
---|
390 | n/a | warning_tests.outer("spam4", stacklevel=1) |
---|
391 | n/a | self.assertEqual(os.path.basename(w[-1].filename), |
---|
392 | n/a | "stacklevel.py") |
---|
393 | n/a | |
---|
394 | n/a | warning_tests.inner("spam5", stacklevel=2) |
---|
395 | n/a | self.assertEqual(os.path.basename(w[-1].filename), |
---|
396 | n/a | "__init__.py") |
---|
397 | n/a | warning_tests.outer("spam6", stacklevel=2) |
---|
398 | n/a | self.assertEqual(os.path.basename(w[-1].filename), |
---|
399 | n/a | "stacklevel.py") |
---|
400 | n/a | warning_tests.outer("spam6.5", stacklevel=3) |
---|
401 | n/a | self.assertEqual(os.path.basename(w[-1].filename), |
---|
402 | n/a | "__init__.py") |
---|
403 | n/a | |
---|
404 | n/a | warning_tests.inner("spam7", stacklevel=9999) |
---|
405 | n/a | self.assertEqual(os.path.basename(w[-1].filename), |
---|
406 | n/a | "sys") |
---|
407 | n/a | |
---|
408 | n/a | def test_stacklevel_import(self): |
---|
409 | n/a | # Issue #24305: With stacklevel=2, module-level warnings should work. |
---|
410 | n/a | support.unload('test.test_warnings.data.import_warning') |
---|
411 | n/a | with warnings_state(self.module): |
---|
412 | n/a | with original_warnings.catch_warnings(record=True, |
---|
413 | n/a | module=self.module) as w: |
---|
414 | n/a | self.module.simplefilter('always') |
---|
415 | n/a | import test.test_warnings.data.import_warning |
---|
416 | n/a | self.assertEqual(len(w), 1) |
---|
417 | n/a | self.assertEqual(w[0].filename, __file__) |
---|
418 | n/a | |
---|
419 | n/a | def test_missing_filename_not_main(self): |
---|
420 | n/a | # If __file__ is not specified and __main__ is not the module name, |
---|
421 | n/a | # then __file__ should be set to the module name. |
---|
422 | n/a | filename = warning_tests.__file__ |
---|
423 | n/a | try: |
---|
424 | n/a | del warning_tests.__file__ |
---|
425 | n/a | with warnings_state(self.module): |
---|
426 | n/a | with original_warnings.catch_warnings(record=True, |
---|
427 | n/a | module=self.module) as w: |
---|
428 | n/a | warning_tests.inner("spam8", stacklevel=1) |
---|
429 | n/a | self.assertEqual(w[-1].filename, warning_tests.__name__) |
---|
430 | n/a | finally: |
---|
431 | n/a | warning_tests.__file__ = filename |
---|
432 | n/a | |
---|
433 | n/a | @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv') |
---|
434 | n/a | def test_missing_filename_main_with_argv(self): |
---|
435 | n/a | # If __file__ is not specified and the caller is __main__ and sys.argv |
---|
436 | n/a | # exists, then use sys.argv[0] as the file. |
---|
437 | n/a | filename = warning_tests.__file__ |
---|
438 | n/a | module_name = warning_tests.__name__ |
---|
439 | n/a | try: |
---|
440 | n/a | del warning_tests.__file__ |
---|
441 | n/a | warning_tests.__name__ = '__main__' |
---|
442 | n/a | with warnings_state(self.module): |
---|
443 | n/a | with original_warnings.catch_warnings(record=True, |
---|
444 | n/a | module=self.module) as w: |
---|
445 | n/a | warning_tests.inner('spam9', stacklevel=1) |
---|
446 | n/a | self.assertEqual(w[-1].filename, sys.argv[0]) |
---|
447 | n/a | finally: |
---|
448 | n/a | warning_tests.__file__ = filename |
---|
449 | n/a | warning_tests.__name__ = module_name |
---|
450 | n/a | |
---|
451 | n/a | def test_missing_filename_main_without_argv(self): |
---|
452 | n/a | # If __file__ is not specified, the caller is __main__, and sys.argv |
---|
453 | n/a | # is not set, then '__main__' is the file name. |
---|
454 | n/a | filename = warning_tests.__file__ |
---|
455 | n/a | module_name = warning_tests.__name__ |
---|
456 | n/a | argv = sys.argv |
---|
457 | n/a | try: |
---|
458 | n/a | del warning_tests.__file__ |
---|
459 | n/a | warning_tests.__name__ = '__main__' |
---|
460 | n/a | del sys.argv |
---|
461 | n/a | with warnings_state(self.module): |
---|
462 | n/a | with original_warnings.catch_warnings(record=True, |
---|
463 | n/a | module=self.module) as w: |
---|
464 | n/a | warning_tests.inner('spam10', stacklevel=1) |
---|
465 | n/a | self.assertEqual(w[-1].filename, '__main__') |
---|
466 | n/a | finally: |
---|
467 | n/a | warning_tests.__file__ = filename |
---|
468 | n/a | warning_tests.__name__ = module_name |
---|
469 | n/a | sys.argv = argv |
---|
470 | n/a | |
---|
471 | n/a | def test_missing_filename_main_with_argv_empty_string(self): |
---|
472 | n/a | # If __file__ is not specified, the caller is __main__, and sys.argv[0] |
---|
473 | n/a | # is the empty string, then '__main__ is the file name. |
---|
474 | n/a | # Tests issue 2743. |
---|
475 | n/a | file_name = warning_tests.__file__ |
---|
476 | n/a | module_name = warning_tests.__name__ |
---|
477 | n/a | argv = sys.argv |
---|
478 | n/a | try: |
---|
479 | n/a | del warning_tests.__file__ |
---|
480 | n/a | warning_tests.__name__ = '__main__' |
---|
481 | n/a | sys.argv = [''] |
---|
482 | n/a | with warnings_state(self.module): |
---|
483 | n/a | with original_warnings.catch_warnings(record=True, |
---|
484 | n/a | module=self.module) as w: |
---|
485 | n/a | warning_tests.inner('spam11', stacklevel=1) |
---|
486 | n/a | self.assertEqual(w[-1].filename, '__main__') |
---|
487 | n/a | finally: |
---|
488 | n/a | warning_tests.__file__ = file_name |
---|
489 | n/a | warning_tests.__name__ = module_name |
---|
490 | n/a | sys.argv = argv |
---|
491 | n/a | |
---|
492 | n/a | def test_warn_explicit_non_ascii_filename(self): |
---|
493 | n/a | with original_warnings.catch_warnings(record=True, |
---|
494 | n/a | module=self.module) as w: |
---|
495 | n/a | self.module.resetwarnings() |
---|
496 | n/a | self.module.filterwarnings("always", category=UserWarning) |
---|
497 | n/a | for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"): |
---|
498 | n/a | try: |
---|
499 | n/a | os.fsencode(filename) |
---|
500 | n/a | except UnicodeEncodeError: |
---|
501 | n/a | continue |
---|
502 | n/a | self.module.warn_explicit("text", UserWarning, filename, 1) |
---|
503 | n/a | self.assertEqual(w[-1].filename, filename) |
---|
504 | n/a | |
---|
505 | n/a | def test_warn_explicit_type_errors(self): |
---|
506 | n/a | # warn_explicit() should error out gracefully if it is given objects |
---|
507 | n/a | # of the wrong types. |
---|
508 | n/a | # lineno is expected to be an integer. |
---|
509 | n/a | self.assertRaises(TypeError, self.module.warn_explicit, |
---|
510 | n/a | None, UserWarning, None, None) |
---|
511 | n/a | # Either 'message' needs to be an instance of Warning or 'category' |
---|
512 | n/a | # needs to be a subclass. |
---|
513 | n/a | self.assertRaises(TypeError, self.module.warn_explicit, |
---|
514 | n/a | None, None, None, 1) |
---|
515 | n/a | # 'registry' must be a dict or None. |
---|
516 | n/a | self.assertRaises((TypeError, AttributeError), |
---|
517 | n/a | self.module.warn_explicit, |
---|
518 | n/a | None, Warning, None, 1, registry=42) |
---|
519 | n/a | |
---|
520 | n/a | def test_bad_str(self): |
---|
521 | n/a | # issue 6415 |
---|
522 | n/a | # Warnings instance with a bad format string for __str__ should not |
---|
523 | n/a | # trigger a bus error. |
---|
524 | n/a | class BadStrWarning(Warning): |
---|
525 | n/a | """Warning with a bad format string for __str__.""" |
---|
526 | n/a | def __str__(self): |
---|
527 | n/a | return ("A bad formatted string %(err)" % |
---|
528 | n/a | {"err" : "there is no %(err)s"}) |
---|
529 | n/a | |
---|
530 | n/a | with self.assertRaises(ValueError): |
---|
531 | n/a | self.module.warn(BadStrWarning()) |
---|
532 | n/a | |
---|
533 | n/a | def test_warning_classes(self): |
---|
534 | n/a | class MyWarningClass(Warning): |
---|
535 | n/a | pass |
---|
536 | n/a | |
---|
537 | n/a | class NonWarningSubclass: |
---|
538 | n/a | pass |
---|
539 | n/a | |
---|
540 | n/a | # passing a non-subclass of Warning should raise a TypeError |
---|
541 | n/a | with self.assertRaises(TypeError) as cm: |
---|
542 | n/a | self.module.warn('bad warning category', '') |
---|
543 | n/a | self.assertIn('category must be a Warning subclass, not ', |
---|
544 | n/a | str(cm.exception)) |
---|
545 | n/a | |
---|
546 | n/a | with self.assertRaises(TypeError) as cm: |
---|
547 | n/a | self.module.warn('bad warning category', NonWarningSubclass) |
---|
548 | n/a | self.assertIn('category must be a Warning subclass, not ', |
---|
549 | n/a | str(cm.exception)) |
---|
550 | n/a | |
---|
551 | n/a | # check that warning instances also raise a TypeError |
---|
552 | n/a | with self.assertRaises(TypeError) as cm: |
---|
553 | n/a | self.module.warn('bad warning category', MyWarningClass()) |
---|
554 | n/a | self.assertIn('category must be a Warning subclass, not ', |
---|
555 | n/a | str(cm.exception)) |
---|
556 | n/a | |
---|
557 | n/a | with original_warnings.catch_warnings(module=self.module): |
---|
558 | n/a | self.module.resetwarnings() |
---|
559 | n/a | self.module.filterwarnings('default') |
---|
560 | n/a | with self.assertWarns(MyWarningClass) as cm: |
---|
561 | n/a | self.module.warn('good warning category', MyWarningClass) |
---|
562 | n/a | self.assertEqual('good warning category', str(cm.warning)) |
---|
563 | n/a | |
---|
564 | n/a | with self.assertWarns(UserWarning) as cm: |
---|
565 | n/a | self.module.warn('good warning category', None) |
---|
566 | n/a | self.assertEqual('good warning category', str(cm.warning)) |
---|
567 | n/a | |
---|
568 | n/a | with self.assertWarns(MyWarningClass) as cm: |
---|
569 | n/a | self.module.warn('good warning category', MyWarningClass) |
---|
570 | n/a | self.assertIsInstance(cm.warning, Warning) |
---|
571 | n/a | |
---|
572 | n/a | class CWarnTests(WarnTests, unittest.TestCase): |
---|
573 | n/a | module = c_warnings |
---|
574 | n/a | |
---|
575 | n/a | # As an early adopter, we sanity check the |
---|
576 | n/a | # test.support.import_fresh_module utility function |
---|
577 | n/a | def test_accelerated(self): |
---|
578 | n/a | self.assertFalse(original_warnings is self.module) |
---|
579 | n/a | self.assertFalse(hasattr(self.module.warn, '__code__')) |
---|
580 | n/a | |
---|
581 | n/a | class PyWarnTests(WarnTests, unittest.TestCase): |
---|
582 | n/a | module = py_warnings |
---|
583 | n/a | |
---|
584 | n/a | # As an early adopter, we sanity check the |
---|
585 | n/a | # test.support.import_fresh_module utility function |
---|
586 | n/a | def test_pure_python(self): |
---|
587 | n/a | self.assertFalse(original_warnings is self.module) |
---|
588 | n/a | self.assertTrue(hasattr(self.module.warn, '__code__')) |
---|
589 | n/a | |
---|
590 | n/a | |
---|
591 | n/a | class WCmdLineTests(BaseTest): |
---|
592 | n/a | |
---|
593 | n/a | def test_improper_input(self): |
---|
594 | n/a | # Uses the private _setoption() function to test the parsing |
---|
595 | n/a | # of command-line warning arguments |
---|
596 | n/a | with original_warnings.catch_warnings(module=self.module): |
---|
597 | n/a | self.assertRaises(self.module._OptionError, |
---|
598 | n/a | self.module._setoption, '1:2:3:4:5:6') |
---|
599 | n/a | self.assertRaises(self.module._OptionError, |
---|
600 | n/a | self.module._setoption, 'bogus::Warning') |
---|
601 | n/a | self.assertRaises(self.module._OptionError, |
---|
602 | n/a | self.module._setoption, 'ignore:2::4:-5') |
---|
603 | n/a | self.module._setoption('error::Warning::0') |
---|
604 | n/a | self.assertRaises(UserWarning, self.module.warn, 'convert to error') |
---|
605 | n/a | |
---|
606 | n/a | |
---|
607 | n/a | class CWCmdLineTests(WCmdLineTests, unittest.TestCase): |
---|
608 | n/a | module = c_warnings |
---|
609 | n/a | |
---|
610 | n/a | |
---|
611 | n/a | class PyWCmdLineTests(WCmdLineTests, unittest.TestCase): |
---|
612 | n/a | module = py_warnings |
---|
613 | n/a | |
---|
614 | n/a | def test_improper_option(self): |
---|
615 | n/a | # Same as above, but check that the message is printed out when |
---|
616 | n/a | # the interpreter is executed. This also checks that options are |
---|
617 | n/a | # actually parsed at all. |
---|
618 | n/a | rc, out, err = assert_python_ok("-Wxxx", "-c", "pass") |
---|
619 | n/a | self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err) |
---|
620 | n/a | |
---|
621 | n/a | def test_warnings_bootstrap(self): |
---|
622 | n/a | # Check that the warnings module does get loaded when -W<some option> |
---|
623 | n/a | # is used (see issue #10372 for an example of silent bootstrap failure). |
---|
624 | n/a | rc, out, err = assert_python_ok("-Wi", "-c", |
---|
625 | n/a | "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)") |
---|
626 | n/a | # '-Wi' was observed |
---|
627 | n/a | self.assertFalse(out.strip()) |
---|
628 | n/a | self.assertNotIn(b'RuntimeWarning', err) |
---|
629 | n/a | |
---|
630 | n/a | |
---|
631 | n/a | class _WarningsTests(BaseTest, unittest.TestCase): |
---|
632 | n/a | |
---|
633 | n/a | """Tests specific to the _warnings module.""" |
---|
634 | n/a | |
---|
635 | n/a | module = c_warnings |
---|
636 | n/a | |
---|
637 | n/a | def test_filter(self): |
---|
638 | n/a | # Everything should function even if 'filters' is not in warnings. |
---|
639 | n/a | with original_warnings.catch_warnings(module=self.module) as w: |
---|
640 | n/a | self.module.filterwarnings("error", "", Warning, "", 0) |
---|
641 | n/a | self.assertRaises(UserWarning, self.module.warn, |
---|
642 | n/a | 'convert to error') |
---|
643 | n/a | del self.module.filters |
---|
644 | n/a | self.assertRaises(UserWarning, self.module.warn, |
---|
645 | n/a | 'convert to error') |
---|
646 | n/a | |
---|
647 | n/a | def test_onceregistry(self): |
---|
648 | n/a | # Replacing or removing the onceregistry should be okay. |
---|
649 | n/a | global __warningregistry__ |
---|
650 | n/a | message = UserWarning('onceregistry test') |
---|
651 | n/a | try: |
---|
652 | n/a | original_registry = self.module.onceregistry |
---|
653 | n/a | __warningregistry__ = {} |
---|
654 | n/a | with original_warnings.catch_warnings(record=True, |
---|
655 | n/a | module=self.module) as w: |
---|
656 | n/a | self.module.resetwarnings() |
---|
657 | n/a | self.module.filterwarnings("once", category=UserWarning) |
---|
658 | n/a | self.module.warn_explicit(message, UserWarning, "file", 42) |
---|
659 | n/a | self.assertEqual(w[-1].message, message) |
---|
660 | n/a | del w[:] |
---|
661 | n/a | self.module.warn_explicit(message, UserWarning, "file", 42) |
---|
662 | n/a | self.assertEqual(len(w), 0) |
---|
663 | n/a | # Test the resetting of onceregistry. |
---|
664 | n/a | self.module.onceregistry = {} |
---|
665 | n/a | __warningregistry__ = {} |
---|
666 | n/a | self.module.warn('onceregistry test') |
---|
667 | n/a | self.assertEqual(w[-1].message.args, message.args) |
---|
668 | n/a | # Removal of onceregistry is okay. |
---|
669 | n/a | del w[:] |
---|
670 | n/a | del self.module.onceregistry |
---|
671 | n/a | __warningregistry__ = {} |
---|
672 | n/a | self.module.warn_explicit(message, UserWarning, "file", 42) |
---|
673 | n/a | self.assertEqual(len(w), 0) |
---|
674 | n/a | finally: |
---|
675 | n/a | self.module.onceregistry = original_registry |
---|
676 | n/a | |
---|
677 | n/a | def test_default_action(self): |
---|
678 | n/a | # Replacing or removing defaultaction should be okay. |
---|
679 | n/a | message = UserWarning("defaultaction test") |
---|
680 | n/a | original = self.module.defaultaction |
---|
681 | n/a | try: |
---|
682 | n/a | with original_warnings.catch_warnings(record=True, |
---|
683 | n/a | module=self.module) as w: |
---|
684 | n/a | self.module.resetwarnings() |
---|
685 | n/a | registry = {} |
---|
686 | n/a | self.module.warn_explicit(message, UserWarning, "<test>", 42, |
---|
687 | n/a | registry=registry) |
---|
688 | n/a | self.assertEqual(w[-1].message, message) |
---|
689 | n/a | self.assertEqual(len(w), 1) |
---|
690 | n/a | # One actual registry key plus the "version" key |
---|
691 | n/a | self.assertEqual(len(registry), 2) |
---|
692 | n/a | self.assertIn("version", registry) |
---|
693 | n/a | del w[:] |
---|
694 | n/a | # Test removal. |
---|
695 | n/a | del self.module.defaultaction |
---|
696 | n/a | __warningregistry__ = {} |
---|
697 | n/a | registry = {} |
---|
698 | n/a | self.module.warn_explicit(message, UserWarning, "<test>", 43, |
---|
699 | n/a | registry=registry) |
---|
700 | n/a | self.assertEqual(w[-1].message, message) |
---|
701 | n/a | self.assertEqual(len(w), 1) |
---|
702 | n/a | self.assertEqual(len(registry), 2) |
---|
703 | n/a | del w[:] |
---|
704 | n/a | # Test setting. |
---|
705 | n/a | self.module.defaultaction = "ignore" |
---|
706 | n/a | __warningregistry__ = {} |
---|
707 | n/a | registry = {} |
---|
708 | n/a | self.module.warn_explicit(message, UserWarning, "<test>", 44, |
---|
709 | n/a | registry=registry) |
---|
710 | n/a | self.assertEqual(len(w), 0) |
---|
711 | n/a | finally: |
---|
712 | n/a | self.module.defaultaction = original |
---|
713 | n/a | |
---|
714 | n/a | def test_showwarning_missing(self): |
---|
715 | n/a | # Test that showwarning() missing is okay. |
---|
716 | n/a | text = 'del showwarning test' |
---|
717 | n/a | with original_warnings.catch_warnings(module=self.module): |
---|
718 | n/a | self.module.filterwarnings("always", category=UserWarning) |
---|
719 | n/a | del self.module.showwarning |
---|
720 | n/a | with support.captured_output('stderr') as stream: |
---|
721 | n/a | self.module.warn(text) |
---|
722 | n/a | result = stream.getvalue() |
---|
723 | n/a | self.assertIn(text, result) |
---|
724 | n/a | |
---|
725 | n/a | def test_showwarnmsg_missing(self): |
---|
726 | n/a | # Test that _showwarnmsg() missing is okay. |
---|
727 | n/a | text = 'del _showwarnmsg test' |
---|
728 | n/a | with original_warnings.catch_warnings(module=self.module): |
---|
729 | n/a | self.module.filterwarnings("always", category=UserWarning) |
---|
730 | n/a | del self.module._showwarnmsg |
---|
731 | n/a | with support.captured_output('stderr') as stream: |
---|
732 | n/a | self.module.warn(text) |
---|
733 | n/a | result = stream.getvalue() |
---|
734 | n/a | self.assertIn(text, result) |
---|
735 | n/a | |
---|
736 | n/a | def test_showwarning_not_callable(self): |
---|
737 | n/a | with original_warnings.catch_warnings(module=self.module): |
---|
738 | n/a | self.module.filterwarnings("always", category=UserWarning) |
---|
739 | n/a | self.module.showwarning = print |
---|
740 | n/a | with support.captured_output('stdout'): |
---|
741 | n/a | self.module.warn('Warning!') |
---|
742 | n/a | self.module.showwarning = 23 |
---|
743 | n/a | self.assertRaises(TypeError, self.module.warn, "Warning!") |
---|
744 | n/a | |
---|
745 | n/a | def test_show_warning_output(self): |
---|
746 | n/a | # With showarning() missing, make sure that output is okay. |
---|
747 | n/a | text = 'test show_warning' |
---|
748 | n/a | with original_warnings.catch_warnings(module=self.module): |
---|
749 | n/a | self.module.filterwarnings("always", category=UserWarning) |
---|
750 | n/a | del self.module.showwarning |
---|
751 | n/a | with support.captured_output('stderr') as stream: |
---|
752 | n/a | warning_tests.inner(text) |
---|
753 | n/a | result = stream.getvalue() |
---|
754 | n/a | self.assertEqual(result.count('\n'), 2, |
---|
755 | n/a | "Too many newlines in %r" % result) |
---|
756 | n/a | first_line, second_line = result.split('\n', 1) |
---|
757 | n/a | expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' |
---|
758 | n/a | first_line_parts = first_line.rsplit(':', 3) |
---|
759 | n/a | path, line, warning_class, message = first_line_parts |
---|
760 | n/a | line = int(line) |
---|
761 | n/a | self.assertEqual(expected_file, path) |
---|
762 | n/a | self.assertEqual(warning_class, ' ' + UserWarning.__name__) |
---|
763 | n/a | self.assertEqual(message, ' ' + text) |
---|
764 | n/a | expected_line = ' ' + linecache.getline(path, line).strip() + '\n' |
---|
765 | n/a | assert expected_line |
---|
766 | n/a | self.assertEqual(second_line, expected_line) |
---|
767 | n/a | |
---|
768 | n/a | def test_filename_none(self): |
---|
769 | n/a | # issue #12467: race condition if a warning is emitted at shutdown |
---|
770 | n/a | globals_dict = globals() |
---|
771 | n/a | oldfile = globals_dict['__file__'] |
---|
772 | n/a | try: |
---|
773 | n/a | catch = original_warnings.catch_warnings(record=True, |
---|
774 | n/a | module=self.module) |
---|
775 | n/a | with catch as w: |
---|
776 | n/a | self.module.filterwarnings("always", category=UserWarning) |
---|
777 | n/a | globals_dict['__file__'] = None |
---|
778 | n/a | original_warnings.warn('test', UserWarning) |
---|
779 | n/a | self.assertTrue(len(w)) |
---|
780 | n/a | finally: |
---|
781 | n/a | globals_dict['__file__'] = oldfile |
---|
782 | n/a | |
---|
783 | n/a | def test_stderr_none(self): |
---|
784 | n/a | rc, stdout, stderr = assert_python_ok("-c", |
---|
785 | n/a | "import sys; sys.stderr = None; " |
---|
786 | n/a | "import warnings; warnings.simplefilter('always'); " |
---|
787 | n/a | "warnings.warn('Warning!')") |
---|
788 | n/a | self.assertEqual(stdout, b'') |
---|
789 | n/a | self.assertNotIn(b'Warning!', stderr) |
---|
790 | n/a | self.assertNotIn(b'Error', stderr) |
---|
791 | n/a | |
---|
792 | n/a | |
---|
793 | n/a | class WarningsDisplayTests(BaseTest): |
---|
794 | n/a | |
---|
795 | n/a | """Test the displaying of warnings and the ability to overload functions |
---|
796 | n/a | related to displaying warnings.""" |
---|
797 | n/a | |
---|
798 | n/a | def test_formatwarning(self): |
---|
799 | n/a | message = "msg" |
---|
800 | n/a | category = Warning |
---|
801 | n/a | file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' |
---|
802 | n/a | line_num = 3 |
---|
803 | n/a | file_line = linecache.getline(file_name, line_num).strip() |
---|
804 | n/a | format = "%s:%s: %s: %s\n %s\n" |
---|
805 | n/a | expect = format % (file_name, line_num, category.__name__, message, |
---|
806 | n/a | file_line) |
---|
807 | n/a | self.assertEqual(expect, self.module.formatwarning(message, |
---|
808 | n/a | category, file_name, line_num)) |
---|
809 | n/a | # Test the 'line' argument. |
---|
810 | n/a | file_line += " for the win!" |
---|
811 | n/a | expect = format % (file_name, line_num, category.__name__, message, |
---|
812 | n/a | file_line) |
---|
813 | n/a | self.assertEqual(expect, self.module.formatwarning(message, |
---|
814 | n/a | category, file_name, line_num, file_line)) |
---|
815 | n/a | |
---|
816 | n/a | def test_showwarning(self): |
---|
817 | n/a | file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' |
---|
818 | n/a | line_num = 3 |
---|
819 | n/a | expected_file_line = linecache.getline(file_name, line_num).strip() |
---|
820 | n/a | message = 'msg' |
---|
821 | n/a | category = Warning |
---|
822 | n/a | file_object = StringIO() |
---|
823 | n/a | expect = self.module.formatwarning(message, category, file_name, |
---|
824 | n/a | line_num) |
---|
825 | n/a | self.module.showwarning(message, category, file_name, line_num, |
---|
826 | n/a | file_object) |
---|
827 | n/a | self.assertEqual(file_object.getvalue(), expect) |
---|
828 | n/a | # Test 'line' argument. |
---|
829 | n/a | expected_file_line += "for the win!" |
---|
830 | n/a | expect = self.module.formatwarning(message, category, file_name, |
---|
831 | n/a | line_num, expected_file_line) |
---|
832 | n/a | file_object = StringIO() |
---|
833 | n/a | self.module.showwarning(message, category, file_name, line_num, |
---|
834 | n/a | file_object, expected_file_line) |
---|
835 | n/a | self.assertEqual(expect, file_object.getvalue()) |
---|
836 | n/a | |
---|
837 | n/a | |
---|
838 | n/a | class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase): |
---|
839 | n/a | module = c_warnings |
---|
840 | n/a | |
---|
841 | n/a | class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase): |
---|
842 | n/a | module = py_warnings |
---|
843 | n/a | |
---|
844 | n/a | def test_tracemalloc(self): |
---|
845 | n/a | self.addCleanup(support.unlink, support.TESTFN) |
---|
846 | n/a | |
---|
847 | n/a | with open(support.TESTFN, 'w') as fp: |
---|
848 | n/a | fp.write(textwrap.dedent(""" |
---|
849 | n/a | def func(): |
---|
850 | n/a | f = open(__file__) |
---|
851 | n/a | # Emit ResourceWarning |
---|
852 | n/a | f = None |
---|
853 | n/a | |
---|
854 | n/a | func() |
---|
855 | n/a | """)) |
---|
856 | n/a | |
---|
857 | n/a | res = assert_python_ok('-Wd', '-X', 'tracemalloc=2', support.TESTFN) |
---|
858 | n/a | |
---|
859 | n/a | stderr = res.err.decode('ascii', 'replace') |
---|
860 | n/a | # normalize newlines |
---|
861 | n/a | stderr = '\n'.join(stderr.splitlines()) |
---|
862 | n/a | stderr = re.sub('<.*>', '<...>', stderr) |
---|
863 | n/a | expected = textwrap.dedent(''' |
---|
864 | n/a | {fname}:5: ResourceWarning: unclosed file <...> |
---|
865 | n/a | f = None |
---|
866 | n/a | Object allocated at (most recent call first): |
---|
867 | n/a | File "{fname}", lineno 3 |
---|
868 | n/a | f = open(__file__) |
---|
869 | n/a | File "{fname}", lineno 7 |
---|
870 | n/a | func() |
---|
871 | n/a | ''') |
---|
872 | n/a | expected = expected.format(fname=support.TESTFN).strip() |
---|
873 | n/a | self.assertEqual(stderr, expected) |
---|
874 | n/a | |
---|
875 | n/a | |
---|
876 | n/a | class CatchWarningTests(BaseTest): |
---|
877 | n/a | |
---|
878 | n/a | """Test catch_warnings().""" |
---|
879 | n/a | |
---|
880 | n/a | def test_catch_warnings_restore(self): |
---|
881 | n/a | wmod = self.module |
---|
882 | n/a | orig_filters = wmod.filters |
---|
883 | n/a | orig_showwarning = wmod.showwarning |
---|
884 | n/a | # Ensure both showwarning and filters are restored when recording |
---|
885 | n/a | with wmod.catch_warnings(module=wmod, record=True): |
---|
886 | n/a | wmod.filters = wmod.showwarning = object() |
---|
887 | n/a | self.assertTrue(wmod.filters is orig_filters) |
---|
888 | n/a | self.assertTrue(wmod.showwarning is orig_showwarning) |
---|
889 | n/a | # Same test, but with recording disabled |
---|
890 | n/a | with wmod.catch_warnings(module=wmod, record=False): |
---|
891 | n/a | wmod.filters = wmod.showwarning = object() |
---|
892 | n/a | self.assertTrue(wmod.filters is orig_filters) |
---|
893 | n/a | self.assertTrue(wmod.showwarning is orig_showwarning) |
---|
894 | n/a | |
---|
895 | n/a | def test_catch_warnings_recording(self): |
---|
896 | n/a | wmod = self.module |
---|
897 | n/a | # Ensure warnings are recorded when requested |
---|
898 | n/a | with wmod.catch_warnings(module=wmod, record=True) as w: |
---|
899 | n/a | self.assertEqual(w, []) |
---|
900 | n/a | self.assertTrue(type(w) is list) |
---|
901 | n/a | wmod.simplefilter("always") |
---|
902 | n/a | wmod.warn("foo") |
---|
903 | n/a | self.assertEqual(str(w[-1].message), "foo") |
---|
904 | n/a | wmod.warn("bar") |
---|
905 | n/a | self.assertEqual(str(w[-1].message), "bar") |
---|
906 | n/a | self.assertEqual(str(w[0].message), "foo") |
---|
907 | n/a | self.assertEqual(str(w[1].message), "bar") |
---|
908 | n/a | del w[:] |
---|
909 | n/a | self.assertEqual(w, []) |
---|
910 | n/a | # Ensure warnings are not recorded when not requested |
---|
911 | n/a | orig_showwarning = wmod.showwarning |
---|
912 | n/a | with wmod.catch_warnings(module=wmod, record=False) as w: |
---|
913 | n/a | self.assertTrue(w is None) |
---|
914 | n/a | self.assertTrue(wmod.showwarning is orig_showwarning) |
---|
915 | n/a | |
---|
916 | n/a | def test_catch_warnings_reentry_guard(self): |
---|
917 | n/a | wmod = self.module |
---|
918 | n/a | # Ensure catch_warnings is protected against incorrect usage |
---|
919 | n/a | x = wmod.catch_warnings(module=wmod, record=True) |
---|
920 | n/a | self.assertRaises(RuntimeError, x.__exit__) |
---|
921 | n/a | with x: |
---|
922 | n/a | self.assertRaises(RuntimeError, x.__enter__) |
---|
923 | n/a | # Same test, but with recording disabled |
---|
924 | n/a | x = wmod.catch_warnings(module=wmod, record=False) |
---|
925 | n/a | self.assertRaises(RuntimeError, x.__exit__) |
---|
926 | n/a | with x: |
---|
927 | n/a | self.assertRaises(RuntimeError, x.__enter__) |
---|
928 | n/a | |
---|
929 | n/a | def test_catch_warnings_defaults(self): |
---|
930 | n/a | wmod = self.module |
---|
931 | n/a | orig_filters = wmod.filters |
---|
932 | n/a | orig_showwarning = wmod.showwarning |
---|
933 | n/a | # Ensure default behaviour is not to record warnings |
---|
934 | n/a | with wmod.catch_warnings(module=wmod) as w: |
---|
935 | n/a | self.assertTrue(w is None) |
---|
936 | n/a | self.assertTrue(wmod.showwarning is orig_showwarning) |
---|
937 | n/a | self.assertTrue(wmod.filters is not orig_filters) |
---|
938 | n/a | self.assertTrue(wmod.filters is orig_filters) |
---|
939 | n/a | if wmod is sys.modules['warnings']: |
---|
940 | n/a | # Ensure the default module is this one |
---|
941 | n/a | with wmod.catch_warnings() as w: |
---|
942 | n/a | self.assertTrue(w is None) |
---|
943 | n/a | self.assertTrue(wmod.showwarning is orig_showwarning) |
---|
944 | n/a | self.assertTrue(wmod.filters is not orig_filters) |
---|
945 | n/a | self.assertTrue(wmod.filters is orig_filters) |
---|
946 | n/a | |
---|
947 | n/a | def test_record_override_showwarning_before(self): |
---|
948 | n/a | # Issue #28835: If warnings.showwarning() was overriden, make sure |
---|
949 | n/a | # that catch_warnings(record=True) overrides it again. |
---|
950 | n/a | text = "This is a warning" |
---|
951 | n/a | wmod = self.module |
---|
952 | n/a | my_log = [] |
---|
953 | n/a | |
---|
954 | n/a | def my_logger(message, category, filename, lineno, file=None, line=None): |
---|
955 | n/a | nonlocal my_log |
---|
956 | n/a | my_log.append(message) |
---|
957 | n/a | |
---|
958 | n/a | # Override warnings.showwarning() before calling catch_warnings() |
---|
959 | n/a | with support.swap_attr(wmod, 'showwarning', my_logger): |
---|
960 | n/a | with wmod.catch_warnings(module=wmod, record=True) as log: |
---|
961 | n/a | self.assertIsNot(wmod.showwarning, my_logger) |
---|
962 | n/a | |
---|
963 | n/a | wmod.simplefilter("always") |
---|
964 | n/a | wmod.warn(text) |
---|
965 | n/a | |
---|
966 | n/a | self.assertIs(wmod.showwarning, my_logger) |
---|
967 | n/a | |
---|
968 | n/a | self.assertEqual(len(log), 1, log) |
---|
969 | n/a | self.assertEqual(log[0].message.args[0], text) |
---|
970 | n/a | self.assertEqual(my_log, []) |
---|
971 | n/a | |
---|
972 | n/a | def test_record_override_showwarning_inside(self): |
---|
973 | n/a | # Issue #28835: It is possible to override warnings.showwarning() |
---|
974 | n/a | # in the catch_warnings(record=True) context manager. |
---|
975 | n/a | text = "This is a warning" |
---|
976 | n/a | wmod = self.module |
---|
977 | n/a | my_log = [] |
---|
978 | n/a | |
---|
979 | n/a | def my_logger(message, category, filename, lineno, file=None, line=None): |
---|
980 | n/a | nonlocal my_log |
---|
981 | n/a | my_log.append(message) |
---|
982 | n/a | |
---|
983 | n/a | with wmod.catch_warnings(module=wmod, record=True) as log: |
---|
984 | n/a | wmod.simplefilter("always") |
---|
985 | n/a | wmod.showwarning = my_logger |
---|
986 | n/a | wmod.warn(text) |
---|
987 | n/a | |
---|
988 | n/a | self.assertEqual(len(my_log), 1, my_log) |
---|
989 | n/a | self.assertEqual(my_log[0].args[0], text) |
---|
990 | n/a | self.assertEqual(log, []) |
---|
991 | n/a | |
---|
992 | n/a | def test_check_warnings(self): |
---|
993 | n/a | # Explicit tests for the test.support convenience wrapper |
---|
994 | n/a | wmod = self.module |
---|
995 | n/a | if wmod is not sys.modules['warnings']: |
---|
996 | n/a | self.skipTest('module to test is not loaded warnings module') |
---|
997 | n/a | with support.check_warnings(quiet=False) as w: |
---|
998 | n/a | self.assertEqual(w.warnings, []) |
---|
999 | n/a | wmod.simplefilter("always") |
---|
1000 | n/a | wmod.warn("foo") |
---|
1001 | n/a | self.assertEqual(str(w.message), "foo") |
---|
1002 | n/a | wmod.warn("bar") |
---|
1003 | n/a | self.assertEqual(str(w.message), "bar") |
---|
1004 | n/a | self.assertEqual(str(w.warnings[0].message), "foo") |
---|
1005 | n/a | self.assertEqual(str(w.warnings[1].message), "bar") |
---|
1006 | n/a | w.reset() |
---|
1007 | n/a | self.assertEqual(w.warnings, []) |
---|
1008 | n/a | |
---|
1009 | n/a | with support.check_warnings(): |
---|
1010 | n/a | # defaults to quiet=True without argument |
---|
1011 | n/a | pass |
---|
1012 | n/a | with support.check_warnings(('foo', UserWarning)): |
---|
1013 | n/a | wmod.warn("foo") |
---|
1014 | n/a | |
---|
1015 | n/a | with self.assertRaises(AssertionError): |
---|
1016 | n/a | with support.check_warnings(('', RuntimeWarning)): |
---|
1017 | n/a | # defaults to quiet=False with argument |
---|
1018 | n/a | pass |
---|
1019 | n/a | with self.assertRaises(AssertionError): |
---|
1020 | n/a | with support.check_warnings(('foo', RuntimeWarning)): |
---|
1021 | n/a | wmod.warn("foo") |
---|
1022 | n/a | |
---|
1023 | n/a | class CCatchWarningTests(CatchWarningTests, unittest.TestCase): |
---|
1024 | n/a | module = c_warnings |
---|
1025 | n/a | |
---|
1026 | n/a | class PyCatchWarningTests(CatchWarningTests, unittest.TestCase): |
---|
1027 | n/a | module = py_warnings |
---|
1028 | n/a | |
---|
1029 | n/a | |
---|
1030 | n/a | class EnvironmentVariableTests(BaseTest): |
---|
1031 | n/a | |
---|
1032 | n/a | def test_single_warning(self): |
---|
1033 | n/a | rc, stdout, stderr = assert_python_ok("-c", |
---|
1034 | n/a | "import sys; sys.stdout.write(str(sys.warnoptions))", |
---|
1035 | n/a | PYTHONWARNINGS="ignore::DeprecationWarning") |
---|
1036 | n/a | self.assertEqual(stdout, b"['ignore::DeprecationWarning']") |
---|
1037 | n/a | |
---|
1038 | n/a | def test_comma_separated_warnings(self): |
---|
1039 | n/a | rc, stdout, stderr = assert_python_ok("-c", |
---|
1040 | n/a | "import sys; sys.stdout.write(str(sys.warnoptions))", |
---|
1041 | n/a | PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning") |
---|
1042 | n/a | self.assertEqual(stdout, |
---|
1043 | n/a | b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") |
---|
1044 | n/a | |
---|
1045 | n/a | def test_envvar_and_command_line(self): |
---|
1046 | n/a | rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c", |
---|
1047 | n/a | "import sys; sys.stdout.write(str(sys.warnoptions))", |
---|
1048 | n/a | PYTHONWARNINGS="ignore::DeprecationWarning") |
---|
1049 | n/a | self.assertEqual(stdout, |
---|
1050 | n/a | b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") |
---|
1051 | n/a | |
---|
1052 | n/a | def test_conflicting_envvar_and_command_line(self): |
---|
1053 | n/a | rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c", |
---|
1054 | n/a | "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); " |
---|
1055 | n/a | "warnings.warn('Message', DeprecationWarning)", |
---|
1056 | n/a | PYTHONWARNINGS="default::DeprecationWarning") |
---|
1057 | n/a | self.assertEqual(stdout, |
---|
1058 | n/a | b"['default::DeprecationWarning', 'error::DeprecationWarning']") |
---|
1059 | n/a | self.assertEqual(stderr.splitlines(), |
---|
1060 | n/a | [b"Traceback (most recent call last):", |
---|
1061 | n/a | b" File \"<string>\", line 1, in <module>", |
---|
1062 | n/a | b"DeprecationWarning: Message"]) |
---|
1063 | n/a | |
---|
1064 | n/a | @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii', |
---|
1065 | n/a | 'requires non-ascii filesystemencoding') |
---|
1066 | n/a | def test_nonascii(self): |
---|
1067 | n/a | rc, stdout, stderr = assert_python_ok("-c", |
---|
1068 | n/a | "import sys; sys.stdout.write(str(sys.warnoptions))", |
---|
1069 | n/a | PYTHONIOENCODING="utf-8", |
---|
1070 | n/a | PYTHONWARNINGS="ignore:DeprecaciónWarning") |
---|
1071 | n/a | self.assertEqual(stdout, |
---|
1072 | n/a | "['ignore:DeprecaciónWarning']".encode('utf-8')) |
---|
1073 | n/a | |
---|
1074 | n/a | class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase): |
---|
1075 | n/a | module = c_warnings |
---|
1076 | n/a | |
---|
1077 | n/a | class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase): |
---|
1078 | n/a | module = py_warnings |
---|
1079 | n/a | |
---|
1080 | n/a | |
---|
1081 | n/a | class BootstrapTest(unittest.TestCase): |
---|
1082 | n/a | def test_issue_8766(self): |
---|
1083 | n/a | # "import encodings" emits a warning whereas the warnings is not loaded |
---|
1084 | n/a | # or not completely loaded (warnings imports indirectly encodings by |
---|
1085 | n/a | # importing linecache) yet |
---|
1086 | n/a | with support.temp_cwd() as cwd, support.temp_cwd('encodings'): |
---|
1087 | n/a | # encodings loaded by initfsencoding() |
---|
1088 | n/a | assert_python_ok('-c', 'pass', PYTHONPATH=cwd) |
---|
1089 | n/a | |
---|
1090 | n/a | # Use -W to load warnings module at startup |
---|
1091 | n/a | assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd) |
---|
1092 | n/a | |
---|
1093 | n/a | |
---|
1094 | n/a | class FinalizationTest(unittest.TestCase): |
---|
1095 | n/a | @support.requires_type_collecting |
---|
1096 | n/a | def test_finalization(self): |
---|
1097 | n/a | # Issue #19421: warnings.warn() should not crash |
---|
1098 | n/a | # during Python finalization |
---|
1099 | n/a | code = """ |
---|
1100 | n/a | import warnings |
---|
1101 | n/a | warn = warnings.warn |
---|
1102 | n/a | |
---|
1103 | n/a | class A: |
---|
1104 | n/a | def __del__(self): |
---|
1105 | n/a | warn("test") |
---|
1106 | n/a | |
---|
1107 | n/a | a=A() |
---|
1108 | n/a | """ |
---|
1109 | n/a | rc, out, err = assert_python_ok("-c", code) |
---|
1110 | n/a | # note: "__main__" filename is not correct, it should be the name |
---|
1111 | n/a | # of the script |
---|
1112 | n/a | self.assertEqual(err, b'__main__:7: UserWarning: test') |
---|
1113 | n/a | |
---|
1114 | n/a | def test_late_resource_warning(self): |
---|
1115 | n/a | # Issue #21925: Emitting a ResourceWarning late during the Python |
---|
1116 | n/a | # shutdown must be logged. |
---|
1117 | n/a | |
---|
1118 | n/a | expected = b"sys:1: ResourceWarning: unclosed file " |
---|
1119 | n/a | |
---|
1120 | n/a | # don't import the warnings module |
---|
1121 | n/a | # (_warnings will try to import it) |
---|
1122 | n/a | code = "f = open(%a)" % __file__ |
---|
1123 | n/a | rc, out, err = assert_python_ok("-Wd", "-c", code) |
---|
1124 | n/a | self.assertTrue(err.startswith(expected), ascii(err)) |
---|
1125 | n/a | |
---|
1126 | n/a | # import the warnings module |
---|
1127 | n/a | code = "import warnings; f = open(%a)" % __file__ |
---|
1128 | n/a | rc, out, err = assert_python_ok("-Wd", "-c", code) |
---|
1129 | n/a | self.assertTrue(err.startswith(expected), ascii(err)) |
---|
1130 | n/a | |
---|
1131 | n/a | |
---|
1132 | n/a | def setUpModule(): |
---|
1133 | n/a | py_warnings.onceregistry.clear() |
---|
1134 | n/a | c_warnings.onceregistry.clear() |
---|
1135 | n/a | |
---|
1136 | n/a | tearDownModule = setUpModule |
---|
1137 | n/a | |
---|
1138 | n/a | if __name__ == "__main__": |
---|
1139 | n/a | unittest.main() |
---|