1 from contextlib
import contextmanager
8 from test
import test_support
12 import warnings
as original_warnings
14 py_warnings
= test_support
.import_fresh_module('warnings', blocked
=['_warnings'])
15 c_warnings
= test_support
.import_fresh_module('warnings', fresh
=['_warnings'])
18 def warnings_state(module
):
19 """Use a specific warnings implementation in warning_tests."""
20 global __warningregistry__
21 for to_clear
in (sys
, warning_tests
):
23 to_clear
.__warningregistry
__.clear()
24 except AttributeError:
27 __warningregistry__
.clear()
30 original_warnings
= warning_tests
.warnings
31 original_filters
= module
.filters
33 module
.filters
= original_filters
[:]
34 module
.simplefilter("once")
35 warning_tests
.warnings
= module
38 warning_tests
.warnings
= original_warnings
39 module
.filters
= original_filters
42 class BaseTest(unittest
.TestCase
):
44 """Basic bookkeeping required for testing."""
47 # The __warningregistry__ needs to be in a pristine state for tests
49 if '__warningregistry__' in globals():
50 del globals()['__warningregistry__']
51 if hasattr(warning_tests
, '__warningregistry__'):
52 del warning_tests
.__warningregistry
__
53 if hasattr(sys
, '__warningregistry__'):
54 del sys
.__warningregistry
__
55 # The 'warnings' module must be explicitly set so that the proper
56 # interaction between _warnings and 'warnings' can be controlled.
57 sys
.modules
['warnings'] = self
.module
58 super(BaseTest
, self
).setUp()
61 sys
.modules
['warnings'] = original_warnings
62 super(BaseTest
, self
).tearDown()
65 class FilterTests(object):
67 """Testing the filtering functionality."""
70 with original_warnings
.catch_warnings(module
=self
.module
) as w
:
71 self
.module
.resetwarnings()
72 self
.module
.filterwarnings("error", category
=UserWarning)
73 self
.assertRaises(UserWarning, self
.module
.warn
,
74 "FilterTests.test_error")
76 def test_ignore(self
):
77 with original_warnings
.catch_warnings(record
=True,
78 module
=self
.module
) as w
:
79 self
.module
.resetwarnings()
80 self
.module
.filterwarnings("ignore", category
=UserWarning)
81 self
.module
.warn("FilterTests.test_ignore", UserWarning)
82 self
.assertEquals(len(w
), 0)
84 def test_always(self
):
85 with original_warnings
.catch_warnings(record
=True,
86 module
=self
.module
) as w
:
87 self
.module
.resetwarnings()
88 self
.module
.filterwarnings("always", category
=UserWarning)
89 message
= "FilterTests.test_always"
90 self
.module
.warn(message
, UserWarning)
91 self
.assertTrue(message
, w
[-1].message
)
92 self
.module
.warn(message
, UserWarning)
93 self
.assertTrue(w
[-1].message
, message
)
95 def test_default(self
):
96 with original_warnings
.catch_warnings(record
=True,
97 module
=self
.module
) as w
:
98 self
.module
.resetwarnings()
99 self
.module
.filterwarnings("default", category
=UserWarning)
100 message
= UserWarning("FilterTests.test_default")
102 self
.module
.warn(message
, UserWarning)
104 self
.assertEquals(w
[-1].message
, message
)
107 self
.assertEquals(len(w
), 0)
109 raise ValueError("loop variant unhandled")
111 def test_module(self
):
112 with original_warnings
.catch_warnings(record
=True,
113 module
=self
.module
) as w
:
114 self
.module
.resetwarnings()
115 self
.module
.filterwarnings("module", category
=UserWarning)
116 message
= UserWarning("FilterTests.test_module")
117 self
.module
.warn(message
, UserWarning)
118 self
.assertEquals(w
[-1].message
, message
)
120 self
.module
.warn(message
, UserWarning)
121 self
.assertEquals(len(w
), 0)
124 with original_warnings
.catch_warnings(record
=True,
125 module
=self
.module
) as w
:
126 self
.module
.resetwarnings()
127 self
.module
.filterwarnings("once", category
=UserWarning)
128 message
= UserWarning("FilterTests.test_once")
129 self
.module
.warn_explicit(message
, UserWarning, "test_warnings.py",
131 self
.assertEquals(w
[-1].message
, message
)
133 self
.module
.warn_explicit(message
, UserWarning, "test_warnings.py",
135 self
.assertEquals(len(w
), 0)
136 self
.module
.warn_explicit(message
, UserWarning, "test_warnings2.py",
138 self
.assertEquals(len(w
), 0)
140 def test_inheritance(self
):
141 with original_warnings
.catch_warnings(module
=self
.module
) as w
:
142 self
.module
.resetwarnings()
143 self
.module
.filterwarnings("error", category
=Warning)
144 self
.assertRaises(UserWarning, self
.module
.warn
,
145 "FilterTests.test_inheritance", UserWarning)
147 def test_ordering(self
):
148 with original_warnings
.catch_warnings(record
=True,
149 module
=self
.module
) as w
:
150 self
.module
.resetwarnings()
151 self
.module
.filterwarnings("ignore", category
=UserWarning)
152 self
.module
.filterwarnings("error", category
=UserWarning,
156 self
.module
.warn("FilterTests.test_ordering", UserWarning)
158 self
.fail("order handling for actions failed")
159 self
.assertEquals(len(w
), 0)
161 def test_filterwarnings(self
):
162 # Test filterwarnings().
163 # Implicitly also tests resetwarnings().
164 with original_warnings
.catch_warnings(record
=True,
165 module
=self
.module
) as w
:
166 self
.module
.filterwarnings("error", "", Warning, "", 0)
167 self
.assertRaises(UserWarning, self
.module
.warn
, 'convert to error')
169 self
.module
.resetwarnings()
170 text
= 'handle normally'
171 self
.module
.warn(text
)
172 self
.assertEqual(str(w
[-1].message
), text
)
173 self
.assertTrue(w
[-1].category
is UserWarning)
175 self
.module
.filterwarnings("ignore", "", Warning, "", 0)
176 text
= 'filtered out'
177 self
.module
.warn(text
)
178 self
.assertNotEqual(str(w
[-1].message
), text
)
180 self
.module
.resetwarnings()
181 self
.module
.filterwarnings("error", "hex*", Warning, "", 0)
182 self
.assertRaises(UserWarning, self
.module
.warn
, 'hex/oct')
183 text
= 'nonmatching text'
184 self
.module
.warn(text
)
185 self
.assertEqual(str(w
[-1].message
), text
)
186 self
.assertTrue(w
[-1].category
is UserWarning)
188 class CFilterTests(BaseTest
, FilterTests
):
191 class PyFilterTests(BaseTest
, FilterTests
):
195 class WarnTests(unittest
.TestCase
):
197 """Test warnings.warn() and warnings.warn_explicit()."""
199 def test_message(self
):
200 with original_warnings
.catch_warnings(record
=True,
201 module
=self
.module
) as w
:
202 self
.module
.simplefilter("once")
204 text
= 'multi %d' %i # Different text on each call.
205 self
.module
.warn(text
)
206 self
.assertEqual(str(w
[-1].message
), text
)
207 self
.assertTrue(w
[-1].category
is UserWarning)
209 def test_filename(self
):
210 with
warnings_state(self
.module
):
211 with original_warnings
.catch_warnings(record
=True,
212 module
=self
.module
) as w
:
213 warning_tests
.inner("spam1")
214 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
216 warning_tests
.outer("spam2")
217 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
220 def test_stacklevel(self
):
221 # Test stacklevel argument
222 # make sure all messages are different, so the warning won't be skipped
223 with
warnings_state(self
.module
):
224 with original_warnings
.catch_warnings(record
=True,
225 module
=self
.module
) as w
:
226 warning_tests
.inner("spam3", stacklevel
=1)
227 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
229 warning_tests
.outer("spam4", stacklevel
=1)
230 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
233 warning_tests
.inner("spam5", stacklevel
=2)
234 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
236 warning_tests
.outer("spam6", stacklevel
=2)
237 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
239 warning_tests
.outer("spam6.5", stacklevel
=3)
240 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
243 warning_tests
.inner("spam7", stacklevel
=9999)
244 self
.assertEqual(os
.path
.basename(w
[-1].filename
),
247 def test_missing_filename_not_main(self
):
248 # If __file__ is not specified and __main__ is not the module name,
249 # then __file__ should be set to the module name.
250 filename
= warning_tests
.__file
__
252 del warning_tests
.__file
__
253 with
warnings_state(self
.module
):
254 with original_warnings
.catch_warnings(record
=True,
255 module
=self
.module
) as w
:
256 warning_tests
.inner("spam8", stacklevel
=1)
257 self
.assertEqual(w
[-1].filename
, warning_tests
.__name
__)
259 warning_tests
.__file
__ = filename
261 def test_missing_filename_main_with_argv(self
):
262 # If __file__ is not specified and the caller is __main__ and sys.argv
263 # exists, then use sys.argv[0] as the file.
264 if not hasattr(sys
, 'argv'):
266 filename
= warning_tests
.__file
__
267 module_name
= warning_tests
.__name
__
269 del warning_tests
.__file
__
270 warning_tests
.__name
__ = '__main__'
271 with
warnings_state(self
.module
):
272 with original_warnings
.catch_warnings(record
=True,
273 module
=self
.module
) as w
:
274 warning_tests
.inner('spam9', stacklevel
=1)
275 self
.assertEqual(w
[-1].filename
, sys
.argv
[0])
277 warning_tests
.__file
__ = filename
278 warning_tests
.__name
__ = module_name
280 def test_missing_filename_main_without_argv(self
):
281 # If __file__ is not specified, the caller is __main__, and sys.argv
282 # is not set, then '__main__' is the file name.
283 filename
= warning_tests
.__file
__
284 module_name
= warning_tests
.__name
__
287 del warning_tests
.__file
__
288 warning_tests
.__name
__ = '__main__'
290 with
warnings_state(self
.module
):
291 with original_warnings
.catch_warnings(record
=True,
292 module
=self
.module
) as w
:
293 warning_tests
.inner('spam10', stacklevel
=1)
294 self
.assertEqual(w
[-1].filename
, '__main__')
296 warning_tests
.__file
__ = filename
297 warning_tests
.__name
__ = module_name
300 def test_missing_filename_main_with_argv_empty_string(self
):
301 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
302 # is the empty string, then '__main__ is the file name.
304 file_name
= warning_tests
.__file
__
305 module_name
= warning_tests
.__name
__
308 del warning_tests
.__file
__
309 warning_tests
.__name
__ = '__main__'
311 with
warnings_state(self
.module
):
312 with original_warnings
.catch_warnings(record
=True,
313 module
=self
.module
) as w
:
314 warning_tests
.inner('spam11', stacklevel
=1)
315 self
.assertEqual(w
[-1].filename
, '__main__')
317 warning_tests
.__file
__ = file_name
318 warning_tests
.__name
__ = module_name
321 def test_warn_explicit_type_errors(self
):
322 # warn_explicit() shoud error out gracefully if it is given objects
323 # of the wrong types.
324 # lineno is expected to be an integer.
325 self
.assertRaises(TypeError, self
.module
.warn_explicit
,
326 None, UserWarning, None, None)
327 # Either 'message' needs to be an instance of Warning or 'category'
328 # needs to be a subclass.
329 self
.assertRaises(TypeError, self
.module
.warn_explicit
,
331 # 'registry' must be a dict or None.
332 self
.assertRaises((TypeError, AttributeError),
333 self
.module
.warn_explicit
,
334 None, Warning, None, 1, registry
=42)
336 def test_bad_str(self
):
338 # Warnings instance with a bad format string for __str__ should not
339 # trigger a bus error.
340 class BadStrWarning(Warning):
341 """Warning with a bad format string for __str__."""
343 return ("A bad formatted string %(err)" %
344 {"err" : "there is no %(err)s"})
346 with self
.assertRaises(ValueError):
347 self
.module
.warn(BadStrWarning())
350 class CWarnTests(BaseTest
, WarnTests
):
353 # As an early adopter, we sanity check the
354 # test_support.import_fresh_module utility function
355 def test_accelerated(self
):
356 self
.assertFalse(original_warnings
is self
.module
)
357 self
.assertFalse(hasattr(self
.module
.warn
, 'func_code'))
359 class PyWarnTests(BaseTest
, WarnTests
):
362 # As an early adopter, we sanity check the
363 # test_support.import_fresh_module utility function
364 def test_pure_python(self
):
365 self
.assertFalse(original_warnings
is self
.module
)
366 self
.assertTrue(hasattr(self
.module
.warn
, 'func_code'))
369 class WCmdLineTests(unittest
.TestCase
):
371 def test_improper_input(self
):
372 # Uses the private _setoption() function to test the parsing
373 # of command-line warning arguments
374 with original_warnings
.catch_warnings(module
=self
.module
):
375 self
.assertRaises(self
.module
._OptionError
,
376 self
.module
._setoption
, '1:2:3:4:5:6')
377 self
.assertRaises(self
.module
._OptionError
,
378 self
.module
._setoption
, 'bogus::Warning')
379 self
.assertRaises(self
.module
._OptionError
,
380 self
.module
._setoption
, 'ignore:2::4:-5')
381 self
.module
._setoption
('error::Warning::0')
382 self
.assertRaises(UserWarning, self
.module
.warn
, 'convert to error')
384 class CWCmdLineTests(BaseTest
, WCmdLineTests
):
387 class PyWCmdLineTests(BaseTest
, WCmdLineTests
):
391 class _WarningsTests(BaseTest
):
393 """Tests specific to the _warnings module."""
397 def test_filter(self
):
398 # Everything should function even if 'filters' is not in warnings.
399 with original_warnings
.catch_warnings(module
=self
.module
) as w
:
400 self
.module
.filterwarnings("error", "", Warning, "", 0)
401 self
.assertRaises(UserWarning, self
.module
.warn
,
403 del self
.module
.filters
404 self
.assertRaises(UserWarning, self
.module
.warn
,
407 def test_onceregistry(self
):
408 # Replacing or removing the onceregistry should be okay.
409 global __warningregistry__
410 message
= UserWarning('onceregistry test')
412 original_registry
= self
.module
.onceregistry
413 __warningregistry__
= {}
414 with original_warnings
.catch_warnings(record
=True,
415 module
=self
.module
) as w
:
416 self
.module
.resetwarnings()
417 self
.module
.filterwarnings("once", category
=UserWarning)
418 self
.module
.warn_explicit(message
, UserWarning, "file", 42)
419 self
.assertEqual(w
[-1].message
, message
)
421 self
.module
.warn_explicit(message
, UserWarning, "file", 42)
422 self
.assertEquals(len(w
), 0)
423 # Test the resetting of onceregistry.
424 self
.module
.onceregistry
= {}
425 __warningregistry__
= {}
426 self
.module
.warn('onceregistry test')
427 self
.assertEqual(w
[-1].message
.args
, message
.args
)
428 # Removal of onceregistry is okay.
430 del self
.module
.onceregistry
431 __warningregistry__
= {}
432 self
.module
.warn_explicit(message
, UserWarning, "file", 42)
433 self
.assertEquals(len(w
), 0)
435 self
.module
.onceregistry
= original_registry
437 def test_default_action(self
):
438 # Replacing or removing defaultaction should be okay.
439 message
= UserWarning("defaultaction test")
440 original
= self
.module
.defaultaction
442 with original_warnings
.catch_warnings(record
=True,
443 module
=self
.module
) as w
:
444 self
.module
.resetwarnings()
446 self
.module
.warn_explicit(message
, UserWarning, "<test>", 42,
448 self
.assertEqual(w
[-1].message
, message
)
449 self
.assertEqual(len(w
), 1)
450 self
.assertEqual(len(registry
), 1)
453 del self
.module
.defaultaction
454 __warningregistry__
= {}
456 self
.module
.warn_explicit(message
, UserWarning, "<test>", 43,
458 self
.assertEqual(w
[-1].message
, message
)
459 self
.assertEqual(len(w
), 1)
460 self
.assertEqual(len(registry
), 1)
463 self
.module
.defaultaction
= "ignore"
464 __warningregistry__
= {}
466 self
.module
.warn_explicit(message
, UserWarning, "<test>", 44,
468 self
.assertEqual(len(w
), 0)
470 self
.module
.defaultaction
= original
472 def test_showwarning_missing(self
):
473 # Test that showwarning() missing is okay.
474 text
= 'del showwarning test'
475 with original_warnings
.catch_warnings(module
=self
.module
):
476 self
.module
.filterwarnings("always", category
=UserWarning)
477 del self
.module
.showwarning
478 with test_support
.captured_output('stderr') as stream
:
479 self
.module
.warn(text
)
480 result
= stream
.getvalue()
481 self
.assertIn(text
, result
)
483 def test_showwarning_not_callable(self
):
484 with original_warnings
.catch_warnings(module
=self
.module
):
485 self
.module
.filterwarnings("always", category
=UserWarning)
486 old_showwarning
= self
.module
.showwarning
487 self
.module
.showwarning
= 23
489 self
.assertRaises(TypeError, self
.module
.warn
, "Warning!")
491 self
.module
.showwarning
= old_showwarning
493 def test_show_warning_output(self
):
494 # With showarning() missing, make sure that output is okay.
495 text
= 'test show_warning'
496 with original_warnings
.catch_warnings(module
=self
.module
):
497 self
.module
.filterwarnings("always", category
=UserWarning)
498 del self
.module
.showwarning
499 with test_support
.captured_output('stderr') as stream
:
500 warning_tests
.inner(text
)
501 result
= stream
.getvalue()
502 self
.assertEqual(result
.count('\n'), 2,
503 "Too many newlines in %r" % result
)
504 first_line
, second_line
= result
.split('\n', 1)
505 expected_file
= os
.path
.splitext(warning_tests
.__file
__)[0] + '.py'
506 first_line_parts
= first_line
.rsplit(':', 3)
507 path
, line
, warning_class
, message
= first_line_parts
509 self
.assertEqual(expected_file
, path
)
510 self
.assertEqual(warning_class
, ' ' + UserWarning.__name
__)
511 self
.assertEqual(message
, ' ' + text
)
512 expected_line
= ' ' + linecache
.getline(path
, line
).strip() + '\n'
514 self
.assertEqual(second_line
, expected_line
)
517 class WarningsDisplayTests(unittest
.TestCase
):
519 """Test the displaying of warnings and the ability to overload functions
520 related to displaying warnings."""
522 def test_formatwarning(self
):
525 file_name
= os
.path
.splitext(warning_tests
.__file
__)[0] + '.py'
527 file_line
= linecache
.getline(file_name
, line_num
).strip()
528 format
= "%s:%s: %s: %s\n %s\n"
529 expect
= format
% (file_name
, line_num
, category
.__name
__, message
,
531 self
.assertEqual(expect
, self
.module
.formatwarning(message
,
532 category
, file_name
, line_num
))
533 # Test the 'line' argument.
534 file_line
+= " for the win!"
535 expect
= format
% (file_name
, line_num
, category
.__name
__, message
,
537 self
.assertEqual(expect
, self
.module
.formatwarning(message
,
538 category
, file_name
, line_num
, file_line
))
540 def test_showwarning(self
):
541 file_name
= os
.path
.splitext(warning_tests
.__file
__)[0] + '.py'
543 expected_file_line
= linecache
.getline(file_name
, line_num
).strip()
546 file_object
= StringIO
.StringIO()
547 expect
= self
.module
.formatwarning(message
, category
, file_name
,
549 self
.module
.showwarning(message
, category
, file_name
, line_num
,
551 self
.assertEqual(file_object
.getvalue(), expect
)
552 # Test 'line' argument.
553 expected_file_line
+= "for the win!"
554 expect
= self
.module
.formatwarning(message
, category
, file_name
,
555 line_num
, expected_file_line
)
556 file_object
= StringIO
.StringIO()
557 self
.module
.showwarning(message
, category
, file_name
, line_num
,
558 file_object
, expected_file_line
)
559 self
.assertEqual(expect
, file_object
.getvalue())
561 class CWarningsDisplayTests(BaseTest
, WarningsDisplayTests
):
564 class PyWarningsDisplayTests(BaseTest
, WarningsDisplayTests
):
568 class CatchWarningTests(BaseTest
):
570 """Test catch_warnings()."""
572 def test_catch_warnings_restore(self
):
574 orig_filters
= wmod
.filters
575 orig_showwarning
= wmod
.showwarning
576 # Ensure both showwarning and filters are restored when recording
577 with wmod
.catch_warnings(module
=wmod
, record
=True):
578 wmod
.filters
= wmod
.showwarning
= object()
579 self
.assertTrue(wmod
.filters
is orig_filters
)
580 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
581 # Same test, but with recording disabled
582 with wmod
.catch_warnings(module
=wmod
, record
=False):
583 wmod
.filters
= wmod
.showwarning
= object()
584 self
.assertTrue(wmod
.filters
is orig_filters
)
585 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
587 def test_catch_warnings_recording(self
):
589 # Ensure warnings are recorded when requested
590 with wmod
.catch_warnings(module
=wmod
, record
=True) as w
:
591 self
.assertEqual(w
, [])
592 self
.assertTrue(type(w
) is list)
593 wmod
.simplefilter("always")
595 self
.assertEqual(str(w
[-1].message
), "foo")
597 self
.assertEqual(str(w
[-1].message
), "bar")
598 self
.assertEqual(str(w
[0].message
), "foo")
599 self
.assertEqual(str(w
[1].message
), "bar")
601 self
.assertEqual(w
, [])
602 # Ensure warnings are not recorded when not requested
603 orig_showwarning
= wmod
.showwarning
604 with wmod
.catch_warnings(module
=wmod
, record
=False) as w
:
605 self
.assertTrue(w
is None)
606 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
608 def test_catch_warnings_reentry_guard(self
):
610 # Ensure catch_warnings is protected against incorrect usage
611 x
= wmod
.catch_warnings(module
=wmod
, record
=True)
612 self
.assertRaises(RuntimeError, x
.__exit
__)
614 self
.assertRaises(RuntimeError, x
.__enter
__)
615 # Same test, but with recording disabled
616 x
= wmod
.catch_warnings(module
=wmod
, record
=False)
617 self
.assertRaises(RuntimeError, x
.__exit
__)
619 self
.assertRaises(RuntimeError, x
.__enter
__)
621 def test_catch_warnings_defaults(self
):
623 orig_filters
= wmod
.filters
624 orig_showwarning
= wmod
.showwarning
625 # Ensure default behaviour is not to record warnings
626 with wmod
.catch_warnings(module
=wmod
) as w
:
627 self
.assertTrue(w
is None)
628 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
629 self
.assertTrue(wmod
.filters
is not orig_filters
)
630 self
.assertTrue(wmod
.filters
is orig_filters
)
631 if wmod
is sys
.modules
['warnings']:
632 # Ensure the default module is this one
633 with wmod
.catch_warnings() as w
:
634 self
.assertTrue(w
is None)
635 self
.assertTrue(wmod
.showwarning
is orig_showwarning
)
636 self
.assertTrue(wmod
.filters
is not orig_filters
)
637 self
.assertTrue(wmod
.filters
is orig_filters
)
639 def test_check_warnings(self
):
640 # Explicit tests for the test_support convenience wrapper
642 if wmod
is not sys
.modules
['warnings']:
644 with test_support
.check_warnings(quiet
=False) as w
:
645 self
.assertEqual(w
.warnings
, [])
646 wmod
.simplefilter("always")
648 self
.assertEqual(str(w
.message
), "foo")
650 self
.assertEqual(str(w
.message
), "bar")
651 self
.assertEqual(str(w
.warnings
[0].message
), "foo")
652 self
.assertEqual(str(w
.warnings
[1].message
), "bar")
654 self
.assertEqual(w
.warnings
, [])
656 with test_support
.check_warnings():
657 # defaults to quiet=True without argument
659 with test_support
.check_warnings(('foo', UserWarning)):
662 with self
.assertRaises(AssertionError):
663 with test_support
.check_warnings(('', RuntimeWarning)):
664 # defaults to quiet=False with argument
666 with self
.assertRaises(AssertionError):
667 with test_support
.check_warnings(('foo', RuntimeWarning)):
671 class CCatchWarningTests(CatchWarningTests
):
674 class PyCatchWarningTests(CatchWarningTests
):
678 class EnvironmentVariableTests(BaseTest
):
680 def test_single_warning(self
):
681 newenv
= os
.environ
.copy()
682 newenv
["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
683 p
= subprocess
.Popen([sys
.executable
,
684 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
685 stdout
=subprocess
.PIPE
, env
=newenv
)
686 self
.assertEqual(p
.communicate()[0], "['ignore::DeprecationWarning']")
687 self
.assertEqual(p
.wait(), 0)
689 def test_comma_separated_warnings(self
):
690 newenv
= os
.environ
.copy()
691 newenv
["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
692 "ignore::UnicodeWarning")
693 p
= subprocess
.Popen([sys
.executable
,
694 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
695 stdout
=subprocess
.PIPE
, env
=newenv
)
696 self
.assertEqual(p
.communicate()[0],
697 "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
698 self
.assertEqual(p
.wait(), 0)
700 def test_envvar_and_command_line(self
):
701 newenv
= os
.environ
.copy()
702 newenv
["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
703 p
= subprocess
.Popen([sys
.executable
, "-W" "ignore::UnicodeWarning",
704 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
705 stdout
=subprocess
.PIPE
, env
=newenv
)
706 self
.assertEqual(p
.communicate()[0],
707 "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
708 self
.assertEqual(p
.wait(), 0)
710 class CEnvironmentVariableTests(EnvironmentVariableTests
):
713 class PyEnvironmentVariableTests(EnvironmentVariableTests
):
718 py_warnings
.onceregistry
.clear()
719 c_warnings
.onceregistry
.clear()
720 test_support
.run_unittest(CFilterTests
, PyFilterTests
,
721 CWarnTests
, PyWarnTests
,
722 CWCmdLineTests
, PyWCmdLineTests
,
724 CWarningsDisplayTests
, PyWarningsDisplayTests
,
725 CCatchWarningTests
, PyCatchWarningTests
,
726 CEnvironmentVariableTests
,
727 PyEnvironmentVariableTests
731 if __name__
== "__main__":