Debian Codegraph @

Lib/test/test_warnings/__init__.py

raw
1 from contextlib import contextmanager
2 import linecache
3 import os
4 import importlib
5 import inspect
6 from io import StringIO
7 import re
8 import sys
9 import textwrap
10 import types
11 from typing import overload, get_overloads
12 import unittest
13 from test import support
14 from test.support import import_helper
15 from test.support import os_helper
16 from test.support import warnings_helper
17 from test.support import force_not_colorized
18 from test.support.script_helper import assert_python_ok, assert_python_failure
19
20 from test.test_warnings.data import package_helper
21 from test.test_warnings.data import stacklevel as warning_tests
22
23 import warnings as original_warnings
24 from warnings import deprecated
25
26
27 py_warnings = import_helper.import_fresh_module('warnings',
28 blocked=['_warnings'])
29 c_warnings = import_helper.import_fresh_module('warnings',
30 fresh=['_warnings'])
31
32 @contextmanager
33 def warnings_state(module):
34 """Use a specific warnings implementation in warning_tests."""
35 global __warningregistry__
36 for to_clear in (sys, warning_tests):
37 try:
38 to_clear.__warningregistry__.clear()
39 except AttributeError:
40 pass
41 try:
42 __warningregistry__.clear()
43 except NameError:
44 pass
45 original_warnings = warning_tests.warnings
46 original_filters = module.filters
47 try:
48 module.filters = original_filters[:]
49 module.simplefilter("once")
50 warning_tests.warnings = module
51 yield
52 finally:
53 warning_tests.warnings = original_warnings
54 module.filters = original_filters
55
56
57 class TestWarning(Warning):
58 pass
59
60
61 class BaseTest:
62
63 """Basic bookkeeping required for testing."""
64
65 def setUp(self):
66 self.old_unittest_module = unittest.case.warnings
67 # The __warningregistry__ needs to be in a pristine state for tests
68 # to work properly.
69 if '__warningregistry__' in globals():
70 del globals()['__warningregistry__']
71 if hasattr(warning_tests, '__warningregistry__'):
72 del warning_tests.__warningregistry__
73 if hasattr(sys, '__warningregistry__'):
74 del sys.__warningregistry__
75 # The 'warnings' module must be explicitly set so that the proper
76 # interaction between _warnings and 'warnings' can be controlled.
77 sys.modules['warnings'] = self.module
78 # Ensure that unittest.TestCase.assertWarns() uses the same warnings
79 # module than warnings.catch_warnings(). Otherwise,
80 # warnings.catch_warnings() will be unable to remove the added filter.
81 unittest.case.warnings = self.module
82 super(BaseTest, self).setUp()
83
84 def tearDown(self):
85 sys.modules['warnings'] = original_warnings
86 unittest.case.warnings = self.old_unittest_module
87 super(BaseTest, self).tearDown()
88
89 class PublicAPITests(BaseTest):
90
91 """Ensures that the correct values are exposed in the
92 public API.
93 """
94
95 def test_module_all_attribute(self):
96 self.assertTrue(hasattr(self.module, '__all__'))
97 target_api = ["warn", "warn_explicit", "showwarning",
98 "formatwarning", "filterwarnings", "simplefilter",
99 "resetwarnings", "catch_warnings", "deprecated"]
100 self.assertSetEqual(set(self.module.__all__),
101 set(target_api))
102
103 class CPublicAPITests(PublicAPITests, unittest.TestCase):
104 module = c_warnings
105
106 class PyPublicAPITests(PublicAPITests, unittest.TestCase):
107 module = py_warnings
108
109 class FilterTests(BaseTest):
110
111 """Testing the filtering functionality."""
112
113 def test_error(self):
114 with original_warnings.catch_warnings(module=self.module) as w:
115 self.module.resetwarnings()
116 self.module.filterwarnings("error", category=UserWarning)
117 self.assertRaises(UserWarning, self.module.warn,
118 "FilterTests.test_error")
119
120 def test_error_after_default(self):
121 with original_warnings.catch_warnings(module=self.module) as w:
122 self.module.resetwarnings()
123 message = "FilterTests.test_ignore_after_default"
124 def f():
125 self.module.warn(message, UserWarning)
126
127 with support.captured_stderr() as stderr:
128 f()
129 stderr = stderr.getvalue()
130 self.assertIn("UserWarning: FilterTests.test_ignore_after_default",
131 stderr)
132 self.assertIn("self.module.warn(message, UserWarning)",
133 stderr)
134
135 self.module.filterwarnings("error", category=UserWarning)
136 self.assertRaises(UserWarning, f)
137
138 def test_ignore(self):
139 with original_warnings.catch_warnings(record=True,
140 module=self.module) as w:
141 self.module.resetwarnings()
142 self.module.filterwarnings("ignore", category=UserWarning)
143 self.module.warn("FilterTests.test_ignore", UserWarning)
144 self.assertEqual(len(w), 0)
145 self.assertEqual(list(__warningregistry__), ['version'])
146
147 def test_ignore_after_default(self):
148 with original_warnings.catch_warnings(record=True,
149 module=self.module) as w:
150 self.module.resetwarnings()
151 message = "FilterTests.test_ignore_after_default"
152 def f():
153 self.module.warn(message, UserWarning)
154 f()
155 self.module.filterwarnings("ignore", category=UserWarning)
156 f()
157 f()
158 self.assertEqual(len(w), 1)
159
160 def test_always(self):
161 with original_warnings.catch_warnings(record=True,
162 module=self.module) as w:
163 self.module.resetwarnings()
164 self.module.filterwarnings("always", category=UserWarning)
165 message = "FilterTests.test_always"
166 def f():
167 self.module.warn(message, UserWarning)
168 f()
169 self.assertEqual(len(w), 1)
170 self.assertEqual(w[-1].message.args[0], message)
171 f()
172 self.assertEqual(len(w), 2)
173 self.assertEqual(w[-1].message.args[0], message)
174
175 def test_always_after_default(self):
176 with original_warnings.catch_warnings(record=True,
177 module=self.module) as w:
178 self.module.resetwarnings()
179 message = "FilterTests.test_always_after_ignore"
180 def f():
181 self.module.warn(message, UserWarning)
182 f()
183 self.assertEqual(len(w), 1)
184 self.assertEqual(w[-1].message.args[0], message)
185 f()
186 self.assertEqual(len(w), 1)
187 self.module.filterwarnings("always", category=UserWarning)
188 f()
189 self.assertEqual(len(w), 2)
190 self.assertEqual(w[-1].message.args[0], message)
191 f()
192 self.assertEqual(len(w), 3)
193 self.assertEqual(w[-1].message.args[0], message)
194
195 def test_default(self):
196 with original_warnings.catch_warnings(record=True,
197 module=self.module) as w:
198 self.module.resetwarnings()
199 self.module.filterwarnings("default", category=UserWarning)
200 message = UserWarning("FilterTests.test_default")
201 for x in range(2):
202 self.module.warn(message, UserWarning)
203 if x == 0:
204 self.assertEqual(w[-1].message, message)
205 del w[:]
206 elif x == 1:
207 self.assertEqual(len(w), 0)
208 else:
209 raise ValueError("loop variant unhandled")
210
211 def test_module(self):
212 with original_warnings.catch_warnings(record=True,
213 module=self.module) as w:
214 self.module.resetwarnings()
215 self.module.filterwarnings("module", category=UserWarning)
216 message = UserWarning("FilterTests.test_module")
217 self.module.warn(message, UserWarning)
218 self.assertEqual(w[-1].message, message)
219 del w[:]
220 self.module.warn(message, UserWarning)
221 self.assertEqual(len(w), 0)
222
223 def test_once(self):
224 with original_warnings.catch_warnings(record=True,
225 module=self.module) as w:
226 self.module.resetwarnings()
227 self.module.filterwarnings("once", category=UserWarning)
228 message = UserWarning("FilterTests.test_once")
229 self.module.warn_explicit(message, UserWarning, "__init__.py",
230 42)
231 self.assertEqual(w[-1].message, message)
232 del w[:]
233 self.module.warn_explicit(message, UserWarning, "__init__.py",
234 13)
235 self.assertEqual(len(w), 0)
236 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
237 42)
238 self.assertEqual(len(w), 0)
239
240 def test_filter_module(self):
241 MS_WINDOWS = (sys.platform == 'win32')
242 with self.module.catch_warnings(record=True) as w:
243 self.module.simplefilter('error')
244 self.module.filterwarnings('always', module=r'package\.module\Z')
245 self.module.warn_explicit('msg', UserWarning, 'filename', 42,
246 module='package.module')
247 self.assertEqual(len(w), 1)
248 with self.assertRaises(UserWarning):
249 self.module.warn_explicit('msg', UserWarning, '/path/to/package/module', 42)
250 with self.assertRaises(UserWarning):
251 self.module.warn_explicit('msg', UserWarning, '/path/to/package/module.py', 42)
252
253 with self.module.catch_warnings(record=True) as w:
254 self.module.simplefilter('error')
255 self.module.filterwarnings('always', module='package')
256 self.module.warn_explicit('msg', UserWarning, 'filename', 42,
257 module='package.module')
258 self.assertEqual(len(w), 1)
259 with self.assertRaises(UserWarning):
260 self.module.warn_explicit('msg', UserWarning, 'filename', 42,
261 module='other.package.module')
262 with self.assertRaises(UserWarning):
263 self.module.warn_explicit('msg', UserWarning, '/path/to/otherpackage/module.py', 42)
264
265 with self.module.catch_warnings(record=True) as w:
266 self.module.simplefilter('error')
267 self.module.filterwarnings('always', module=r'/path/to/package/module\Z')
268 self.module.warn_explicit('msg', UserWarning, '/path/to/package/module', 42)
269 self.assertEqual(len(w), 1)
270 self.module.warn_explicit('msg', UserWarning, '/path/to/package/module.py', 42)
271 self.assertEqual(len(w), 2)
272 with self.assertRaises(UserWarning):
273 self.module.warn_explicit('msg', UserWarning, '/PATH/TO/PACKAGE/MODULE', 42)
274 if MS_WINDOWS:
275 if self.module is py_warnings:
276 self.module.warn_explicit('msg', UserWarning, r'/path/to/package/module.PY', 42)
277 self.assertEqual(len(w), 3)
278 with self.assertRaises(UserWarning):
279 self.module.warn_explicit('msg', UserWarning, r'/path/to/package/module/__init__.py', 42)
280 with self.assertRaises(UserWarning):
281 self.module.warn_explicit('msg', UserWarning, r'/path/to/package/module.pyw', 42)
282 with self.assertRaises(UserWarning):
283 self.module.warn_explicit('msg', UserWarning, r'\path\to\package\module', 42)
284
285 with self.module.catch_warnings(record=True) as w:
286 self.module.simplefilter('error')
287 self.module.filterwarnings('always', module=r'/path/to/package/__init__\Z')
288 self.module.warn_explicit('msg', UserWarning, '/path/to/package/__init__.py', 42)
289 self.assertEqual(len(w), 1)
290 self.module.warn_explicit('msg', UserWarning, '/path/to/package/__init__', 42)
291 self.assertEqual(len(w), 2)
292
293 if MS_WINDOWS:
294 with self.module.catch_warnings(record=True) as w:
295 self.module.simplefilter('error')
296 self.module.filterwarnings('always', module=r'C:\\path\\to\\package\\module\Z')
297 self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module', 42)
298 self.assertEqual(len(w), 1)
299 self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.py', 42)
300 self.assertEqual(len(w), 2)
301 if self.module is py_warnings:
302 self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.PY', 42)
303 self.assertEqual(len(w), 3)
304 with self.assertRaises(UserWarning):
305 self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.pyw', 42)
306 with self.assertRaises(UserWarning):
307 self.module.warn_explicit('msg', UserWarning, r'C:\PATH\TO\PACKAGE\MODULE', 42)
308 with self.assertRaises(UserWarning):
309 self.module.warn_explicit('msg', UserWarning, r'C:/path/to/package/module', 42)
310 with self.assertRaises(UserWarning):
311 self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module\__init__.py', 42)
312
313 with self.module.catch_warnings(record=True) as w:
314 self.module.simplefilter('error')
315 self.module.filterwarnings('always', module=r'<unknown>\Z')
316 self.module.warn_explicit('msg', UserWarning, '', 42)
317 self.assertEqual(len(w), 1)
318
319 def test_module_globals(self):
320 with original_warnings.catch_warnings(record=True,
321 module=self.module) as w:
322 self.module.simplefilter("always", UserWarning)
323
324 # bpo-33509: module_globals=None must not crash
325 self.module.warn_explicit('msg', UserWarning, "filename", 42,
326 module_globals=None)
327 self.assertEqual(len(w), 1)
328
329 # Invalid module_globals type
330 with self.assertRaises(TypeError):
331 self.module.warn_explicit('msg', UserWarning, "filename", 42,
332 module_globals=True)
333 self.assertEqual(len(w), 1)
334
335 # Empty module_globals
336 self.module.warn_explicit('msg', UserWarning, "filename", 42,
337 module_globals={})
338 self.assertEqual(len(w), 2)
339
340 def test_inheritance(self):
341 with original_warnings.catch_warnings(module=self.module) as w:
342 self.module.resetwarnings()
343 self.module.filterwarnings("error", category=Warning)
344 self.assertRaises(UserWarning, self.module.warn,
345 "FilterTests.test_inheritance", UserWarning)
346
347 def test_ordering(self):
348 with original_warnings.catch_warnings(record=True,
349 module=self.module) as w:
350 self.module.resetwarnings()
351 self.module.filterwarnings("ignore", category=UserWarning)
352 self.module.filterwarnings("error", category=UserWarning,
353 append=True)
354 del w[:]
355 try:
356 self.module.warn("FilterTests.test_ordering", UserWarning)
357 except UserWarning:
358 self.fail("order handling for actions failed")
359 self.assertEqual(len(w), 0)
360
361 def test_filterwarnings(self):
362 # Test filterwarnings().
363 # Implicitly also tests resetwarnings().
364 with original_warnings.catch_warnings(record=True,
365 module=self.module) as w:
366 self.module.filterwarnings("error", "", Warning, "", 0)
367 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
368
369 self.module.resetwarnings()
370 text = 'handle normally'
371 self.module.warn(text)
372 self.assertEqual(str(w[-1].message), text)
373 self.assertIs(w[-1].category, UserWarning)
374
375 self.module.filterwarnings("ignore", "", Warning, "", 0)
376 text = 'filtered out'
377 self.module.warn(text)
378 self.assertNotEqual(str(w[-1].message), text)
379
380 self.module.resetwarnings()
381 self.module.filterwarnings("error", "hex*", Warning, "", 0)
382 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
383 text = 'nonmatching text'
384 self.module.warn(text)
385 self.assertEqual(str(w[-1].message), text)
386 self.assertIs(w[-1].category, UserWarning)
387
388 def test_message_matching(self):
389 with original_warnings.catch_warnings(record=True,
390 module=self.module) as w:
391 self.module.simplefilter("ignore", UserWarning)
392 self.module.filterwarnings("error", "match", UserWarning)
393 self.assertRaises(UserWarning, self.module.warn, "match")
394 self.assertRaises(UserWarning, self.module.warn, "match prefix")
395 self.module.warn("suffix match")
396 self.assertEqual(w, [])
397 self.module.warn("something completely different")
398 self.assertEqual(w, [])
399
400 def test_mutate_filter_list(self):
401 class X:
402 def match(self, a):
403 L[:] = []
404
405 L = [("default",X(),UserWarning,X(),0) for i in range(2)]
406 with original_warnings.catch_warnings(record=True,
407 module=self.module) as w:
408 self.module.filters = L
409 self.module.warn_explicit(UserWarning("b"), None, "f.py", 42)
410 self.assertEqual(str(w[-1].message), "b")
411
412 def test_filterwarnings_duplicate_filters(self):
413 with original_warnings.catch_warnings(module=self.module):
414 self.module.resetwarnings()
415 self.module.filterwarnings("error", category=UserWarning)
416 self.assertEqual(len(self.module.filters), 1)
417 self.module.filterwarnings("ignore", category=UserWarning)
418 self.module.filterwarnings("error", category=UserWarning)
419 self.assertEqual(
420 len(self.module.filters), 2,
421 "filterwarnings inserted duplicate filter"
422 )
423 self.assertEqual(
424 self.module.filters[0][0], "error",
425 "filterwarnings did not promote filter to "
426 "the beginning of list"
427 )
428
429 def test_simplefilter_duplicate_filters(self):
430 with original_warnings.catch_warnings(module=self.module):
431 self.module.resetwarnings()
432 self.module.simplefilter("error", category=UserWarning)
433 self.assertEqual(len(self.module.filters), 1)
434 self.module.simplefilter("ignore", category=UserWarning)
435 self.module.simplefilter("error", category=UserWarning)
436 self.assertEqual(
437 len(self.module.filters), 2,
438 "simplefilter inserted duplicate filter"
439 )
440 self.assertEqual(
441 self.module.filters[0][0], "error",
442 "simplefilter did not promote filter to the beginning of list"
443 )
444
445 def test_append_duplicate(self):
446 with original_warnings.catch_warnings(module=self.module,
447 record=True) as w:
448 self.module.resetwarnings()
449 self.module.simplefilter("ignore")
450 self.module.simplefilter("error", append=True)
451 self.module.simplefilter("ignore", append=True)
452 self.module.warn("test_append_duplicate", category=UserWarning)
453 self.assertEqual(len(self.module.filters), 2,
454 "simplefilter inserted duplicate filter"
455 )
456 self.assertEqual(len(w), 0,
457 "appended duplicate changed order of filters"
458 )
459
460 def test_argument_validation(self):
461 with self.assertRaises(ValueError):
462 self.module.filterwarnings(action='foo')
463 with self.assertRaises(TypeError):
464 self.module.filterwarnings('ignore', message=0)
465 with self.assertRaises(TypeError):
466 self.module.filterwarnings('ignore', category=0)
467 with self.assertRaises(TypeError):
468 self.module.filterwarnings('ignore', category=int)
469 with self.assertRaises(TypeError):
470 self.module.filterwarnings('ignore', module=0)
471 with self.assertRaises(TypeError):
472 self.module.filterwarnings('ignore', lineno=int)
473 with self.assertRaises(ValueError):
474 self.module.filterwarnings('ignore', lineno=-1)
475 with self.assertRaises(ValueError):
476 self.module.simplefilter(action='foo')
477 with self.assertRaises(TypeError):
478 self.module.simplefilter('ignore', lineno=int)
479 with self.assertRaises(ValueError):
480 self.module.simplefilter('ignore', lineno=-1)
481
482 def test_catchwarnings_with_simplefilter_ignore(self):
483 with original_warnings.catch_warnings(module=self.module):
484 self.module.resetwarnings()
485 self.module.simplefilter("error")
486 with self.module.catch_warnings(
487 module=self.module, action="ignore"
488 ):
489 self.module.warn("This will be ignored")
490
491 def test_catchwarnings_with_simplefilter_error(self):
492 with original_warnings.catch_warnings(module=self.module):
493 self.module.resetwarnings()
494 with self.module.catch_warnings(
495 module=self.module, action="error", category=FutureWarning
496 ):
497 with support.captured_stderr() as stderr:
498 error_msg = "Other types of warnings are not errors"
499 self.module.warn(error_msg)
500 self.assertRaises(FutureWarning,
501 self.module.warn, FutureWarning("msg"))
502 stderr = stderr.getvalue()
503 self.assertIn(error_msg, stderr)
504
505 class CFilterTests(FilterTests, unittest.TestCase):
506 module = c_warnings
507
508 class PyFilterTests(FilterTests, unittest.TestCase):
509 module = py_warnings
510
511
512 class WarnTests(BaseTest):
513
514 """Test warnings.warn() and warnings.warn_explicit()."""
515
516 def test_message(self):
517 with original_warnings.catch_warnings(record=True,
518 module=self.module) as w:
519 self.module.simplefilter("once")
520 for i in range(4):
521 text = 'multi %d' %i # Different text on each call.
522 self.module.warn(text)
523 self.assertEqual(str(w[-1].message), text)
524 self.assertIs(w[-1].category, UserWarning)
525
526 # Issue 3639
527 def test_warn_nonstandard_types(self):
528 # warn() should handle non-standard types without issue.
529 for ob in (Warning, None, 42):
530 with original_warnings.catch_warnings(record=True,
531 module=self.module) as w:
532 self.module.simplefilter("once")
533 self.module.warn(ob)
534 # Don't directly compare objects since
535 # ``Warning() != Warning()``.
536 self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
537
538 def test_filename(self):
539 with warnings_state(self.module):
540 with original_warnings.catch_warnings(record=True,
541 module=self.module) as w:
542 warning_tests.inner("spam1")
543 self.assertEqual(os.path.basename(w[-1].filename),
544 "stacklevel.py")
545 warning_tests.outer("spam2")
546 self.assertEqual(os.path.basename(w[-1].filename),
547 "stacklevel.py")
548
549 def test_stacklevel(self):
550 # Test stacklevel argument
551 # make sure all messages are different, so the warning won't be skipped
552 with warnings_state(self.module):
553 with original_warnings.catch_warnings(record=True,
554 module=self.module) as w:
555 warning_tests.inner("spam3", stacklevel=1)
556 self.assertEqual(os.path.basename(w[-1].filename),
557 "stacklevel.py")
558 warning_tests.outer("spam4", stacklevel=1)
559 self.assertEqual(os.path.basename(w[-1].filename),
560 "stacklevel.py")
561
562 warning_tests.inner("spam5", stacklevel=2)
563 self.assertEqual(os.path.basename(w[-1].filename),
564 "__init__.py")
565 warning_tests.outer("spam6", stacklevel=2)
566 self.assertEqual(os.path.basename(w[-1].filename),
567 "stacklevel.py")
568 warning_tests.outer("spam6.5", stacklevel=3)
569 self.assertEqual(os.path.basename(w[-1].filename),
570 "__init__.py")
571
572 warning_tests.inner("spam7", stacklevel=9999)
573 self.assertEqual(os.path.basename(w[-1].filename),
574 "<sys>")
575
576 def test_stacklevel_import(self):
577 # Issue #24305: With stacklevel=2, module-level warnings should work.
578 import_helper.unload('test.test_warnings.data.import_warning')
579 with warnings_state(self.module):
580 with original_warnings.catch_warnings(record=True,
581 module=self.module) as w:
582 self.module.simplefilter('always')
583 import test.test_warnings.data.import_warning
584 self.assertEqual(len(w), 1)
585 self.assertEqual(w[0].filename, __file__)
586
587 def test_skip_file_prefixes(self):
588 with warnings_state(self.module):
589 with original_warnings.catch_warnings(record=True,
590 module=self.module) as w:
591 self.module.simplefilter('always')
592
593 # Warning never attributed to the data/ package.
594 package_helper.inner_api(
595 "inner_api", stacklevel=2,
596 warnings_module=warning_tests.warnings)
597 self.assertEqual(w[-1].filename, __file__)
598 warning_tests.package("package api", stacklevel=2)
599 self.assertEqual(w[-1].filename, __file__)
600 self.assertEqual(w[-2].filename, w[-1].filename)
601 # Low stacklevels are overridden to 2 behavior.
602 warning_tests.package("package api 1", stacklevel=1)
603 self.assertEqual(w[-1].filename, __file__)
604 warning_tests.package("package api 0", stacklevel=0)
605 self.assertEqual(w[-1].filename, __file__)
606 warning_tests.package("package api -99", stacklevel=-99)
607 self.assertEqual(w[-1].filename, __file__)
608
609 # The stacklevel still goes up out of the package.
610 warning_tests.package("prefix02", stacklevel=3)
611 self.assertIn("unittest", w[-1].filename)
612
613 def test_skip_file_prefixes_type_errors(self):
614 with warnings_state(self.module):
615 warn = warning_tests.warnings.warn
616 with self.assertRaises(TypeError):
617 warn("msg", skip_file_prefixes=[])
618 with self.assertRaises(TypeError):
619 warn("msg", skip_file_prefixes=(b"bytes",))
620 with self.assertRaises(TypeError):
621 warn("msg", skip_file_prefixes="a sequence of strs")
622
623 def test_exec_filename(self):
624 filename = "<warnings-test>"
625 codeobj = compile(("import warnings\n"
626 "warnings.warn('hello', UserWarning)"),
627 filename, "exec")
628 with original_warnings.catch_warnings(record=True) as w:
629 self.module.simplefilter("always", category=UserWarning)
630 exec(codeobj)
631 self.assertEqual(w[0].filename, filename)
632
633 def test_warn_explicit_non_ascii_filename(self):
634 with original_warnings.catch_warnings(record=True,
635 module=self.module) as w:
636 self.module.resetwarnings()
637 self.module.filterwarnings("always", category=UserWarning)
638 filenames = ["nonascii\xe9\u20ac"]
639 if not support.is_emscripten:
640 # JavaScript does not like surrogates.
641 # Invalid UTF-8 leading byte 0x80 encountered when
642 # deserializing a UTF-8 string in wasm memory to a JS
643 # string!
644 filenames.append("surrogate\udc80")
645 for filename in filenames:
646 try:
647 os.fsencode(filename)
648 except UnicodeEncodeError:
649 continue
650 self.module.warn_explicit("text", UserWarning, filename, 1)
651 self.assertEqual(w[-1].filename, filename)
652
653 def test_warn_explicit_type_errors(self):
654 # warn_explicit() should error out gracefully if it is given objects
655 # of the wrong types.
656 # lineno is expected to be an integer.
657 self.assertRaises(TypeError, self.module.warn_explicit,
658 None, UserWarning, None, None)
659 # Either 'message' needs to be an instance of Warning or 'category'
660 # needs to be a subclass.
661 self.assertRaises(TypeError, self.module.warn_explicit,
662 None, None, None, 1)
663 # 'registry' must be a dict or None.
664 self.assertRaises((TypeError, AttributeError),
665 self.module.warn_explicit,
666 None, Warning, None, 1, registry=42)
667
668 def test_bad_str(self):
669 # issue 6415
670 # Warnings instance with a bad format string for __str__ should not
671 # trigger a bus error.
672 class BadStrWarning(Warning):
673 """Warning with a bad format string for __str__."""
674 def __str__(self):
675 return ("A bad formatted string %(err)" %
676 {"err" : "there is no %(err)s"})
677
678 with self.assertRaises(ValueError):
679 self.module.warn(BadStrWarning())
680
681 def test_warning_classes(self):
682 class MyWarningClass(Warning):
683 pass
684
685 class NonWarningSubclass:
686 pass
687
688 # passing a non-subclass of Warning should raise a TypeError
689 with self.assertRaises(TypeError) as cm:
690 self.module.warn('bad warning category', '')
691 self.assertIn('category must be a Warning subclass, not ',
692 str(cm.exception))
693
694 with self.assertRaises(TypeError) as cm:
695 self.module.warn('bad warning category', NonWarningSubclass)
696 self.assertIn('category must be a Warning subclass, not ',
697 str(cm.exception))
698
699 # check that warning instances also raise a TypeError
700 with self.assertRaises(TypeError) as cm:
701 self.module.warn('bad warning category', MyWarningClass())
702 self.assertIn('category must be a Warning subclass, not ',
703 str(cm.exception))
704
705 with original_warnings.catch_warnings(module=self.module):
706 self.module.resetwarnings()
707 self.module.filterwarnings('default')
708 with self.assertWarns(MyWarningClass) as cm:
709 self.module.warn('good warning category', MyWarningClass)
710 self.assertEqual('good warning category', str(cm.warning))
711
712 with self.assertWarns(UserWarning) as cm:
713 self.module.warn('good warning category', None)
714 self.assertEqual('good warning category', str(cm.warning))
715
716 with self.assertWarns(MyWarningClass) as cm:
717 self.module.warn('good warning category', MyWarningClass)
718 self.assertIsInstance(cm.warning, Warning)
719
720 def check_module_globals(self, module_globals):
721 with original_warnings.catch_warnings(module=self.module, record=True) as w:
722 self.module.filterwarnings('default')
723 self.module.warn_explicit(
724 'eggs', UserWarning, 'bar', 1,
725 module_globals=module_globals)
726 self.assertEqual(len(w), 1)
727 self.assertEqual(w[0].category, UserWarning)
728 self.assertEqual(str(w[0].message), 'eggs')
729
730 def check_module_globals_error(self, module_globals, errmsg, errtype=ValueError):
731 if self.module is py_warnings:
732 self.check_module_globals(module_globals)
733 return
734 with original_warnings.catch_warnings(module=self.module, record=True) as w:
735 self.module.filterwarnings('always')
736 with self.assertRaisesRegex(errtype, re.escape(errmsg)):
737 self.module.warn_explicit(
738 'eggs', UserWarning, 'bar', 1,
739 module_globals=module_globals)
740 self.assertEqual(len(w), 0)
741
742 def check_module_globals_deprecated(self, module_globals, msg):
743 if self.module is py_warnings:
744 self.check_module_globals(module_globals)
745 return
746 with original_warnings.catch_warnings(module=self.module, record=True) as w:
747 self.module.filterwarnings('always')
748 self.module.warn_explicit(
749 'eggs', UserWarning, 'bar', 1,
750 module_globals=module_globals)
751 self.assertEqual(len(w), 2)
752 self.assertEqual(w[0].category, DeprecationWarning)
753 self.assertEqual(str(w[0].message), msg)
754 self.assertEqual(w[1].category, UserWarning)
755 self.assertEqual(str(w[1].message), 'eggs')
756
757 def test_gh86298_no_loader_and_no_spec(self):
758 self.check_module_globals({'__name__': 'bar'})
759
760 def test_gh86298_loader_is_none_and_no_spec(self):
761 self.check_module_globals({'__name__': 'bar', '__loader__': None})
762
763 def test_gh86298_no_loader_and_spec_is_none(self):
764 self.check_module_globals_error(
765 {'__name__': 'bar', '__spec__': None},
766 'Module globals is missing a __spec__.loader')
767
768 def test_gh86298_loader_is_none_and_spec_is_none(self):
769 self.check_module_globals_error(
770 {'__name__': 'bar', '__loader__': None, '__spec__': None},
771 'Module globals is missing a __spec__.loader')
772
773 def test_gh86298_loader_is_none_and_spec_loader_is_none(self):
774 self.check_module_globals_error(
775 {'__name__': 'bar', '__loader__': None,
776 '__spec__': types.SimpleNamespace(loader=None)},
777 'Module globals is missing a __spec__.loader')
778
779 def test_gh86298_no_spec(self):
780 self.check_module_globals_deprecated(
781 {'__name__': 'bar', '__loader__': object()},
782 'Module globals is missing a __spec__.loader')
783
784 def test_gh86298_spec_is_none(self):
785 self.check_module_globals_deprecated(
786 {'__name__': 'bar', '__loader__': object(), '__spec__': None},
787 'Module globals is missing a __spec__.loader')
788
789 def test_gh86298_no_spec_loader(self):
790 self.check_module_globals_deprecated(
791 {'__name__': 'bar', '__loader__': object(),
792 '__spec__': types.SimpleNamespace()},
793 'Module globals is missing a __spec__.loader')
794
795 def test_gh86298_loader_and_spec_loader_disagree(self):
796 self.check_module_globals_deprecated(
797 {'__name__': 'bar', '__loader__': object(),
798 '__spec__': types.SimpleNamespace(loader=object())},
799 'Module globals; __loader__ != __spec__.loader')
800
801 def test_gh86298_no_loader_and_no_spec_loader(self):
802 self.check_module_globals_error(
803 {'__name__': 'bar', '__spec__': types.SimpleNamespace()},
804 'Module globals is missing a __spec__.loader', AttributeError)
805
806 def test_gh86298_no_loader_with_spec_loader_okay(self):
807 self.check_module_globals(
808 {'__name__': 'bar',
809 '__spec__': types.SimpleNamespace(loader=object())})
810
811 class CWarnTests(WarnTests, unittest.TestCase):
812 module = c_warnings
813
814 # As an early adopter, we sanity check the
815 # test.import_helper.import_fresh_module utility function
816 def test_accelerated(self):
817 self.assertIsNot(original_warnings, self.module)
818 self.assertFalse(hasattr(self.module.warn, '__code__'))
819
820 class PyWarnTests(WarnTests, unittest.TestCase):
821 module = py_warnings
822
823 # As an early adopter, we sanity check the
824 # test.import_helper.import_fresh_module utility function
825 def test_pure_python(self):
826 self.assertIsNot(original_warnings, self.module)
827 self.assertTrue(hasattr(self.module.warn, '__code__'))
828
829
830 class WCmdLineTests(BaseTest):
831
832 def test_improper_input(self):
833 # Uses the private _setoption() function to test the parsing
834 # of command-line warning arguments
835 with original_warnings.catch_warnings(module=self.module):
836 self.assertRaises(self.module._OptionError,
837 self.module._setoption, '1:2:3:4:5:6')
838 self.assertRaises(self.module._OptionError,
839 self.module._setoption, 'bogus::Warning')
840 self.assertRaises(self.module._OptionError,
841 self.module._setoption, 'ignore:2::4:-5')
842 with self.assertRaises(self.module._OptionError):
843 self.module._setoption('ignore::123')
844 with self.assertRaises(self.module._OptionError):
845 self.module._setoption('ignore::123abc')
846 with self.assertRaises(self.module._OptionError):
847 self.module._setoption('ignore::===')
848 with self.assertRaisesRegex(self.module._OptionError, 'Wärning'):
849 self.module._setoption('ignore::Wärning')
850 self.module._setoption('error::Warning::0')
851 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
852
853 def test_import_from_module(self):
854 with original_warnings.catch_warnings(module=self.module):
855 self.module._setoption('ignore::Warning')
856 with self.assertRaises(self.module._OptionError):
857 self.module._setoption('ignore::TestWarning')
858 with self.assertRaises(self.module._OptionError):
859 self.module._setoption('ignore::test.test_warnings.bogus')
860 self.module._setoption('error::test.test_warnings.TestWarning')
861 with self.assertRaises(TestWarning):
862 self.module.warn('test warning', TestWarning)
863
864
865 class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
866 module = c_warnings
867
868
869 class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
870 module = py_warnings
871
872 def test_improper_option(self):
873 # Same as above, but check that the message is printed out when
874 # the interpreter is executed. This also checks that options are
875 # actually parsed at all.
876 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
877 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
878
879 def test_warnings_bootstrap(self):
880 # Check that the warnings module does get loaded when -W<some option>
881 # is used (see issue #10372 for an example of silent bootstrap failure).
882 rc, out, err = assert_python_ok("-Wi", "-c",
883 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
884 # '-Wi' was observed
885 self.assertFalse(out.strip())
886 self.assertNotIn(b'RuntimeWarning', err)
887
888
889 class _WarningsTests(BaseTest, unittest.TestCase):
890
891 """Tests specific to the _warnings module."""
892
893 module = c_warnings
894
895 def test_filter(self):
896 # Everything should function even if 'filters' is not in warnings.
897 with original_warnings.catch_warnings(module=self.module) as w:
898 self.module.filterwarnings("error", "", Warning, "", 0)
899 self.assertRaises(UserWarning, self.module.warn,
900 'convert to error')
901 del self.module.filters
902 self.assertRaises(UserWarning, self.module.warn,
903 'convert to error')
904
905 def test_onceregistry(self):
906 # Replacing or removing the onceregistry should be okay.
907 global __warningregistry__
908 message = UserWarning('onceregistry test')
909 try:
910 original_registry = self.module.onceregistry
911 __warningregistry__ = {}
912 with original_warnings.catch_warnings(record=True,
913 module=self.module) as w:
914 self.module.resetwarnings()
915 self.module.filterwarnings("once", category=UserWarning)
916 self.module.warn_explicit(message, UserWarning, "file", 42)
917 self.assertEqual(w[-1].message, message)
918 del w[:]
919 self.module.warn_explicit(message, UserWarning, "file", 42)
920 self.assertEqual(len(w), 0)
921 # Test the resetting of onceregistry.
922 self.module.onceregistry = {}
923 __warningregistry__ = {}
924 self.module.warn('onceregistry test')
925 self.assertEqual(w[-1].message.args, message.args)
926 # Removal of onceregistry is okay.
927 del w[:]
928 del self.module.onceregistry
929 __warningregistry__ = {}
930 self.module.warn_explicit(message, UserWarning, "file", 42)
931 self.assertEqual(len(w), 0)
932 finally:
933 self.module.onceregistry = original_registry
934
935 def test_default_action(self):
936 # Replacing or removing defaultaction should be okay.
937 message = UserWarning("defaultaction test")
938 original = self.module.defaultaction
939 try:
940 with original_warnings.catch_warnings(record=True,
941 module=self.module) as w:
942 self.module.resetwarnings()
943 registry = {}
944 self.module.warn_explicit(message, UserWarning, "<test>", 42,
945 registry=registry)
946 self.assertEqual(w[-1].message, message)
947 self.assertEqual(len(w), 1)
948 # One actual registry key plus the "version" key
949 self.assertEqual(len(registry), 2)
950 self.assertIn("version", registry)
951 del w[:]
952 # Test removal.
953 del self.module.defaultaction
954 __warningregistry__ = {}
955 registry = {}
956 self.module.warn_explicit(message, UserWarning, "<test>", 43,
957 registry=registry)
958 self.assertEqual(w[-1].message, message)
959 self.assertEqual(len(w), 1)
960 self.assertEqual(len(registry), 2)
961 del w[:]
962 # Test setting.
963 self.module.defaultaction = "ignore"
964 __warningregistry__ = {}
965 registry = {}
966 self.module.warn_explicit(message, UserWarning, "<test>", 44,
967 registry=registry)
968 self.assertEqual(len(w), 0)
969 finally:
970 self.module.defaultaction = original
971
972 def test_showwarning_missing(self):
973 # Test that showwarning() missing is okay.
974 text = 'del showwarning test'
975 with original_warnings.catch_warnings(module=self.module):
976 self.module.filterwarnings("always", category=UserWarning)
977 del self.module.showwarning
978 with support.captured_output('stderr') as stream:
979 self.module.warn(text)
980 result = stream.getvalue()
981 self.assertIn(text, result)
982
983 def test_showwarnmsg_missing(self):
984 # Test that _showwarnmsg() missing is okay.
985 text = 'del _showwarnmsg test'
986 with original_warnings.catch_warnings(module=self.module):
987 self.module.filterwarnings("always", category=UserWarning)
988
989 show = self.module._showwarnmsg
990 try:
991 del self.module._showwarnmsg
992 with support.captured_output('stderr') as stream:
993 self.module.warn(text)
994 result = stream.getvalue()
995 finally:
996 self.module._showwarnmsg = show
997 self.assertIn(text, result)
998
999 def test_showwarning_not_callable(self):
1000 with original_warnings.catch_warnings(module=self.module):
1001 self.module.filterwarnings("always", category=UserWarning)
1002 self.module.showwarning = print
1003 with support.captured_output('stdout'):
1004 self.module.warn('Warning!')
1005 self.module.showwarning = 23
1006 self.assertRaises(TypeError, self.module.warn, "Warning!")
1007
1008 def test_show_warning_output(self):
1009 # With showwarning() missing, make sure that output is okay.
1010 text = 'test show_warning'
1011 with original_warnings.catch_warnings(module=self.module):
1012 self.module.filterwarnings("always", category=UserWarning)
1013 del self.module.showwarning
1014 with support.captured_output('stderr') as stream:
1015 warning_tests.inner(text)
1016 result = stream.getvalue()
1017 self.assertEqual(result.count('\n'), 2,
1018 "Too many newlines in %r" % result)
1019 first_line, second_line = result.split('\n', 1)
1020 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
1021 first_line_parts = first_line.rsplit(':', 3)
1022 path, line, warning_class, message = first_line_parts
1023 line = int(line)
1024 self.assertEqual(expected_file, path)
1025 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
1026 self.assertEqual(message, ' ' + text)
1027 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
1028 assert expected_line
1029 self.assertEqual(second_line, expected_line)
1030
1031 def test_filename_none(self):
1032 # issue #12467: race condition if a warning is emitted at shutdown
1033 globals_dict = globals()
1034 oldfile = globals_dict['__file__']
1035 try:
1036 catch = original_warnings.catch_warnings(record=True,
1037 module=self.module)
1038 with catch as w:
1039 self.module.filterwarnings("always", category=UserWarning)
1040 globals_dict['__file__'] = None
1041 original_warnings.warn('test', UserWarning)
1042 self.assertTrue(len(w))
1043 finally:
1044 globals_dict['__file__'] = oldfile
1045
1046 def test_stderr_none(self):
1047 rc, stdout, stderr = assert_python_ok("-c",
1048 "import sys; sys.stderr = None; "
1049 "import warnings; warnings.simplefilter('always'); "
1050 "warnings.warn('Warning!')")
1051 self.assertEqual(stdout, b'')
1052 self.assertNotIn(b'Warning!', stderr)
1053 self.assertNotIn(b'Error', stderr)
1054
1055 def test_issue31285(self):
1056 # warn_explicit() should neither raise a SystemError nor cause an
1057 # assertion failure, in case the return value of get_source() has a
1058 # bad splitlines() method.
1059 get_source_called = []
1060 def get_module_globals(*, splitlines_ret_val):
1061 class BadSource(str):
1062 def splitlines(self):
1063 return splitlines_ret_val
1064
1065 class BadLoader:
1066 def get_source(self, fullname):
1067 get_source_called.append(splitlines_ret_val)
1068 return BadSource('spam')
1069
1070 loader = BadLoader()
1071 spec = importlib.machinery.ModuleSpec('foobar', loader)
1072 return {'__loader__': loader,
1073 '__spec__': spec,
1074 '__name__': 'foobar'}
1075
1076
1077 wmod = self.module
1078 with original_warnings.catch_warnings(module=wmod):
1079 wmod.filterwarnings('default', category=UserWarning)
1080
1081 linecache.clearcache()
1082 with support.captured_stderr() as stderr:
1083 wmod.warn_explicit(
1084 'foo', UserWarning, 'bar', 1,
1085 module_globals=get_module_globals(splitlines_ret_val=42))
1086 self.assertIn('UserWarning: foo', stderr.getvalue())
1087 self.assertEqual(get_source_called, [42])
1088
1089 linecache.clearcache()
1090 with support.swap_attr(wmod, '_showwarnmsg', None):
1091 del wmod._showwarnmsg
1092 with support.captured_stderr() as stderr:
1093 wmod.warn_explicit(
1094 'eggs', UserWarning, 'bar', 1,
1095 module_globals=get_module_globals(splitlines_ret_val=[42]))
1096 self.assertIn('UserWarning: eggs', stderr.getvalue())
1097 self.assertEqual(get_source_called, [42, [42]])
1098 linecache.clearcache()
1099
1100 @support.cpython_only
1101 def test_issue31411(self):
1102 # warn_explicit() shouldn't raise a SystemError in case
1103 # warnings.onceregistry isn't a dictionary.
1104 wmod = self.module
1105 with original_warnings.catch_warnings(module=wmod):
1106 wmod.filterwarnings('once')
1107 with support.swap_attr(wmod, 'onceregistry', None):
1108 with self.assertRaises(TypeError):
1109 wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
1110
1111 @support.cpython_only
1112 def test_issue31416(self):
1113 # warn_explicit() shouldn't cause an assertion failure in case of a
1114 # bad warnings.filters or warnings.defaultaction.
1115 wmod = self.module
1116 with original_warnings.catch_warnings(module=wmod):
1117 wmod.filters = [(None, None, Warning, None, 0)]
1118 with self.assertRaises(TypeError):
1119 wmod.warn_explicit('foo', Warning, 'bar', 1)
1120
1121 wmod.filters = []
1122 with support.swap_attr(wmod, 'defaultaction', None), \
1123 self.assertRaises(TypeError):
1124 wmod.warn_explicit('foo', Warning, 'bar', 1)
1125
1126 @support.cpython_only
1127 def test_issue31566(self):
1128 # warn() shouldn't cause an assertion failure in case of a bad
1129 # __name__ global.
1130 with original_warnings.catch_warnings(module=self.module):
1131 self.module.filterwarnings('error', category=UserWarning)
1132 with support.swap_item(globals(), '__name__', b'foo'), \
1133 support.swap_item(globals(), '__file__', None):
1134 self.assertRaises(UserWarning, self.module.warn, 'bar')
1135
1136
1137 class WarningsDisplayTests(BaseTest):
1138
1139 """Test the displaying of warnings and the ability to overload functions
1140 related to displaying warnings."""
1141
1142 def test_formatwarning(self):
1143 message = "msg"
1144 category = Warning
1145 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
1146 line_num = 5
1147 file_line = linecache.getline(file_name, line_num).strip()
1148 format = "%s:%s: %s: %s\n %s\n"
1149 expect = format % (file_name, line_num, category.__name__, message,
1150 file_line)
1151 self.assertEqual(expect, self.module.formatwarning(message,
1152 category, file_name, line_num))
1153 # Test the 'line' argument.
1154 file_line += " for the win!"
1155 expect = format % (file_name, line_num, category.__name__, message,
1156 file_line)
1157 self.assertEqual(expect, self.module.formatwarning(message,
1158 category, file_name, line_num, file_line))
1159
1160 def test_showwarning(self):
1161 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
1162 line_num = 3
1163 expected_file_line = linecache.getline(file_name, line_num).strip()
1164 message = 'msg'
1165 category = Warning
1166 file_object = StringIO()
1167 expect = self.module.formatwarning(message, category, file_name,
1168 line_num)
1169 self.module.showwarning(message, category, file_name, line_num,
1170 file_object)
1171 self.assertEqual(file_object.getvalue(), expect)
1172 # Test 'line' argument.
1173 expected_file_line += "for the win!"
1174 expect = self.module.formatwarning(message, category, file_name,
1175 line_num, expected_file_line)
1176 file_object = StringIO()
1177 self.module.showwarning(message, category, file_name, line_num,
1178 file_object, expected_file_line)
1179 self.assertEqual(expect, file_object.getvalue())
1180
1181 def test_formatwarning_override(self):
1182 # bpo-35178: Test that a custom formatwarning function gets the 'line'
1183 # argument as a positional argument, and not only as a keyword argument
1184 def myformatwarning(message, category, filename, lineno, text):
1185 return f'm={message}:c={category}:f={filename}:l={lineno}:t={text}'
1186
1187 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
1188 line_num = 3
1189 file_line = linecache.getline(file_name, line_num).strip()
1190 message = 'msg'
1191 category = Warning
1192 file_object = StringIO()
1193 expected = f'm={message}:c={category}:f={file_name}:l={line_num}' + \
1194 f':t={file_line}'
1195 with support.swap_attr(self.module, 'formatwarning', myformatwarning):
1196 self.module.showwarning(message, category, file_name, line_num,
1197 file_object, file_line)
1198 self.assertEqual(file_object.getvalue(), expected)
1199
1200
1201 class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
1202 module = c_warnings
1203
1204 class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
1205 module = py_warnings
1206
1207 def test_tracemalloc(self):
1208 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1209
1210 with open(os_helper.TESTFN, 'w', encoding="utf-8") as fp:
1211 fp.write(textwrap.dedent("""
1212 def func():
1213 f = open(__file__, "rb")
1214 # Emit ResourceWarning
1215 f = None
1216
1217 func()
1218 """))
1219
1220 def run(*args):
1221 res = assert_python_ok(*args, PYTHONIOENCODING='utf-8')
1222 stderr = res.err.decode('utf-8', 'replace')
1223 stderr = '\n'.join(stderr.splitlines())
1224
1225 # normalize newlines
1226 stderr = re.sub('<.*>', '<...>', stderr)
1227 return stderr
1228
1229 # tracemalloc disabled
1230 filename = os.path.abspath(os_helper.TESTFN)
1231 stderr = run('-Wd', os_helper.TESTFN)
1232 expected = textwrap.dedent(f'''
1233 {filename}:5: ResourceWarning: unclosed file <...>
1234 f = None
1235 ResourceWarning: Enable tracemalloc to get the object allocation traceback
1236 ''').strip()
1237 self.assertEqual(stderr, expected)
1238
1239 # tracemalloc enabled
1240 stderr = run('-Wd', '-X', 'tracemalloc=2', os_helper.TESTFN)
1241 expected = textwrap.dedent(f'''
1242 {filename}:5: ResourceWarning: unclosed file <...>
1243 f = None
1244 Object allocated at (most recent call last):
1245 File "{filename}", lineno 7
1246 func()
1247 File "{filename}", lineno 3
1248 f = open(__file__, "rb")
1249 ''').strip()
1250 self.assertEqual(stderr, expected)
1251
1252
1253 class CatchWarningTests(BaseTest):
1254
1255 """Test catch_warnings()."""
1256
1257 def test_catch_warnings_restore(self):
1258 wmod = self.module
1259 orig_filters = wmod.filters
1260 orig_showwarning = wmod.showwarning
1261 # Ensure both showwarning and filters are restored when recording
1262 with wmod.catch_warnings(module=wmod, record=True):
1263 wmod.filters = wmod.showwarning = object()
1264 self.assertIs(wmod.filters, orig_filters)
1265 self.assertIs(wmod.showwarning, orig_showwarning)
1266 # Same test, but with recording disabled
1267 with wmod.catch_warnings(module=wmod, record=False):
1268 wmod.filters = wmod.showwarning = object()
1269 self.assertIs(wmod.filters, orig_filters)
1270 self.assertIs(wmod.showwarning, orig_showwarning)
1271
1272 def test_catch_warnings_recording(self):
1273 wmod = self.module
1274 # Ensure warnings are recorded when requested
1275 with wmod.catch_warnings(module=wmod, record=True) as w:
1276 self.assertEqual(w, [])
1277 self.assertIs(type(w), list)
1278 wmod.simplefilter("always")
1279 wmod.warn("foo")
1280 self.assertEqual(str(w[-1].message), "foo")
1281 wmod.warn("bar")
1282 self.assertEqual(str(w[-1].message), "bar")
1283 self.assertEqual(str(w[0].message), "foo")
1284 self.assertEqual(str(w[1].message), "bar")
1285 del w[:]
1286 self.assertEqual(w, [])
1287 # Ensure warnings are not recorded when not requested
1288 orig_showwarning = wmod.showwarning
1289 with wmod.catch_warnings(module=wmod, record=False) as w:
1290 self.assertIsNone(w)
1291 self.assertIs(wmod.showwarning, orig_showwarning)
1292
1293 def test_catch_warnings_reentry_guard(self):
1294 wmod = self.module
1295 # Ensure catch_warnings is protected against incorrect usage
1296 x = wmod.catch_warnings(module=wmod, record=True)
1297 self.assertRaises(RuntimeError, x.__exit__)
1298 with x:
1299 self.assertRaises(RuntimeError, x.__enter__)
1300 # Same test, but with recording disabled
1301 x = wmod.catch_warnings(module=wmod, record=False)
1302 self.assertRaises(RuntimeError, x.__exit__)
1303 with x:
1304 self.assertRaises(RuntimeError, x.__enter__)
1305
1306 def test_catch_warnings_defaults(self):
1307 wmod = self.module
1308 orig_filters = wmod.filters
1309 orig_showwarning = wmod.showwarning
1310 # Ensure default behaviour is not to record warnings
1311 with wmod.catch_warnings(module=wmod) as w:
1312 self.assertIsNone(w)
1313 self.assertIs(wmod.showwarning, orig_showwarning)
1314 self.assertIsNot(wmod.filters, orig_filters)
1315 self.assertIs(wmod.filters, orig_filters)
1316 if wmod is sys.modules['warnings']:
1317 # Ensure the default module is this one
1318 with wmod.catch_warnings() as w:
1319 self.assertIsNone(w)
1320 self.assertIs(wmod.showwarning, orig_showwarning)
1321 self.assertIsNot(wmod.filters, orig_filters)
1322 self.assertIs(wmod.filters, orig_filters)
1323
1324 def test_record_override_showwarning_before(self):
1325 # Issue #28835: If warnings.showwarning() was overridden, make sure
1326 # that catch_warnings(record=True) overrides it again.
1327 text = "This is a warning"
1328 wmod = self.module
1329 my_log = []
1330
1331 def my_logger(message, category, filename, lineno, file=None, line=None):
1332 nonlocal my_log
1333 my_log.append(message)
1334
1335 # Override warnings.showwarning() before calling catch_warnings()
1336 with support.swap_attr(wmod, 'showwarning', my_logger):
1337 with wmod.catch_warnings(module=wmod, record=True) as log:
1338 self.assertIsNot(wmod.showwarning, my_logger)
1339
1340 wmod.simplefilter("always")
1341 wmod.warn(text)
1342
1343 self.assertIs(wmod.showwarning, my_logger)
1344
1345 self.assertEqual(len(log), 1, log)
1346 self.assertEqual(log[0].message.args[0], text)
1347 self.assertEqual(my_log, [])
1348
1349 def test_record_override_showwarning_inside(self):
1350 # Issue #28835: It is possible to override warnings.showwarning()
1351 # in the catch_warnings(record=True) context manager.
1352 text = "This is a warning"
1353 wmod = self.module
1354 my_log = []
1355
1356 def my_logger(message, category, filename, lineno, file=None, line=None):
1357 nonlocal my_log
1358 my_log.append(message)
1359
1360 with wmod.catch_warnings(module=wmod, record=True) as log:
1361 wmod.simplefilter("always")
1362 wmod.showwarning = my_logger
1363 wmod.warn(text)
1364
1365 self.assertEqual(len(my_log), 1, my_log)
1366 self.assertEqual(my_log[0].args[0], text)
1367 self.assertEqual(log, [])
1368
1369 def test_check_warnings(self):
1370 # Explicit tests for the test.support convenience wrapper
1371 wmod = self.module
1372 if wmod is not sys.modules['warnings']:
1373 self.skipTest('module to test is not loaded warnings module')
1374 with warnings_helper.check_warnings(quiet=False) as w:
1375 self.assertEqual(w.warnings, [])
1376 wmod.simplefilter("always")
1377 wmod.warn("foo")
1378 self.assertEqual(str(w.message), "foo")
1379 wmod.warn("bar")
1380 self.assertEqual(str(w.message), "bar")
1381 self.assertEqual(str(w.warnings[0].message), "foo")
1382 self.assertEqual(str(w.warnings[1].message), "bar")
1383 w.reset()
1384 self.assertEqual(w.warnings, [])
1385
1386 with warnings_helper.check_warnings():
1387 # defaults to quiet=True without argument
1388 pass
1389 with warnings_helper.check_warnings(('foo', UserWarning)):
1390 wmod.warn("foo")
1391
1392 with self.assertRaises(AssertionError):
1393 with warnings_helper.check_warnings(('', RuntimeWarning)):
1394 # defaults to quiet=False with argument
1395 pass
1396 with self.assertRaises(AssertionError):
1397 with warnings_helper.check_warnings(('foo', RuntimeWarning)):
1398 wmod.warn("foo")
1399
1400 class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
1401 module = c_warnings
1402
1403 class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
1404 module = py_warnings
1405
1406
1407 class EnvironmentVariableTests(BaseTest):
1408
1409 def test_single_warning(self):
1410 rc, stdout, stderr = assert_python_ok("-c",
1411 "import sys; sys.stdout.write(str(sys.warnoptions))",
1412 PYTHONWARNINGS="ignore::DeprecationWarning",
1413 PYTHONDEVMODE="")
1414 self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
1415
1416 def test_comma_separated_warnings(self):
1417 rc, stdout, stderr = assert_python_ok("-c",
1418 "import sys; sys.stdout.write(str(sys.warnoptions))",
1419 PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning",
1420 PYTHONDEVMODE="")
1421 self.assertEqual(stdout,
1422 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
1423
1424 @force_not_colorized
1425 def test_envvar_and_command_line(self):
1426 rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
1427 "import sys; sys.stdout.write(str(sys.warnoptions))",
1428 PYTHONWARNINGS="ignore::DeprecationWarning",
1429 PYTHONDEVMODE="")
1430 self.assertEqual(stdout,
1431 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
1432
1433 @force_not_colorized
1434 def test_conflicting_envvar_and_command_line(self):
1435 rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
1436 "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
1437 "warnings.warn('Message', DeprecationWarning)",
1438 PYTHONWARNINGS="default::DeprecationWarning",
1439 PYTHONDEVMODE="")
1440 self.assertEqual(stdout,
1441 b"['default::DeprecationWarning', 'error::DeprecationWarning']")
1442 self.assertEqual(stderr.splitlines(),
1443 [b"Traceback (most recent call last):",
1444 b" File \"<string>\", line 1, in <module>",
1445 b' import sys, warnings; sys.stdout.write(str(sys.warnoptions)); warnings.w'
1446 b"arn('Message', DeprecationWarning)",
1447 b' ~~~~~~~~~~'
1448 b'~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^',
1449 b"DeprecationWarning: Message"])
1450
1451 def test_default_filter_configuration(self):
1452 pure_python_api = self.module is py_warnings
1453 if support.Py_DEBUG:
1454 expected_default_filters = []
1455 else:
1456 if pure_python_api:
1457 main_module_filter = re.compile("__main__")
1458 else:
1459 main_module_filter = "__main__"
1460 expected_default_filters = [
1461 ('default', None, DeprecationWarning, main_module_filter, 0),
1462 ('ignore', None, DeprecationWarning, None, 0),
1463 ('ignore', None, PendingDeprecationWarning, None, 0),
1464 ('ignore', None, ImportWarning, None, 0),
1465 ('ignore', None, ResourceWarning, None, 0),
1466 ]
1467 expected_output = [str(f).encode() for f in expected_default_filters]
1468
1469 if pure_python_api:
1470 # Disable the warnings acceleration module in the subprocess
1471 code = "import sys; sys.modules.pop('warnings', None); sys.modules['_warnings'] = None; "
1472 else:
1473 code = ""
1474 code += "import warnings; [print(f) for f in warnings.filters]"
1475
1476 rc, stdout, stderr = assert_python_ok("-c", code, __isolated=True)
1477 stdout_lines = [line.strip() for line in stdout.splitlines()]
1478 self.maxDiff = None
1479 self.assertEqual(stdout_lines, expected_output)
1480
1481
1482 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
1483 'requires non-ascii filesystemencoding')
1484 def test_nonascii(self):
1485 PYTHONWARNINGS="ignore:DeprecationWarning" + os_helper.FS_NONASCII
1486 rc, stdout, stderr = assert_python_ok("-c",
1487 "import sys; sys.stdout.write(str(sys.warnoptions))",
1488 PYTHONIOENCODING="utf-8",
1489 PYTHONWARNINGS=PYTHONWARNINGS,
1490 PYTHONDEVMODE="")
1491 self.assertEqual(stdout, str([PYTHONWARNINGS]).encode())
1492
1493 class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
1494 module = c_warnings
1495
1496 class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
1497 module = py_warnings
1498
1499
1500 class _DeprecatedTest(BaseTest, unittest.TestCase):
1501
1502 """Test _deprecated()."""
1503
1504 module = original_warnings
1505
1506 def test_warning(self):
1507 version = (3, 11, 0, "final", 0)
1508 test = [(4, 12), (4, 11), (4, 0), (3, 12)]
1509 for remove in test:
1510 msg = rf".*test_warnings.*{remove[0]}\.{remove[1]}"
1511 filter = msg, DeprecationWarning
1512 with self.subTest(remove=remove):
1513 with warnings_helper.check_warnings(filter, quiet=False):
1514 self.module._deprecated("test_warnings", remove=remove,
1515 _version=version)
1516
1517 version = (3, 11, 0, "alpha", 0)
1518 msg = r".*test_warnings.*3\.11"
1519 with warnings_helper.check_warnings((msg, DeprecationWarning), quiet=False):
1520 self.module._deprecated("test_warnings", remove=(3, 11),
1521 _version=version)
1522
1523 def test_RuntimeError(self):
1524 version = (3, 11, 0, "final", 0)
1525 test = [(2, 0), (2, 12), (3, 10)]
1526 for remove in test:
1527 with self.subTest(remove=remove):
1528 with self.assertRaises(RuntimeError):
1529 self.module._deprecated("test_warnings", remove=remove,
1530 _version=version)
1531 for level in ["beta", "candidate", "final"]:
1532 version = (3, 11, 0, level, 0)
1533 with self.subTest(releaselevel=level):
1534 with self.assertRaises(RuntimeError):
1535 self.module._deprecated("test_warnings", remove=(3, 11),
1536 _version=version)
1537
1538
1539 class BootstrapTest(unittest.TestCase):
1540
1541 def test_issue_8766(self):
1542 # "import encodings" emits a warning whereas the warnings is not loaded
1543 # or not completely loaded (warnings imports indirectly encodings by
1544 # importing linecache) yet
1545 with os_helper.temp_cwd() as cwd, os_helper.temp_cwd('encodings'):
1546 # encodings loaded by initfsencoding()
1547 assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
1548
1549 # Use -W to load warnings module at startup
1550 assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
1551
1552
1553 class FinalizationTest(unittest.TestCase):
1554 def test_finalization(self):
1555 # Issue #19421: warnings.warn() should not crash
1556 # during Python finalization
1557 code = """
1558 import warnings
1559 warn = warnings.warn
1560
1561 class A:
1562 def __del__(self):
1563 warn("test")
1564
1565 a=A()
1566 """
1567 rc, out, err = assert_python_ok("-c", code)
1568 self.assertEqual(err.decode().rstrip(),
1569 '<string>:7: UserWarning: test')
1570
1571 def test_late_resource_warning(self):
1572 # Issue #21925: Emitting a ResourceWarning late during the Python
1573 # shutdown must be logged.
1574
1575 expected = b"<sys>:0: ResourceWarning: unclosed file "
1576
1577 # don't import the warnings module
1578 # (_warnings will try to import it)
1579 code = "f = open(%a)" % __file__
1580 rc, out, err = assert_python_ok("-Wd", "-c", code)
1581 self.assertTrue(err.startswith(expected), ascii(err))
1582
1583 # import the warnings module
1584 code = "import warnings; f = open(%a)" % __file__
1585 rc, out, err = assert_python_ok("-Wd", "-c", code)
1586 self.assertTrue(err.startswith(expected), ascii(err))
1587
1588
1589 class DeprecatedTests(unittest.TestCase):
1590 def test_dunder_deprecated(self):
1591 @deprecated("A will go away soon")
1592 class A:
1593 pass
1594
1595 self.assertEqual(A.__deprecated__, "A will go away soon")
1596 self.assertIsInstance(A, type)
1597
1598 @deprecated("b will go away soon")
1599 def b():
1600 pass
1601
1602 self.assertEqual(b.__deprecated__, "b will go away soon")
1603 self.assertIsInstance(b, types.FunctionType)
1604
1605 @overload
1606 @deprecated("no more ints")
1607 def h(x: int) -> int: ...
1608 @overload
1609 def h(x: str) -> str: ...
1610 def h(x):
1611 return x
1612
1613 overloads = get_overloads(h)
1614 self.assertEqual(len(overloads), 2)
1615 self.assertEqual(overloads[0].__deprecated__, "no more ints")
1616
1617 def test_class(self):
1618 @deprecated("A will go away soon")
1619 class A:
1620 pass
1621
1622 with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
1623 A()
1624 with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
1625 with self.assertRaises(TypeError):
1626 A(42)
1627
1628 def test_class_with_init(self):
1629 @deprecated("HasInit will go away soon")
1630 class HasInit:
1631 def __init__(self, x):
1632 self.x = x
1633
1634 with self.assertWarnsRegex(DeprecationWarning, "HasInit will go away soon"):
1635 instance = HasInit(42)
1636 self.assertEqual(instance.x, 42)
1637
1638 def test_class_with_new(self):
1639 has_new_called = False
1640
1641 @deprecated("HasNew will go away soon")
1642 class HasNew:
1643 def __new__(cls, x):
1644 nonlocal has_new_called
1645 has_new_called = True
1646 return super().__new__(cls)
1647
1648 def __init__(self, x) -> None:
1649 self.x = x
1650
1651 with self.assertWarnsRegex(DeprecationWarning, "HasNew will go away soon"):
1652 instance = HasNew(42)
1653 self.assertEqual(instance.x, 42)
1654 self.assertTrue(has_new_called)
1655
1656 def test_class_with_inherited_new(self):
1657 new_base_called = False
1658
1659 class NewBase:
1660 def __new__(cls, x):
1661 nonlocal new_base_called
1662 new_base_called = True
1663 return super().__new__(cls)
1664
1665 def __init__(self, x) -> None:
1666 self.x = x
1667
1668 @deprecated("HasInheritedNew will go away soon")
1669 class HasInheritedNew(NewBase):
1670 pass
1671
1672 with self.assertWarnsRegex(DeprecationWarning, "HasInheritedNew will go away soon"):
1673 instance = HasInheritedNew(42)
1674 self.assertEqual(instance.x, 42)
1675 self.assertTrue(new_base_called)
1676
1677 def test_class_with_new_but_no_init(self):
1678 new_called = False
1679
1680 @deprecated("HasNewNoInit will go away soon")
1681 class HasNewNoInit:
1682 def __new__(cls, x):
1683 nonlocal new_called
1684 new_called = True
1685 obj = super().__new__(cls)
1686 obj.x = x
1687 return obj
1688
1689 with self.assertWarnsRegex(DeprecationWarning, "HasNewNoInit will go away soon"):
1690 instance = HasNewNoInit(42)
1691 self.assertEqual(instance.x, 42)
1692 self.assertTrue(new_called)
1693
1694 def test_mixin_class(self):
1695 @deprecated("Mixin will go away soon")
1696 class Mixin:
1697 pass
1698
1699 class Base:
1700 def __init__(self, a) -> None:
1701 self.a = a
1702
1703 with self.assertWarnsRegex(DeprecationWarning, "Mixin will go away soon"):
1704 class Child(Base, Mixin):
1705 pass
1706
1707 instance = Child(42)
1708 self.assertEqual(instance.a, 42)
1709
1710 def test_do_not_shadow_user_arguments(self):
1711 new_called = False
1712 new_called_cls = None
1713
1714 @deprecated("MyMeta will go away soon")
1715 class MyMeta(type):
1716 def __new__(mcs, name, bases, attrs, cls=None):
1717 nonlocal new_called, new_called_cls
1718 new_called = True
1719 new_called_cls = cls
1720 return super().__new__(mcs, name, bases, attrs)
1721
1722 with self.assertWarnsRegex(DeprecationWarning, "MyMeta will go away soon"):
1723 class Foo(metaclass=MyMeta, cls='haha'):
1724 pass
1725
1726 self.assertTrue(new_called)
1727 self.assertEqual(new_called_cls, 'haha')
1728
1729 def test_existing_init_subclass(self):
1730 @deprecated("C will go away soon")
1731 class C:
1732 def __init_subclass__(cls) -> None:
1733 cls.inited = True
1734
1735 with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
1736 C()
1737
1738 with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
1739 class D(C):
1740 pass
1741
1742 self.assertTrue(D.inited)
1743 self.assertIsInstance(D(), D) # no deprecation
1744
1745 def test_existing_init_subclass_in_base(self):
1746 class Base:
1747 def __init_subclass__(cls, x) -> None:
1748 cls.inited = x
1749
1750 @deprecated("C will go away soon")
1751 class C(Base, x=42):
1752 pass
1753
1754 self.assertEqual(C.inited, 42)
1755
1756 with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
1757 C()
1758
1759 with self.assertWarnsRegex(DeprecationWarning, "C will go away soon"):
1760 class D(C, x=3):
1761 pass
1762
1763 self.assertEqual(D.inited, 3)
1764
1765 def test_existing_init_subclass_in_sibling_base(self):
1766 @deprecated("A will go away soon")
1767 class A:
1768 pass
1769 class B:
1770 def __init_subclass__(cls, x):
1771 super().__init_subclass__()
1772 cls.inited = x
1773
1774 with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
1775 class C(A, B, x=42):
1776 pass
1777 self.assertEqual(C.inited, 42)
1778
1779 with self.assertWarnsRegex(DeprecationWarning, "A will go away soon"):
1780 class D(B, A, x=42):
1781 pass
1782 self.assertEqual(D.inited, 42)
1783
1784 def test_init_subclass_has_correct_cls(self):
1785 init_subclass_saw = None
1786
1787 @deprecated("Base will go away soon")
1788 class Base:
1789 def __init_subclass__(cls) -> None:
1790 nonlocal init_subclass_saw
1791 init_subclass_saw = cls
1792
1793 self.assertIsNone(init_subclass_saw)
1794
1795 with self.assertWarnsRegex(DeprecationWarning, "Base will go away soon"):
1796 class C(Base):
1797 pass
1798
1799 self.assertIs(init_subclass_saw, C)
1800
1801 def test_init_subclass_with_explicit_classmethod(self):
1802 init_subclass_saw = None
1803
1804 @deprecated("Base will go away soon")
1805 class Base:
1806 @classmethod
1807 def __init_subclass__(cls) -> None:
1808 nonlocal init_subclass_saw
1809 init_subclass_saw = cls
1810
1811 self.assertIsNone(init_subclass_saw)
1812
1813 with self.assertWarnsRegex(DeprecationWarning, "Base will go away soon"):
1814 class C(Base):
1815 pass
1816
1817 self.assertIs(init_subclass_saw, C)
1818
1819 def test_function(self):
1820 @deprecated("b will go away soon")
1821 def b():
1822 pass
1823
1824 with self.assertWarnsRegex(DeprecationWarning, "b will go away soon"):
1825 b()
1826
1827 def test_method(self):
1828 class Capybara:
1829 @deprecated("x will go away soon")
1830 def x(self):
1831 pass
1832
1833 instance = Capybara()
1834 with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
1835 instance.x()
1836
1837 def test_property(self):
1838 class Capybara:
1839 @property
1840 @deprecated("x will go away soon")
1841 def x(self):
1842 pass
1843
1844 @property
1845 def no_more_setting(self):
1846 return 42
1847
1848 @no_more_setting.setter
1849 @deprecated("no more setting")
1850 def no_more_setting(self, value):
1851 pass
1852
1853 instance = Capybara()
1854 with self.assertWarnsRegex(DeprecationWarning, "x will go away soon"):
1855 instance.x
1856
1857 with py_warnings.catch_warnings():
1858 py_warnings.simplefilter("error")
1859 self.assertEqual(instance.no_more_setting, 42)
1860
1861 with self.assertWarnsRegex(DeprecationWarning, "no more setting"):
1862 instance.no_more_setting = 42
1863
1864 def test_category(self):
1865 @deprecated("c will go away soon", category=RuntimeWarning)
1866 def c():
1867 pass
1868
1869 with self.assertWarnsRegex(RuntimeWarning, "c will go away soon"):
1870 c()
1871
1872 def test_turn_off_warnings(self):
1873 @deprecated("d will go away soon", category=None)
1874 def d():
1875 pass
1876
1877 with py_warnings.catch_warnings():
1878 py_warnings.simplefilter("error")
1879 d()
1880
1881 def test_only_strings_allowed(self):
1882 with self.assertRaisesRegex(
1883 TypeError,
1884 "Expected an object of type str for 'message', not 'type'"
1885 ):
1886 @deprecated
1887 class Foo: ...
1888
1889 with self.assertRaisesRegex(
1890 TypeError,
1891 "Expected an object of type str for 'message', not 'function'"
1892 ):
1893 @deprecated
1894 def foo(): ...
1895
1896 def test_no_retained_references_to_wrapper_instance(self):
1897 @deprecated('depr')
1898 def d(): pass
1899
1900 self.assertFalse(any(
1901 isinstance(cell.cell_contents, deprecated) for cell in d.__closure__
1902 ))
1903
1904 def test_inspect(self):
1905 @deprecated("depr")
1906 def sync():
1907 pass
1908
1909 @deprecated("depr")
1910 async def coro():
1911 pass
1912
1913 class Cls:
1914 @deprecated("depr")
1915 def sync(self):
1916 pass
1917
1918 @deprecated("depr")
1919 async def coro(self):
1920 pass
1921
1922 self.assertFalse(inspect.iscoroutinefunction(sync))
1923 self.assertTrue(inspect.iscoroutinefunction(coro))
1924 self.assertFalse(inspect.iscoroutinefunction(Cls.sync))
1925 self.assertTrue(inspect.iscoroutinefunction(Cls.coro))
1926
1927 def test_inspect_class_signature(self):
1928 class Cls1: # no __init__ or __new__
1929 pass
1930
1931 class Cls2: # __new__ only
1932 def __new__(cls, x, y):
1933 return super().__new__(cls)
1934
1935 class Cls3: # __init__ only
1936 def __init__(self, x, y):
1937 pass
1938
1939 class Cls4: # __new__ and __init__
1940 def __new__(cls, x, y):
1941 return super().__new__(cls)
1942
1943 def __init__(self, x, y):
1944 pass
1945
1946 class Cls5(Cls1): # inherits no __init__ or __new__
1947 pass
1948
1949 class Cls6(Cls2): # inherits __new__ only
1950 pass
1951
1952 class Cls7(Cls3): # inherits __init__ only
1953 pass
1954
1955 class Cls8(Cls4): # inherits __new__ and __init__
1956 pass
1957
1958 # The `@deprecated` decorator will update the class in-place.
1959 # Test the child classes first.
1960 for cls in reversed((Cls1, Cls2, Cls3, Cls4, Cls5, Cls6, Cls7, Cls8)):
1961 with self.subTest(f'class {cls.__name__} signature'):
1962 try:
1963 original_signature = inspect.signature(cls)
1964 except ValueError:
1965 original_signature = None
1966 try:
1967 original_new_signature = inspect.signature(cls.__new__)
1968 except ValueError:
1969 original_new_signature = None
1970
1971 deprecated_cls = deprecated("depr")(cls)
1972
1973 try:
1974 deprecated_signature = inspect.signature(deprecated_cls)
1975 except ValueError:
1976 deprecated_signature = None
1977 self.assertEqual(original_signature, deprecated_signature)
1978
1979 try:
1980 deprecated_new_signature = inspect.signature(deprecated_cls.__new__)
1981 except ValueError:
1982 deprecated_new_signature = None
1983 self.assertEqual(original_new_signature, deprecated_new_signature)
1984
1985
1986 def setUpModule():
1987 py_warnings.onceregistry.clear()
1988 c_warnings.onceregistry.clear()
1989
1990
1991 tearDownModule = setUpModule
1992
1993 if __name__ == "__main__":
1994 unittest.main()