move sections
[python/dscho.git] / Lib / test / test_warnings.py
blob4e0afcc659a6dd6282a627dd7b5fa0e63ee78054
1 from contextlib import contextmanager
2 import linecache
3 import os
4 import StringIO
5 import sys
6 import unittest
7 import subprocess
8 from test import test_support
10 import warning_tests
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'])
17 @contextmanager
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):
22 try:
23 to_clear.__warningregistry__.clear()
24 except AttributeError:
25 pass
26 try:
27 __warningregistry__.clear()
28 except NameError:
29 pass
30 original_warnings = warning_tests.warnings
31 original_filters = module.filters
32 try:
33 module.filters = original_filters[:]
34 module.simplefilter("once")
35 warning_tests.warnings = module
36 yield
37 finally:
38 warning_tests.warnings = original_warnings
39 module.filters = original_filters
42 class BaseTest(unittest.TestCase):
44 """Basic bookkeeping required for testing."""
46 def setUp(self):
47 # The __warningregistry__ needs to be in a pristine state for tests
48 # to work properly.
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()
60 def tearDown(self):
61 sys.modules['warnings'] = original_warnings
62 super(BaseTest, self).tearDown()
65 class FilterTests(object):
67 """Testing the filtering functionality."""
69 def test_error(self):
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")
101 for x in xrange(2):
102 self.module.warn(message, UserWarning)
103 if x == 0:
104 self.assertEquals(w[-1].message, message)
105 del w[:]
106 elif x == 1:
107 self.assertEquals(len(w), 0)
108 else:
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)
119 del w[:]
120 self.module.warn(message, UserWarning)
121 self.assertEquals(len(w), 0)
123 def test_once(self):
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)
132 del w[:]
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,
153 append=True)
154 del w[:]
155 try:
156 self.module.warn("FilterTests.test_ordering", UserWarning)
157 except 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):
189 module = c_warnings
191 class PyFilterTests(BaseTest, FilterTests):
192 module = py_warnings
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")
203 for i in range(4):
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),
215 "warning_tests.py")
216 warning_tests.outer("spam2")
217 self.assertEqual(os.path.basename(w[-1].filename),
218 "warning_tests.py")
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),
228 "warning_tests.py")
229 warning_tests.outer("spam4", stacklevel=1)
230 self.assertEqual(os.path.basename(w[-1].filename),
231 "warning_tests.py")
233 warning_tests.inner("spam5", stacklevel=2)
234 self.assertEqual(os.path.basename(w[-1].filename),
235 "test_warnings.py")
236 warning_tests.outer("spam6", stacklevel=2)
237 self.assertEqual(os.path.basename(w[-1].filename),
238 "warning_tests.py")
239 warning_tests.outer("spam6.5", stacklevel=3)
240 self.assertEqual(os.path.basename(w[-1].filename),
241 "test_warnings.py")
243 warning_tests.inner("spam7", stacklevel=9999)
244 self.assertEqual(os.path.basename(w[-1].filename),
245 "sys")
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__
251 try:
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__)
258 finally:
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'):
265 return
266 filename = warning_tests.__file__
267 module_name = warning_tests.__name__
268 try:
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])
276 finally:
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__
285 argv = sys.argv
286 try:
287 del warning_tests.__file__
288 warning_tests.__name__ = '__main__'
289 del sys.argv
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__')
295 finally:
296 warning_tests.__file__ = filename
297 warning_tests.__name__ = module_name
298 sys.argv = argv
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.
303 # Tests issue 2743.
304 file_name = warning_tests.__file__
305 module_name = warning_tests.__name__
306 argv = sys.argv
307 try:
308 del warning_tests.__file__
309 warning_tests.__name__ = '__main__'
310 sys.argv = ['']
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__')
316 finally:
317 warning_tests.__file__ = file_name
318 warning_tests.__name__ = module_name
319 sys.argv = argv
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,
330 None, None, None, 1)
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):
337 # issue 6415
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__."""
342 def __str__(self):
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):
351 module = c_warnings
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):
360 module = py_warnings
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):
385 module = c_warnings
387 class PyWCmdLineTests(BaseTest, WCmdLineTests):
388 module = py_warnings
391 class _WarningsTests(BaseTest):
393 """Tests specific to the _warnings module."""
395 module = c_warnings
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,
402 'convert to error')
403 del self.module.filters
404 self.assertRaises(UserWarning, self.module.warn,
405 'convert to error')
407 def test_onceregistry(self):
408 # Replacing or removing the onceregistry should be okay.
409 global __warningregistry__
410 message = UserWarning('onceregistry test')
411 try:
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)
420 del w[:]
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.
429 del w[:]
430 del self.module.onceregistry
431 __warningregistry__ = {}
432 self.module.warn_explicit(message, UserWarning, "file", 42)
433 self.assertEquals(len(w), 0)
434 finally:
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
441 try:
442 with original_warnings.catch_warnings(record=True,
443 module=self.module) as w:
444 self.module.resetwarnings()
445 registry = {}
446 self.module.warn_explicit(message, UserWarning, "<test>", 42,
447 registry=registry)
448 self.assertEqual(w[-1].message, message)
449 self.assertEqual(len(w), 1)
450 self.assertEqual(len(registry), 1)
451 del w[:]
452 # Test removal.
453 del self.module.defaultaction
454 __warningregistry__ = {}
455 registry = {}
456 self.module.warn_explicit(message, UserWarning, "<test>", 43,
457 registry=registry)
458 self.assertEqual(w[-1].message, message)
459 self.assertEqual(len(w), 1)
460 self.assertEqual(len(registry), 1)
461 del w[:]
462 # Test setting.
463 self.module.defaultaction = "ignore"
464 __warningregistry__ = {}
465 registry = {}
466 self.module.warn_explicit(message, UserWarning, "<test>", 44,
467 registry=registry)
468 self.assertEqual(len(w), 0)
469 finally:
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
488 try:
489 self.assertRaises(TypeError, self.module.warn, "Warning!")
490 finally:
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
508 line = int(line)
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'
513 assert expected_line
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):
523 message = "msg"
524 category = Warning
525 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
526 line_num = 3
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,
530 file_line)
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,
536 file_line)
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'
542 line_num = 3
543 expected_file_line = linecache.getline(file_name, line_num).strip()
544 message = 'msg'
545 category = Warning
546 file_object = StringIO.StringIO()
547 expect = self.module.formatwarning(message, category, file_name,
548 line_num)
549 self.module.showwarning(message, category, file_name, line_num,
550 file_object)
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):
562 module = c_warnings
564 class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
565 module = py_warnings
568 class CatchWarningTests(BaseTest):
570 """Test catch_warnings()."""
572 def test_catch_warnings_restore(self):
573 wmod = self.module
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):
588 wmod = self.module
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")
594 wmod.warn("foo")
595 self.assertEqual(str(w[-1].message), "foo")
596 wmod.warn("bar")
597 self.assertEqual(str(w[-1].message), "bar")
598 self.assertEqual(str(w[0].message), "foo")
599 self.assertEqual(str(w[1].message), "bar")
600 del w[:]
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):
609 wmod = self.module
610 # Ensure catch_warnings is protected against incorrect usage
611 x = wmod.catch_warnings(module=wmod, record=True)
612 self.assertRaises(RuntimeError, x.__exit__)
613 with x:
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__)
618 with x:
619 self.assertRaises(RuntimeError, x.__enter__)
621 def test_catch_warnings_defaults(self):
622 wmod = self.module
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
641 wmod = self.module
642 if wmod is not sys.modules['warnings']:
643 return
644 with test_support.check_warnings(quiet=False) as w:
645 self.assertEqual(w.warnings, [])
646 wmod.simplefilter("always")
647 wmod.warn("foo")
648 self.assertEqual(str(w.message), "foo")
649 wmod.warn("bar")
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")
653 w.reset()
654 self.assertEqual(w.warnings, [])
656 with test_support.check_warnings():
657 # defaults to quiet=True without argument
658 pass
659 with test_support.check_warnings(('foo', UserWarning)):
660 wmod.warn("foo")
662 with self.assertRaises(AssertionError):
663 with test_support.check_warnings(('', RuntimeWarning)):
664 # defaults to quiet=False with argument
665 pass
666 with self.assertRaises(AssertionError):
667 with test_support.check_warnings(('foo', RuntimeWarning)):
668 wmod.warn("foo")
671 class CCatchWarningTests(CatchWarningTests):
672 module = c_warnings
674 class PyCatchWarningTests(CatchWarningTests):
675 module = py_warnings
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):
711 module = c_warnings
713 class PyEnvironmentVariableTests(EnvironmentVariableTests):
714 module = py_warnings
717 def test_main():
718 py_warnings.onceregistry.clear()
719 c_warnings.onceregistry.clear()
720 test_support.run_unittest(CFilterTests, PyFilterTests,
721 CWarnTests, PyWarnTests,
722 CWCmdLineTests, PyWCmdLineTests,
723 _WarningsTests,
724 CWarningsDisplayTests, PyWarningsDisplayTests,
725 CCatchWarningTests, PyCatchWarningTests,
726 CEnvironmentVariableTests,
727 PyEnvironmentVariableTests
731 if __name__ == "__main__":
732 test_main()