Changeset 391 for python/trunk/Lib/test/test_warnings.py
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/test/test_warnings.py
r2 r391 5 5 import sys 6 6 import unittest 7 import subprocess 7 8 from test import test_support 9 from test.script_helper import assert_python_ok 8 10 9 11 import warning_tests … … 11 13 import warnings as original_warnings 12 14 13 sys.modules['_warnings'] = 0 14 del sys.modules['warnings'] 15 16 import warnings as py_warnings 17 18 del sys.modules['_warnings'] 19 del sys.modules['warnings'] 20 21 import warnings as c_warnings 22 23 sys.modules['warnings'] = original_warnings 24 15 py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings']) 16 c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings']) 25 17 26 18 @contextmanager … … 38 30 pass 39 31 original_warnings = warning_tests.warnings 32 original_filters = module.filters 40 33 try: 34 module.filters = original_filters[:] 35 module.simplefilter("once") 41 36 warning_tests.warnings = module 42 37 yield 43 38 finally: 44 39 warning_tests.warnings = original_warnings 40 module.filters = original_filters 45 41 46 42 … … 85 81 self.module.filterwarnings("ignore", category=UserWarning) 86 82 self.module.warn("FilterTests.test_ignore", UserWarning) 87 self.assertEqual s(len(w), 0)83 self.assertEqual(len(w), 0) 88 84 89 85 def test_always(self): … … 94 90 message = "FilterTests.test_always" 95 91 self.module.warn(message, UserWarning) 96 self.assert _(message, w[-1].message)92 self.assertTrue(message, w[-1].message) 97 93 self.module.warn(message, UserWarning) 98 self.assert _(w[-1].message, message)94 self.assertTrue(w[-1].message, message) 99 95 100 96 def test_default(self): … … 107 103 self.module.warn(message, UserWarning) 108 104 if x == 0: 109 self.assertEqual s(w[-1].message, message)105 self.assertEqual(w[-1].message, message) 110 106 del w[:] 111 107 elif x == 1: 112 self.assertEqual s(len(w), 0)108 self.assertEqual(len(w), 0) 113 109 else: 114 110 raise ValueError("loop variant unhandled") … … 121 117 message = UserWarning("FilterTests.test_module") 122 118 self.module.warn(message, UserWarning) 123 self.assertEqual s(w[-1].message, message)119 self.assertEqual(w[-1].message, message) 124 120 del w[:] 125 121 self.module.warn(message, UserWarning) 126 self.assertEqual s(len(w), 0)122 self.assertEqual(len(w), 0) 127 123 128 124 def test_once(self): … … 134 130 self.module.warn_explicit(message, UserWarning, "test_warnings.py", 135 131 42) 136 self.assertEqual s(w[-1].message, message)132 self.assertEqual(w[-1].message, message) 137 133 del w[:] 138 134 self.module.warn_explicit(message, UserWarning, "test_warnings.py", 139 135 13) 140 self.assertEqual s(len(w), 0)136 self.assertEqual(len(w), 0) 141 137 self.module.warn_explicit(message, UserWarning, "test_warnings2.py", 142 138 42) 143 self.assertEqual s(len(w), 0)139 self.assertEqual(len(w), 0) 144 140 145 141 def test_inheritance(self): … … 162 158 except UserWarning: 163 159 self.fail("order handling for actions failed") 164 self.assertEqual s(len(w), 0)160 self.assertEqual(len(w), 0) 165 161 166 162 def test_filterwarnings(self): … … 176 172 self.module.warn(text) 177 173 self.assertEqual(str(w[-1].message), text) 178 self.assert _(w[-1].category is UserWarning)174 self.assertTrue(w[-1].category is UserWarning) 179 175 180 176 self.module.filterwarnings("ignore", "", Warning, "", 0) … … 189 185 self.module.warn(text) 190 186 self.assertEqual(str(w[-1].message), text) 191 self.assert _(w[-1].category is UserWarning)187 self.assertTrue(w[-1].category is UserWarning) 192 188 193 189 class CFilterTests(BaseTest, FilterTests): … … 205 201 with original_warnings.catch_warnings(record=True, 206 202 module=self.module) as w: 203 self.module.simplefilter("once") 207 204 for i in range(4): 208 205 text = 'multi %d' %i # Different text on each call. 209 206 self.module.warn(text) 210 207 self.assertEqual(str(w[-1].message), text) 211 self.assert _(w[-1].category is UserWarning)208 self.assertTrue(w[-1].category is UserWarning) 212 209 213 210 def test_filename(self): … … 324 321 325 322 def test_warn_explicit_type_errors(self): 326 # warn_explicit() shou d error out gracefully if it is given objects323 # warn_explicit() should error out gracefully if it is given objects 327 324 # of the wrong types. 328 325 # lineno is expected to be an integer. … … 348 345 {"err" : "there is no %(err)s"}) 349 346 350 self.assertRaises(ValueError, self.module.warn, BadStrWarning()) 347 with self.assertRaises(ValueError): 348 self.module.warn(BadStrWarning()) 351 349 352 350 … … 354 352 module = c_warnings 355 353 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')) 359 356 360 class PyWarnTests(BaseTest, WarnTests): 357 361 module = py_warnings 362 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')) 358 368 359 369 … … 373 383 self.assertRaises(UserWarning, self.module.warn, 'convert to error') 374 384 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) 391 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)") 397 # '-Wi' was observed 398 self.assertFalse(out.strip()) 399 self.assertNotIn(b'RuntimeWarning', err) 400 375 401 class CWCmdLineTests(BaseTest, WCmdLineTests): 376 402 module = c_warnings … … 408 434 self.module.filterwarnings("once", category=UserWarning) 409 435 self.module.warn_explicit(message, UserWarning, "file", 42) 410 self. failUnlessEqual(w[-1].message, message)436 self.assertEqual(w[-1].message, message) 411 437 del w[:] 412 438 self.module.warn_explicit(message, UserWarning, "file", 42) 413 self.assertEqual s(len(w), 0)439 self.assertEqual(len(w), 0) 414 440 # Test the resetting of onceregistry. 415 441 self.module.onceregistry = {} 416 442 __warningregistry__ = {} 417 443 self.module.warn('onceregistry test') 418 self. failUnlessEqual(w[-1].message.args, message.args)444 self.assertEqual(w[-1].message.args, message.args) 419 445 # Removal of onceregistry is okay. 420 446 del w[:] … … 422 448 __warningregistry__ = {} 423 449 self.module.warn_explicit(message, UserWarning, "file", 42) 424 self.assertEqual s(len(w), 0)450 self.assertEqual(len(w), 0) 425 451 finally: 426 452 self.module.onceregistry = original_registry 453 454 def test_default_action(self): 455 # Replacing or removing defaultaction should be okay. 456 message = UserWarning("defaultaction test") 457 original = self.module.defaultaction 458 try: 459 with original_warnings.catch_warnings(record=True, 460 module=self.module) as w: 461 self.module.resetwarnings() 462 registry = {} 463 self.module.warn_explicit(message, UserWarning, "<test>", 42, 464 registry=registry) 465 self.assertEqual(w[-1].message, message) 466 self.assertEqual(len(w), 1) 467 self.assertEqual(len(registry), 1) 468 del w[:] 469 # Test removal. 470 del self.module.defaultaction 471 __warningregistry__ = {} 472 registry = {} 473 self.module.warn_explicit(message, UserWarning, "<test>", 43, 474 registry=registry) 475 self.assertEqual(w[-1].message, message) 476 self.assertEqual(len(w), 1) 477 self.assertEqual(len(registry), 1) 478 del w[:] 479 # Test setting. 480 self.module.defaultaction = "ignore" 481 __warningregistry__ = {} 482 registry = {} 483 self.module.warn_explicit(message, UserWarning, "<test>", 44, 484 registry=registry) 485 self.assertEqual(len(w), 0) 486 finally: 487 self.module.defaultaction = original 427 488 428 489 def test_showwarning_missing(self): … … 435 496 self.module.warn(text) 436 497 result = stream.getvalue() 437 self. failUnless(text inresult)498 self.assertIn(text, result) 438 499 439 500 def test_showwarning_not_callable(self): 440 self.module.filterwarnings("always", category=UserWarning)441 old_showwarning = self.module.showwarning442 self.module.showwarning = 23443 try:444 self.assertRaises(TypeError, self.module.warn, "Warning!")445 finally:446 self.module.showwarning = old_showwarning447 self.module.resetwarnings()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 505 try: 506 self.assertRaises(TypeError, self.module.warn, "Warning!") 507 finally: 508 self.module.showwarning = old_showwarning 448 509 449 510 def test_show_warning_output(self): … … 456 517 warning_tests.inner(text) 457 518 result = stream.getvalue() 458 self. failUnlessEqual(result.count('\n'), 2,519 self.assertEqual(result.count('\n'), 2, 459 520 "Too many newlines in %r" % result) 460 521 first_line, second_line = result.split('\n', 1) … … 463 524 path, line, warning_class, message = first_line_parts 464 525 line = int(line) 465 self. failUnlessEqual(expected_file, path)466 self. failUnlessEqual(warning_class, ' ' + UserWarning.__name__)467 self. failUnlessEqual(message, ' ' + text)526 self.assertEqual(expected_file, path) 527 self.assertEqual(warning_class, ' ' + UserWarning.__name__) 528 self.assertEqual(message, ' ' + text) 468 529 expected_line = ' ' + linecache.getline(path, line).strip() + '\n' 469 530 assert expected_line 470 self.failUnlessEqual(second_line, expected_line) 531 self.assertEqual(second_line, expected_line) 532 533 def test_filename_none(self): 534 # issue #12467: race condition if a warning is emitted at shutdown 535 globals_dict = globals() 536 oldfile = globals_dict['__file__'] 537 try: 538 with original_warnings.catch_warnings(module=self.module) as w: 539 self.module.filterwarnings("always", category=UserWarning) 540 globals_dict['__file__'] = None 541 self.module.warn('test', UserWarning) 542 finally: 543 globals_dict['__file__'] = oldfile 471 544 472 545 … … 485 558 expect = format % (file_name, line_num, category.__name__, message, 486 559 file_line) 487 self. failUnlessEqual(expect, self.module.formatwarning(message,560 self.assertEqual(expect, self.module.formatwarning(message, 488 561 category, file_name, line_num)) 489 562 # Test the 'line' argument. … … 491 564 expect = format % (file_name, line_num, category.__name__, message, 492 565 file_line) 493 self. failUnlessEqual(expect, self.module.formatwarning(message,566 self.assertEqual(expect, self.module.formatwarning(message, 494 567 category, file_name, line_num, file_line)) 495 568 … … 505 578 self.module.showwarning(message, category, file_name, line_num, 506 579 file_object) 507 self. failUnlessEqual(file_object.getvalue(), expect)580 self.assertEqual(file_object.getvalue(), expect) 508 581 # Test 'line' argument. 509 582 expected_file_line += "for the win!" … … 513 586 self.module.showwarning(message, category, file_name, line_num, 514 587 file_object, expected_file_line) 515 self. failUnlessEqual(expect, file_object.getvalue())588 self.assertEqual(expect, file_object.getvalue()) 516 589 517 590 class CWarningsDisplayTests(BaseTest, WarningsDisplayTests): … … 533 606 with wmod.catch_warnings(module=wmod, record=True): 534 607 wmod.filters = wmod.showwarning = object() 535 self.assert _(wmod.filters is orig_filters)536 self.assert _(wmod.showwarning is orig_showwarning)608 self.assertTrue(wmod.filters is orig_filters) 609 self.assertTrue(wmod.showwarning is orig_showwarning) 537 610 # Same test, but with recording disabled 538 611 with wmod.catch_warnings(module=wmod, record=False): 539 612 wmod.filters = wmod.showwarning = object() 540 self.assert _(wmod.filters is orig_filters)541 self.assert _(wmod.showwarning is orig_showwarning)613 self.assertTrue(wmod.filters is orig_filters) 614 self.assertTrue(wmod.showwarning is orig_showwarning) 542 615 543 616 def test_catch_warnings_recording(self): … … 546 619 with wmod.catch_warnings(module=wmod, record=True) as w: 547 620 self.assertEqual(w, []) 548 self.assert _(type(w) is list)621 self.assertTrue(type(w) is list) 549 622 wmod.simplefilter("always") 550 623 wmod.warn("foo") … … 559 632 orig_showwarning = wmod.showwarning 560 633 with wmod.catch_warnings(module=wmod, record=False) as w: 561 self.assert _(w is None)562 self.assert _(wmod.showwarning is orig_showwarning)634 self.assertTrue(w is None) 635 self.assertTrue(wmod.showwarning is orig_showwarning) 563 636 564 637 def test_catch_warnings_reentry_guard(self): … … 581 654 # Ensure default behaviour is not to record warnings 582 655 with wmod.catch_warnings(module=wmod) as w: 583 self.assert _(w is None)584 self.assert _(wmod.showwarning is orig_showwarning)585 self.assert _(wmod.filters is not orig_filters)586 self.assert _(wmod.filters is orig_filters)656 self.assertTrue(w is None) 657 self.assertTrue(wmod.showwarning is orig_showwarning) 658 self.assertTrue(wmod.filters is not orig_filters) 659 self.assertTrue(wmod.filters is orig_filters) 587 660 if wmod is sys.modules['warnings']: 588 661 # Ensure the default module is this one 589 662 with wmod.catch_warnings() as w: 590 self.assert _(w is None)591 self.assert _(wmod.showwarning is orig_showwarning)592 self.assert _(wmod.filters is not orig_filters)593 self.assert _(wmod.filters is orig_filters)663 self.assertTrue(w is None) 664 self.assertTrue(wmod.showwarning is orig_showwarning) 665 self.assertTrue(wmod.filters is not orig_filters) 666 self.assertTrue(wmod.filters is orig_filters) 594 667 595 668 def test_check_warnings(self): 596 669 # Explicit tests for the test_support convenience wrapper 597 670 wmod = self.module 598 if wmod is sys.modules['warnings']: 599 with test_support.check_warnings() as w: 600 self.assertEqual(w.warnings, []) 601 wmod.simplefilter("always") 671 if wmod is not sys.modules['warnings']: 672 return 673 with test_support.check_warnings(quiet=False) as w: 674 self.assertEqual(w.warnings, []) 675 wmod.simplefilter("always") 676 wmod.warn("foo") 677 self.assertEqual(str(w.message), "foo") 678 wmod.warn("bar") 679 self.assertEqual(str(w.message), "bar") 680 self.assertEqual(str(w.warnings[0].message), "foo") 681 self.assertEqual(str(w.warnings[1].message), "bar") 682 w.reset() 683 self.assertEqual(w.warnings, []) 684 685 with test_support.check_warnings(): 686 # defaults to quiet=True without argument 687 pass 688 with test_support.check_warnings(('foo', UserWarning)): 689 wmod.warn("foo") 690 691 with self.assertRaises(AssertionError): 692 with test_support.check_warnings(('', RuntimeWarning)): 693 # defaults to quiet=False with argument 694 pass 695 with self.assertRaises(AssertionError): 696 with test_support.check_warnings(('foo', RuntimeWarning)): 602 697 wmod.warn("foo") 603 self.assertEqual(str(w.message), "foo")604 wmod.warn("bar")605 self.assertEqual(str(w.message), "bar")606 self.assertEqual(str(w.warnings[0].message), "foo")607 self.assertEqual(str(w.warnings[1].message), "bar")608 w.reset()609 self.assertEqual(w.warnings, [])610 611 698 612 699 … … 618 705 619 706 620 class ShowwarningDeprecationTests(BaseTest): 621 622 """Test the deprecation of the old warnings.showwarning() API works.""" 623 624 @staticmethod 625 def bad_showwarning(message, category, filename, lineno, file=None): 626 pass 627 628 @staticmethod 629 def ok_showwarning(*args): 630 pass 631 632 def test_deprecation(self): 633 # message, category, filename, lineno[, file[, line]] 634 args = ("message", UserWarning, "file name", 42) 635 with original_warnings.catch_warnings(module=self.module): 636 self.module.filterwarnings("error", category=DeprecationWarning) 637 self.module.showwarning = self.bad_showwarning 638 self.assertRaises(DeprecationWarning, self.module.warn_explicit, 639 *args) 640 self.module.showwarning = self.ok_showwarning 641 try: 642 self.module.warn_explicit(*args) 643 except DeprecationWarning as exc: 644 self.fail('showwarning(*args) should not trigger a ' 645 'DeprecationWarning') 646 647 class CShowwarningDeprecationTests(ShowwarningDeprecationTests): 707 class EnvironmentVariableTests(BaseTest): 708 709 def test_single_warning(self): 710 newenv = os.environ.copy() 711 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" 712 p = subprocess.Popen([sys.executable, 713 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], 714 stdout=subprocess.PIPE, env=newenv) 715 self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']") 716 self.assertEqual(p.wait(), 0) 717 718 def test_comma_separated_warnings(self): 719 newenv = os.environ.copy() 720 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning," 721 "ignore::UnicodeWarning") 722 p = subprocess.Popen([sys.executable, 723 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], 724 stdout=subprocess.PIPE, env=newenv) 725 self.assertEqual(p.communicate()[0], 726 "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") 727 self.assertEqual(p.wait(), 0) 728 729 def test_envvar_and_command_line(self): 730 newenv = os.environ.copy() 731 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning" 732 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning", 733 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"], 734 stdout=subprocess.PIPE, env=newenv) 735 self.assertEqual(p.communicate()[0], 736 "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']") 737 self.assertEqual(p.wait(), 0) 738 739 class CEnvironmentVariableTests(EnvironmentVariableTests): 648 740 module = c_warnings 649 741 650 651 class PyShowwarningDeprecationTests(ShowwarningDeprecationTests): 742 class PyEnvironmentVariableTests(EnvironmentVariableTests): 652 743 module = py_warnings 653 744 … … 662 753 CWarningsDisplayTests, PyWarningsDisplayTests, 663 754 CCatchWarningTests, PyCatchWarningTests, 664 C ShowwarningDeprecationTests,665 PyShowwarningDeprecationTests,755 CEnvironmentVariableTests, 756 PyEnvironmentVariableTests 666 757 ) 667 758
Note:
See TracChangeset
for help on using the changeset viewer.