1 from contextlib
import contextmanager
8 from test
import test_support
9 from test
.script_helper
import assert_python_ok
13 import warnings
as original_warnings
15 py_warnings
= test_support
.import_fresh_module('warnings', blocked
=['_warnings'])
16 c_warnings
= test_support
.import_fresh_module('warnings', fresh
=['_warnings'])
19 def warnings_state(module
):
20 """Use a specific warnings implementation in warning_tests."""
21 global __warningregistry__
22 for to_clear
in (sys
, warning_tests
):
24 to_clear
.__warningregistry
__.clear()
25 except AttributeError:
28 __warningregistry__
.clear()
31 original_warnings
= warning_tests
.warnings
32 original_filters
= module
.filters
34 module
.filters
= original_filters
[:]
35 module
.simplefilter("once")
36 warning_tests
.warnings
= module
39 warning_tests
.warnings
= original_warnings
40 module
.filters
= original_filters
43 class BaseTest(unittest
.TestCase
):
45 """Basic bookkeeping required for testing."""
48 # The __warningregistry__ needs to be in a pristine state for tests
50 if '__warningregistry__' in globals():
51 del globals()['__warningregistry__']
52 if hasattr(warning_tests
, '__warningregistry__'):
53 del warning_tests
.__warningregistry
__
54 if hasattr(sys
, '__warningregistry__'):
55 del sys
.__warningregistry
__
56 # The 'warnings' module must be explicitly set so that the proper
57 # interaction between _warnings and 'warnings' can be controlled.
58 sys
.modules
['warnings'] = self
.module
59 super(BaseTest
, self
).setUp()
62 sys
.modules
['warnings'] = original_warnings
63 super(BaseTest
, self
).tearDown()
66 class FilterTests(object):
68 """Testing the filtering functionality."""
71 with original_warnings
.catch_warnings(module
=self
.module
) as w
:
72 self
.module
.resetwarnings()
73 self
.module
.filterwarnings("error", category
=UserWarning)
74 self
.assertRaises(UserWarning, self
.module
.warn
,
75 "FilterTests.test_error")
77 def test_ignore(self
):
78 with original_warnings
.catch_warnings(record
=True,
79 module
=self
.module
) as w
:
80 self
.module
.resetwarnings()
81 self
.module
.filterwarnings("ignore", category
=UserWarning)
82 self
.module
.warn("FilterTests.test_ignore", UserWarning)
83 self
.assertEqual(len(w
), 0)
85 def test_always(self
):
86 with original_warnings
.catch_warnings(record
=True,
87 module
=self
.module
) as w
:
88 self
.module
.resetwarnings()
89 self
.module
.filterwarnings("always", category
=UserWarning)
90 message
= "FilterTests.test_always"
91 self
.module
.warn(message
, UserWarning)
92 self
.assertTrue(message
, w
[-1].message
)
93 self
.module
.warn(message
, UserWarning)
94 self
.assertTrue(w
[-1].message
, message
)
96 def test_default(self
):
97 with original_warnings
.catch_warnings(record
=True,
98 module
=self
.module
) as w
:
99 self
.module
.resetwarnings()
100 self
.module
.filterwarnings("default", category
=UserWarning)
101 message
= UserWarning("FilterTests.test_default")
103 self
.module
.warn(message
, UserWarning)
105 self
.assertEqual(w
[-1].message
, message
)
108 self
.assertEqual(len(w
), 0)
110 raise ValueError("loop variant unhandled")
112 def test_module(self
):
113 with original_warnings
.catch_warnings(record
=True,
114 module
=self
.module
) as w
:
115 self
.module
.resetwarnings()
116 self
.module
.filterwarnings("module", category
=UserWarning)
117 message
= UserWarning("FilterTests.test_module")
118 self
.module
.warn(message
, UserWarning)
119 self
.assertEqual(w
[-1].message
, message
)
121 self
.module
.warn(message
, UserWarning)
122 self
.assertEqual(len(w
), 0)
125 with original_warnings
.catch_warnings(record
=True,
126 module
=self
.module
) as w
:
127 self
.module
.resetwarnings()
128 self
.module
.filterwarnings("once", category
=UserWarning)
129 message
= UserWarning("FilterTests.test_once")
130 self
.module
.warn_explicit(message
, UserWarning, "test_warnings.py",
132 self
.assertEqual(w
[-1].message
, message
)
134 self
.module
.warn_explicit(message
, UserWarning, "test_warnings.py",
136 self
.assertEqual(len(w
), 0)
137 self
.module
.warn_explicit(message
, UserWarning, "test_warnings2.py",
139 self
.assertEqual(len(w
), 0)
141 def test_inheritance(self
):
142 with original_warnings
.catch_warnings(module
=self
.module
) as w
:
143 self
.module
.resetwarnings()
144 self
.module
.filterwarnings("error", category
=Warning)
145 self
.assertRaises(UserWarning, self
.module
.warn
,
146 "FilterTests.test_inheritance", UserWarning)
148 def test_ordering(self
):
149 with original_warnings
.catch_warnings(record
=True,
150 module
=self
.module
) as w
:
151 self
.module
.resetwarnings()
152 self
.module
.filterwarnings("ignore", category
=UserWarning)
153 self
.module
.filterwarnings("error", category
=UserWarning,
157 self
.module
.warn("FilterTests.test_ordering", UserWarning)
159 self
.fail("order handling for actions failed")
160 self
.assertEqual(len(w
), 0)
162 def test_filterwarnings(self
):
163 # Test filterwarnings().
164 # Implicitly also tests resetwarnings().
165 with original_warnings
.catch_warnings(record
=True,
166 module
=self
.module
) as w
:
167 self
.module
.filterwarnings("error", "", Warning, "", 0)
168 self
.assertRaises(UserWarning, self
.module
.warn
, 'convert to error')
170 self
.module
.resetwarnings()
171 text
= 'handle normally'
172 self
.module
.warn(text
)
173 self
.assertEqual(str(w
[-1].message
), text
)
174 self
.assertTrue(w
[-1].category
is UserWarning)
176 self
.module
.filterwarnings("ignore", "", Warning, "", 0)
177 text
= 'filtered out'
178 self
.module
.warn(text
)
179 self
.assertNotEqual(str(w
[-1].message
), text
)
181 self
.module
.resetwarnings()
182 self
.module
.filterwarnings("error", "hex*", Warning, "", 0)
183 self
.assertRaises(UserWarning, self
.module
.warn
, 'hex/oct')
184 text
= 'nonmatching text'
185 self
.module
.warn(text
)
186 self
.assertEqual(str(w
[-1].message
), text
)
187 self
.assertTrue(w
[-1].category
is UserWarning)
189 class CFilterTests(BaseTest
, FilterTests
):
192 class PyFilterTests(BaseTest
, FilterTests
):
196 class WarnTests(unittest
.TestCase
):
198 """Test warnings.warn() and warnings.warn_explicit()."""
200 def test_message(self
):
201 with original_warnings
.catch_warnings(record
=True,
202 module
=self
.module
) as w
:
203 self
.module
.simplefilter("once")
205 text
= 'multi %d' %i # Different text on each call.
206 self
.module
.warn(text
)
207 self
.assertEqual(str(w
[-1].message
), text
)
208 self
.assertTrue(w
[-1].category
is UserWarning)
210 def test_filename(self
):
211 with
warnings_state(self
.module
):
212 with original_warnings
.catch_warnings(record
=True,
213 module
=self
.module
) as w
:
214 warning_tests
.inner("spam1")
215 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
217 warning_tests
.outer("spam2")
218 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
221 def test_stacklevel(self
):
222 # Test stacklevel argument
223 # make sure all messages are different, so the warning won't be skipped
224 with
warnings_state(self
.module
):
225 with original_warnings
.catch_warnings(record
=True,
226 module
=self
.module
) as w
:
227 warning_tests
.inner("spam3", stacklevel
=1)
228 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
230 warning_tests
.outer("spam4", stacklevel
=1)
231 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
234 warning_tests
.inner("spam5", stacklevel
=2)
235 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
237 warning_tests
.outer("spam6", stacklevel
=2)
238 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
240 warning_tests
.outer("spam6.5", stacklevel
=3)
241 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
244 warning_tests
.inner("spam7", stacklevel
=9999)
245 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
248 def test_missing_filename_not_main(self
):
249 # If __file__ is not specified and __main__ is not the module name,
250 # then __file__ should be set to the module name.
251 filename
= warning_tests
.__file
__
253 del warning_tests
.__file
__
254 with
warnings_state(self
.module
):
255 with original_warnings
.catch_warnings(record
=True,
256 module
=self
.module
) as w
:
257 warning_tests
.inner("spam8", stacklevel
=1)
258 self
.assertEqual(w
[-1].filename
, warning_tests
.__name
__)
260 warning_tests
.__file
__ = filename
262 def test_missing_filename_main_with_argv(self
):
263 # If __file__ is not specified and the caller is __main__ and sys.argv
264 # exists, then use sys.argv[0] as the file.
265 if not hasattr(sys
, 'argv'):
267 filename
= warning_tests
.__file
__
268 module_name
= warning_tests
.__name
__
270 del warning_tests
.__file
__
271 warning_tests
.__name
__ = '__main__'
272 with
warnings_state(self
.module
):
273 with original_warnings
.catch_warnings(record
=True,
274 module
=self
.module
) as w
:
275 warning_tests
.inner('spam9', stacklevel
=1)
276 self
.assertEqual(w
[-1].filename
, sys
.argv
[0])
278 warning_tests
.__file
__ = filename
279 warning_tests
.__name
__ = module_name
281 def test_missing_filename_main_without_argv(self
):
282 # If __file__ is not specified, the caller is __main__, and sys.argv
283 # is not set, then '__main__' is the file name.
284 filename
= warning_tests
.__file
__
285 module_name
= warning_tests
.__name
__
288 del warning_tests
.__file
__
289 warning_tests
.__name
__ = '__main__'
291 with
warnings_state(self
.module
):
292 with original_warnings
.catch_warnings(record
=True,
293 module
=self
.module
) as w
:
294 warning_tests
.inner('spam10', stacklevel
=1)
295 self
.assertEqual(w
[-1].filename
, '__main__')
297 warning_tests
.__file
__ = filename
298 warning_tests
.__name
__ = module_name
301 def test_missing_filename_main_with_argv_empty_string(self
):
302 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
303 # is the empty string, then '__main__ is the file name.
305 file_name
= warning_tests
.__file
__
306 module_name
= warning_tests
.__name
__
309 del warning_tests
.__file
__
310 warning_tests
.__name
__ = '__main__'
312 with
warnings_state(self
.module
):
313 with original_warnings
.catch_warnings(record
=True,
314 module
=self
.module
) as w
:
315 warning_tests
.inner('spam11', stacklevel
=1)
316 self
.assertEqual(w
[-1].filename
, '__main__')
318 warning_tests
.__file
__ = file_name
319 warning_tests
.__name
__ = module_name
322 def test_warn_explicit_type_errors(self
):
323 # warn_explicit() should error out gracefully if it is given objects
324 # of the wrong types.
325 # lineno is expected to be an integer.
326 self
.assertRaises(TypeError, self
.module
.warn_explicit
,
327 None, UserWarning, None, None)
328 # Either 'message' needs to be an instance of Warning or 'category'
329 # needs to be a subclass.
330 self
.assertRaises(TypeError, self
.module
.warn_explicit
,
332 # 'registry' must be a dict or None.
333 self
.assertRaises((TypeError, AttributeError),
334 self
.module
.warn_explicit
,
335 None, Warning, None, 1, registry
=42)
337 def test_bad_str(self
):
339 # Warnings instance with a bad format string for __str__ should not
340 # trigger a bus error.
341 class BadStrWarning(Warning):
342 """Warning with a bad format string for __str__."""
344 return ("A bad formatted string %(err)" %
345 {"err" : "there is no %(err)s"})
347 with self
.assertRaises(ValueError):
348 self
.module
.warn(BadStrWarning())
351 class CWarnTests(BaseTest
, WarnTests
):
354 # As an early adopter, we sanity check the
355 # test_support.import_fresh_module utility function
356 def test_accelerated(self
):
357 self
.assertFalse(original_warnings
is self
.module
)
358 self
.assertFalse(hasattr(self
.module
.warn
, 'func_code'))
360 class PyWarnTests(BaseTest
, WarnTests
):
363 # As an early adopter, we sanity check the
364 # test_support.import_fresh_module utility function
365 def test_pure_python(self
):
366 self
.assertFalse(original_warnings
is self
.module
)
367 self
.assertTrue(hasattr(self
.module
.warn
, 'func_code'))
370 class WCmdLineTests(unittest
.TestCase
):
372 def test_improper_input(self
):
373 # Uses the private _setoption() function to test the parsing
374 # of command-line warning arguments
375 with original_warnings
.catch_warnings(module
=self
.module
):
376 self
.assertRaises(self
.module
._OptionError
,
377 self
.module
._setoption
, '1:2:3:4:5:6')
378 self
.assertRaises(self
.module
._OptionError
,
379 self
.module
._setoption
, 'bogus::Warning')
380 self
.assertRaises(self
.module
._OptionError
,
381 self
.module
._setoption
, 'ignore:2::4:-5')
382 self
.module
._setoption
('error::Warning::0')
383 self
.assertRaises(UserWarning, self
.module
.warn
, 'convert to error')
385 def test_improper_option(self
):
386 # Same as above, but check that the message is printed out when
387 # the interpreter is executed. This also checks that options are
388 # actually parsed at all.
389 rc
, out
, err
= assert_python_ok("-Wxxx", "-c", "pass")
390 self
.assertIn(b
"Invalid -W option ignored: invalid action: 'xxx'", err
)
392 def test_warnings_bootstrap(self
):
393 # Check that the warnings module does get loaded when -W<some option>
394 # is used (see issue #10372 for an example of silent bootstrap failure).
395 rc
, out
, err
= assert_python_ok("-Wi", "-c",
396 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
398 self
.assertFalse(out
.strip())
399 self
.assertNotIn(b
'RuntimeWarning', err
)
401 class CWCmdLineTests(BaseTest
, WCmdLineTests
):
404 class PyWCmdLineTests(BaseTest
, WCmdLineTests
):
408 class _WarningsTests(BaseTest
):
410 """Tests specific to the _warnings module."""
414 def test_filter(self
):
415 # Everything should function even if 'filters' is not in warnings.
416 with original_warnings
.catch_warnings(module
=self
.module
) as w
:
417 self
.module
.filterwarnings("error", "", Warning, "", 0)
418 self
.assertRaises(UserWarning, self
.module
.warn
,
420 del self
.module
.filters
421 self
.assertRaises(UserWarning, self
.module
.warn
,
424 def test_onceregistry(self
):
425 # Replacing or removing the onceregistry should be okay.
426 global __warningregistry__
427 message
= UserWarning('onceregistry test')
429 original_registry
= self
.module
.onceregistry
430 __warningregistry__
= {}
431 with original_warnings
.catch_warnings(record
=True,
432 module
=self
.module
) as w
:
433 self
.module
.resetwarnings()
434 self
.module
.filterwarnings("once", category
=UserWarning)
435 self
.module
.warn_explicit(message
, UserWarning, "file", 42)
436 self
.assertEqual(w
[-1].message
, message
)
438 self
.module
.warn_explicit(message
, UserWarning, "file", 42)
439 self
.assertEqual(len(w
), 0)
440 # Test the resetting of onceregistry.
441 self
.module
.onceregistry
= {}
442 __warningregistry__
= {}
443 self
.module
.warn('onceregistry test')
444 self
.assertEqual(w
[-1].message
.args
, message
.args
)
445 # Removal of onceregistry is okay.
447 del self
.module
.onceregistry
448 __warningregistry__
= {}
449 self
.module
.warn_explicit(message
, UserWarning, "file", 42)
450 self
.assertEqual(len(w
), 0)
452 self
.module
.onceregistry
= original_registry
454 def test_default_action(self
):
455 # Replacing or removing defaultaction should be okay.
456 message
= UserWarning("defaultaction test")
457 original
= self
.module
.defaultaction
459 with original_warnings
.catch_warnings(record
=True,
460 module
=self
.module
) as w
:
461 self
.module
.resetwarnings()
463 self
.module
.warn_explicit(message
, UserWarning, "<test>", 42,
465 self
.assertEqual(w
[-1].message
, message
)
466 self
.assertEqual(len(w
), 1)
467 self
.assertEqual(len(registry
), 1)
470 del self
.module
.defaultaction
471 __warningregistry__
= {}
473 self
.module
.warn_explicit(message
, UserWarning, "<test>", 43,
475 self
.assertEqual(w
[-1].message
, message
)
476 self
.assertEqual(len(w
), 1)
477 self
.assertEqual(len(registry
), 1)
480 self
.module
.defaultaction
= "ignore"
481 __warningregistry__
= {}
483 self
.module
.warn_explicit(message
, UserWarning, "<test>", 44,
485 self
.assertEqual(len(w
), 0)
487 self
.module
.defaultaction
= original
489 def test_showwarning_missing(self
):
490 # Test that showwarning() missing is okay.
491 text
= 'del showwarning test'
492 with original_warnings
.catch_warnings(module
=self
.module
):
493 self
.module
.filterwarnings("always", category
=UserWarning)
494 del self
.module
.showwarning
495 with test_support
.captured_output('stderr') as stream
:
496 self
.module
.warn(text
)
497 result
= stream
.getvalue()
498 self
.assertIn(text
, result
)
500 def test_showwarning_not_callable(self
):
501 with original_warnings
.catch_warnings(module
=self
.module
):
502 self
.module
.filterwarnings("always", category
=UserWarning)
503 old_showwarning
= self
.module
.showwarning
504 self
.module
.showwarning
= 23
506 self
.assertRaises(TypeError, self
.module
.warn
, "Warning!")
508 self
.module
.showwarning
= old_showwarning
510 def test_show_warning_output(self
):
511 # With showarning() missing, make sure that output is okay.
512 text
= 'test show_warning'
513 with original_warnings
.catch_warnings(module
=self
.module
):
514 self
.module
.filterwarnings("always", category
=UserWarning)
515 del self
.module
.showwarning
516 with test_support
.captured_output('stderr') as stream
:
517 warning_tests
.inner(text
)
518 result
= stream
.getvalue()
519 self
.assertEqual(result
.count('\n'), 2,
520 "Too many newlines in %r" % result
)
521 first_line
, second_line
= result
.split('\n', 1)
522 expected_file
= os
.path
.splitext(warning_tests
.__file
__)[0] + '.py'
523 first_line_parts
= first_line
.rsplit(':', 3)
524 path
, line
, warning_class
, message
= first_line_parts
526 self
.assertEqual(expected_file
, path
)
527 self
.assertEqual(warning_class
, ' ' + UserWarning.__name
__)
528 self
.assertEqual(message
, ' ' + text
)
529 expected_line
= ' ' + linecache
.getline(path
, line
).strip() + '\n'
531 self
.assertEqual(second_line
, expected_line
)
534 class WarningsDisplayTests(unittest
.TestCase
):
536 """Test the displaying of warnings and the ability to overload functions
537 related to displaying warnings."""
539 def test_formatwarning(self
):
542 file_name
= os
.path
.splitext(warning_tests
.__file
__)[0] + '.py'
544 file_line
= linecache
.getline(file_name
, line_num
).strip()
545 format
= "%s:%s: %s: %s\n %s\n"
546 expect
= format
% (file_name
, line_num
, category
.__name
__, message
,
548 self
.assertEqual(expect
, self
.module
.formatwarning(message
,
549 category
, file_name
, line_num
))
550 # Test the 'line' argument.
551 file_line
+= " for the win!"
552 expect
= format
% (file_name
, line_num
, category
.__name
__, message
,
554 self
.assertEqual(expect
, self
.module
.formatwarning(message
,
555 category
, file_name
, line_num
, file_line
))
557 def test_showwarning(self
):
558 file_name
= os
.path
.splitext(warning_tests
.__file
__)[0] + '.py'
560 expected_file_line
= linecache
.getline(file_name
, line_num
).strip()
563 file_object
= StringIO
.StringIO()
564 expect
= self
.module
.formatwarning(message
, category
, file_name
,
566 self
.module
.showwarning(message
, category
, file_name
, line_num
,
568 self
.assertEqual(file_object
.getvalue(), expect
)
569 # Test 'line' argument.
570 expected_file_line
+= "for the win!"
571 expect
= self
.module
.formatwarning(message
, category
, file_name
,
572 line_num
, expected_file_line
)
573 file_object
= StringIO
.StringIO()
574 self
.module
.showwarning(message
, category
, file_name
, line_num
,
575 file_object
, expected_file_line
)
576 self
.assertEqual(expect
, file_object
.getvalue())
578 class CWarningsDisplayTests(BaseTest
, WarningsDisplayTests
):
581 class PyWarningsDisplayTests(BaseTest
, WarningsDisplayTests
):
585 class CatchWarningTests(BaseTest
):
587 """Test catch_warnings()."""
589 def test_catch_warnings_restore(self
):
591 orig_filters
= wmod
.filters
592 orig_showwarning
= wmod
.showwarning
593 # Ensure both showwarning and filters are restored when recording
594 with wmod
.catch_warnings(module
=wmod
, record
=True):
595 wmod
.filters
= wmod
.showwarning
= object()
596 self
.assertTrue(wmod
.filters
is orig_filters
)
597 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
598 # Same test, but with recording disabled
599 with wmod
.catch_warnings(module
=wmod
, record
=False):
600 wmod
.filters
= wmod
.showwarning
= object()
601 self
.assertTrue(wmod
.filters
is orig_filters
)
602 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
604 def test_catch_warnings_recording(self
):
606 # Ensure warnings are recorded when requested
607 with wmod
.catch_warnings(module
=wmod
, record
=True) as w
:
608 self
.assertEqual(w
, [])
609 self
.assertTrue(type(w
) is list)
610 wmod
.simplefilter("always")
612 self
.assertEqual(str(w
[-1].message
), "foo")
614 self
.assertEqual(str(w
[-1].message
), "bar")
615 self
.assertEqual(str(w
[0].message
), "foo")
616 self
.assertEqual(str(w
[1].message
), "bar")
618 self
.assertEqual(w
, [])
619 # Ensure warnings are not recorded when not requested
620 orig_showwarning
= wmod
.showwarning
621 with wmod
.catch_warnings(module
=wmod
, record
=False) as w
:
622 self
.assertTrue(w
is None)
623 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
625 def test_catch_warnings_reentry_guard(self
):
627 # Ensure catch_warnings is protected against incorrect usage
628 x
= wmod
.catch_warnings(module
=wmod
, record
=True)
629 self
.assertRaises(RuntimeError, x
.__exit
__)
631 self
.assertRaises(RuntimeError, x
.__enter
__)
632 # Same test, but with recording disabled
633 x
= wmod
.catch_warnings(module
=wmod
, record
=False)
634 self
.assertRaises(RuntimeError, x
.__exit
__)
636 self
.assertRaises(RuntimeError, x
.__enter
__)
638 def test_catch_warnings_defaults(self
):
640 orig_filters
= wmod
.filters
641 orig_showwarning
= wmod
.showwarning
642 # Ensure default behaviour is not to record warnings
643 with wmod
.catch_warnings(module
=wmod
) as w
:
644 self
.assertTrue(w
is None)
645 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
646 self
.assertTrue(wmod
.filters
is not orig_filters
)
647 self
.assertTrue(wmod
.filters
is orig_filters
)
648 if wmod
is sys
.modules
['warnings']:
649 # Ensure the default module is this one
650 with wmod
.catch_warnings() as w
:
651 self
.assertTrue(w
is None)
652 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
653 self
.assertTrue(wmod
.filters
is not orig_filters
)
654 self
.assertTrue(wmod
.filters
is orig_filters
)
656 def test_check_warnings(self
):
657 # Explicit tests for the test_support convenience wrapper
659 if wmod
is not sys
.modules
['warnings']:
661 with test_support
.check_warnings(quiet
=False) as w
:
662 self
.assertEqual(w
.warnings
, [])
663 wmod
.simplefilter("always")
665 self
.assertEqual(str(w
.message
), "foo")
667 self
.assertEqual(str(w
.message
), "bar")
668 self
.assertEqual(str(w
.warnings
[0].message
), "foo")
669 self
.assertEqual(str(w
.warnings
[1].message
), "bar")
671 self
.assertEqual(w
.warnings
, [])
673 with test_support
.check_warnings():
674 # defaults to quiet=True without argument
676 with test_support
.check_warnings(('foo', UserWarning)):
679 with self
.assertRaises(AssertionError):
680 with test_support
.check_warnings(('', RuntimeWarning)):
681 # defaults to quiet=False with argument
683 with self
.assertRaises(AssertionError):
684 with test_support
.check_warnings(('foo', RuntimeWarning)):
688 class CCatchWarningTests(CatchWarningTests
):
691 class PyCatchWarningTests(CatchWarningTests
):
695 class EnvironmentVariableTests(BaseTest
):
697 def test_single_warning(self
):
698 newenv
= os
.environ
.copy()
699 newenv
["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
700 p
= subprocess
.Popen([sys
.executable
,
701 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
702 stdout
=subprocess
.PIPE
, env
=newenv
)
703 self
.assertEqual(p
.communicate()[0], "['ignore::DeprecationWarning']")
704 self
.assertEqual(p
.wait(), 0)
706 def test_comma_separated_warnings(self
):
707 newenv
= os
.environ
.copy()
708 newenv
["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
709 "ignore::UnicodeWarning")
710 p
= subprocess
.Popen([sys
.executable
,
711 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
712 stdout
=subprocess
.PIPE
, env
=newenv
)
713 self
.assertEqual(p
.communicate()[0],
714 "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
715 self
.assertEqual(p
.wait(), 0)
717 def test_envvar_and_command_line(self
):
718 newenv
= os
.environ
.copy()
719 newenv
["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
720 p
= subprocess
.Popen([sys
.executable
, "-W" "ignore::UnicodeWarning",
721 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
722 stdout
=subprocess
.PIPE
, env
=newenv
)
723 self
.assertEqual(p
.communicate()[0],
724 "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
725 self
.assertEqual(p
.wait(), 0)
727 class CEnvironmentVariableTests(EnvironmentVariableTests
):
730 class PyEnvironmentVariableTests(EnvironmentVariableTests
):
735 py_warnings
.onceregistry
.clear()
736 c_warnings
.onceregistry
.clear()
737 test_support
.run_unittest(CFilterTests
, PyFilterTests
,
738 CWarnTests
, PyWarnTests
,
739 CWCmdLineTests
, PyWCmdLineTests
,
741 CWarningsDisplayTests
, PyWarningsDisplayTests
,
742 CCatchWarningTests
, PyCatchWarningTests
,
743 CEnvironmentVariableTests
,
744 PyEnvironmentVariableTests
748 if __name__
== "__main__":