Debian Codegraph @

Lib/test/test_warnings/__init__.py

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