1import contextlib 2import difflib 3import pprint 4import pickle 5import re 6import sys 7import logging 8import warnings 9import weakref 10import inspect 11import types 12 13from copy import deepcopy 14from test import support 15 16import unittest 17 18from unittest.test.support import ( 19 TestEquality, TestHashing, LoggingResult, LegacyLoggingResult, 20 ResultWithNoStartTestRunStopTestRun 21) 22from test.support import captured_stderr, gc_collect 23 24 25log_foo = logging.getLogger('foo') 26log_foobar = logging.getLogger('foo.bar') 27log_quux = logging.getLogger('quux') 28 29 30class Test(object): 31 "Keep these TestCase classes out of the main namespace" 32 33 class Foo(unittest.TestCase): 34 def runTest(self): pass 35 def test1(self): pass 36 37 class Bar(Foo): 38 def test2(self): pass 39 40 class LoggingTestCase(unittest.TestCase): 41 """A test case which logs its calls.""" 42 43 def __init__(self, events): 44 super(Test.LoggingTestCase, self).__init__('test') 45 self.events = events 46 47 def setUp(self): 48 self.events.append('setUp') 49 50 def test(self): 51 self.events.append('test') 52 53 def tearDown(self): 54 self.events.append('tearDown') 55 56 57class Test_TestCase(unittest.TestCase, TestEquality, TestHashing): 58 59 ### Set up attributes used by inherited tests 60 ################################################################ 61 62 # Used by TestHashing.test_hash and TestEquality.test_eq 63 eq_pairs = [(Test.Foo('test1'), Test.Foo('test1'))] 64 65 # Used by TestEquality.test_ne 66 ne_pairs = [(Test.Foo('test1'), Test.Foo('runTest')), 67 (Test.Foo('test1'), Test.Bar('test1')), 68 (Test.Foo('test1'), Test.Bar('test2'))] 69 70 ################################################################ 71 ### /Set up attributes used by inherited tests 72 73 74 # "class TestCase([methodName])" 75 # ... 76 # "Each instance of TestCase will run a single test method: the 77 # method named methodName." 78 # ... 79 # "methodName defaults to "runTest"." 80 # 81 # Make sure it really is optional, and that it defaults to the proper 82 # thing. 83 def test_init__no_test_name(self): 84 class Test(unittest.TestCase): 85 def runTest(self): raise MyException() 86 def test(self): pass 87 88 self.assertEqual(Test().id()[-13:], '.Test.runTest') 89 90 # test that TestCase can be instantiated with no args 91 # primarily for use at the interactive interpreter 92 test = unittest.TestCase() 93 test.assertEqual(3, 3) 94 with test.assertRaises(test.failureException): 95 test.assertEqual(3, 2) 96 97 with self.assertRaises(AttributeError): 98 test.run() 99 100 # "class TestCase([methodName])" 101 # ... 102 # "Each instance of TestCase will run a single test method: the 103 # method named methodName." 104 def test_init__test_name__valid(self): 105 class Test(unittest.TestCase): 106 def runTest(self): raise MyException() 107 def test(self): pass 108 109 self.assertEqual(Test('test').id()[-10:], '.Test.test') 110 111 # "class TestCase([methodName])" 112 # ... 113 # "Each instance of TestCase will run a single test method: the 114 # method named methodName." 115 def test_init__test_name__invalid(self): 116 class Test(unittest.TestCase): 117 def runTest(self): raise MyException() 118 def test(self): pass 119 120 try: 121 Test('testfoo') 122 except ValueError: 123 pass 124 else: 125 self.fail("Failed to raise ValueError") 126 127 # "Return the number of tests represented by the this test object. For 128 # TestCase instances, this will always be 1" 129 def test_countTestCases(self): 130 class Foo(unittest.TestCase): 131 def test(self): pass 132 133 self.assertEqual(Foo('test').countTestCases(), 1) 134 135 # "Return the default type of test result object to be used to run this 136 # test. For TestCase instances, this will always be 137 # unittest.TestResult; subclasses of TestCase should 138 # override this as necessary." 139 def test_defaultTestResult(self): 140 class Foo(unittest.TestCase): 141 def runTest(self): 142 pass 143 144 result = Foo().defaultTestResult() 145 self.assertEqual(type(result), unittest.TestResult) 146 147 # "When a setUp() method is defined, the test runner will run that method 148 # prior to each test. Likewise, if a tearDown() method is defined, the 149 # test runner will invoke that method after each test. In the example, 150 # setUp() was used to create a fresh sequence for each test." 151 # 152 # Make sure the proper call order is maintained, even if setUp() raises 153 # an exception. 154 def test_run_call_order__error_in_setUp(self): 155 events = [] 156 result = LoggingResult(events) 157 158 class Foo(Test.LoggingTestCase): 159 def setUp(self): 160 super(Foo, self).setUp() 161 raise RuntimeError('raised by Foo.setUp') 162 163 Foo(events).run(result) 164 expected = ['startTest', 'setUp', 'addError', 'stopTest'] 165 self.assertEqual(events, expected) 166 167 # "With a temporary result stopTestRun is called when setUp errors. 168 def test_run_call_order__error_in_setUp_default_result(self): 169 events = [] 170 171 class Foo(Test.LoggingTestCase): 172 def defaultTestResult(self): 173 return LoggingResult(self.events) 174 175 def setUp(self): 176 super(Foo, self).setUp() 177 raise RuntimeError('raised by Foo.setUp') 178 179 Foo(events).run() 180 expected = ['startTestRun', 'startTest', 'setUp', 'addError', 181 'stopTest', 'stopTestRun'] 182 self.assertEqual(events, expected) 183 184 # "When a setUp() method is defined, the test runner will run that method 185 # prior to each test. Likewise, if a tearDown() method is defined, the 186 # test runner will invoke that method after each test. In the example, 187 # setUp() was used to create a fresh sequence for each test." 188 # 189 # Make sure the proper call order is maintained, even if the test raises 190 # an error (as opposed to a failure). 191 def test_run_call_order__error_in_test(self): 192 events = [] 193 result = LoggingResult(events) 194 195 class Foo(Test.LoggingTestCase): 196 def test(self): 197 super(Foo, self).test() 198 raise RuntimeError('raised by Foo.test') 199 200 expected = ['startTest', 'setUp', 'test', 201 'addError', 'tearDown', 'stopTest'] 202 Foo(events).run(result) 203 self.assertEqual(events, expected) 204 205 # "With a default result, an error in the test still results in stopTestRun 206 # being called." 207 def test_run_call_order__error_in_test_default_result(self): 208 events = [] 209 210 class Foo(Test.LoggingTestCase): 211 def defaultTestResult(self): 212 return LoggingResult(self.events) 213 214 def test(self): 215 super(Foo, self).test() 216 raise RuntimeError('raised by Foo.test') 217 218 expected = ['startTestRun', 'startTest', 'setUp', 'test', 219 'addError', 'tearDown', 'stopTest', 'stopTestRun'] 220 Foo(events).run() 221 self.assertEqual(events, expected) 222 223 # "When a setUp() method is defined, the test runner will run that method 224 # prior to each test. Likewise, if a tearDown() method is defined, the 225 # test runner will invoke that method after each test. In the example, 226 # setUp() was used to create a fresh sequence for each test." 227 # 228 # Make sure the proper call order is maintained, even if the test signals 229 # a failure (as opposed to an error). 230 def test_run_call_order__failure_in_test(self): 231 events = [] 232 result = LoggingResult(events) 233 234 class Foo(Test.LoggingTestCase): 235 def test(self): 236 super(Foo, self).test() 237 self.fail('raised by Foo.test') 238 239 expected = ['startTest', 'setUp', 'test', 240 'addFailure', 'tearDown', 'stopTest'] 241 Foo(events).run(result) 242 self.assertEqual(events, expected) 243 244 # "When a test fails with a default result stopTestRun is still called." 245 def test_run_call_order__failure_in_test_default_result(self): 246 247 class Foo(Test.LoggingTestCase): 248 def defaultTestResult(self): 249 return LoggingResult(self.events) 250 def test(self): 251 super(Foo, self).test() 252 self.fail('raised by Foo.test') 253 254 expected = ['startTestRun', 'startTest', 'setUp', 'test', 255 'addFailure', 'tearDown', 'stopTest', 'stopTestRun'] 256 events = [] 257 Foo(events).run() 258 self.assertEqual(events, expected) 259 260 # "When a setUp() method is defined, the test runner will run that method 261 # prior to each test. Likewise, if a tearDown() method is defined, the 262 # test runner will invoke that method after each test. In the example, 263 # setUp() was used to create a fresh sequence for each test." 264 # 265 # Make sure the proper call order is maintained, even if tearDown() raises 266 # an exception. 267 def test_run_call_order__error_in_tearDown(self): 268 events = [] 269 result = LoggingResult(events) 270 271 class Foo(Test.LoggingTestCase): 272 def tearDown(self): 273 super(Foo, self).tearDown() 274 raise RuntimeError('raised by Foo.tearDown') 275 276 Foo(events).run(result) 277 expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError', 278 'stopTest'] 279 self.assertEqual(events, expected) 280 281 # "When tearDown errors with a default result stopTestRun is still called." 282 def test_run_call_order__error_in_tearDown_default_result(self): 283 284 class Foo(Test.LoggingTestCase): 285 def defaultTestResult(self): 286 return LoggingResult(self.events) 287 def tearDown(self): 288 super(Foo, self).tearDown() 289 raise RuntimeError('raised by Foo.tearDown') 290 291 events = [] 292 Foo(events).run() 293 expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown', 294 'addError', 'stopTest', 'stopTestRun'] 295 self.assertEqual(events, expected) 296 297 # "TestCase.run() still works when the defaultTestResult is a TestResult 298 # that does not support startTestRun and stopTestRun. 299 def test_run_call_order_default_result(self): 300 301 class Foo(unittest.TestCase): 302 def defaultTestResult(self): 303 return ResultWithNoStartTestRunStopTestRun() 304 def test(self): 305 pass 306 307 Foo('test').run() 308 309 def test_deprecation_of_return_val_from_test(self): 310 # Issue 41322 - deprecate return of value that is not None from a test 311 class Nothing: 312 def __eq__(self, o): 313 return o is None 314 class Foo(unittest.TestCase): 315 def test1(self): 316 return 1 317 def test2(self): 318 yield 1 319 def test3(self): 320 return Nothing() 321 322 with self.assertWarns(DeprecationWarning) as w: 323 Foo('test1').run() 324 self.assertIn('It is deprecated to return a value that is not None', str(w.warning)) 325 self.assertIn('test1', str(w.warning)) 326 self.assertEqual(w.filename, __file__) 327 328 with self.assertWarns(DeprecationWarning) as w: 329 Foo('test2').run() 330 self.assertIn('It is deprecated to return a value that is not None', str(w.warning)) 331 self.assertIn('test2', str(w.warning)) 332 self.assertEqual(w.filename, __file__) 333 334 with self.assertWarns(DeprecationWarning) as w: 335 Foo('test3').run() 336 self.assertIn('It is deprecated to return a value that is not None', str(w.warning)) 337 self.assertIn('test3', str(w.warning)) 338 self.assertEqual(w.filename, __file__) 339 340 def _check_call_order__subtests(self, result, events, expected_events): 341 class Foo(Test.LoggingTestCase): 342 def test(self): 343 super(Foo, self).test() 344 for i in [1, 2, 3]: 345 with self.subTest(i=i): 346 if i == 1: 347 self.fail('failure') 348 for j in [2, 3]: 349 with self.subTest(j=j): 350 if i * j == 6: 351 raise RuntimeError('raised by Foo.test') 352 1 / 0 353 354 # Order is the following: 355 # i=1 => subtest failure 356 # i=2, j=2 => subtest success 357 # i=2, j=3 => subtest error 358 # i=3, j=2 => subtest error 359 # i=3, j=3 => subtest success 360 # toplevel => error 361 Foo(events).run(result) 362 self.assertEqual(events, expected_events) 363 364 def test_run_call_order__subtests(self): 365 events = [] 366 result = LoggingResult(events) 367 expected = ['startTest', 'setUp', 'test', 368 'addSubTestFailure', 'addSubTestSuccess', 369 'addSubTestFailure', 'addSubTestFailure', 370 'addSubTestSuccess', 'addError', 'tearDown', 'stopTest'] 371 self._check_call_order__subtests(result, events, expected) 372 373 def test_run_call_order__subtests_legacy(self): 374 # With a legacy result object (without an addSubTest method), 375 # text execution stops after the first subtest failure. 376 events = [] 377 result = LegacyLoggingResult(events) 378 expected = ['startTest', 'setUp', 'test', 379 'addFailure', 'tearDown', 'stopTest'] 380 self._check_call_order__subtests(result, events, expected) 381 382 def _check_call_order__subtests_success(self, result, events, expected_events): 383 class Foo(Test.LoggingTestCase): 384 def test(self): 385 super(Foo, self).test() 386 for i in [1, 2]: 387 with self.subTest(i=i): 388 for j in [2, 3]: 389 with self.subTest(j=j): 390 pass 391 392 Foo(events).run(result) 393 self.assertEqual(events, expected_events) 394 395 def test_run_call_order__subtests_success(self): 396 events = [] 397 result = LoggingResult(events) 398 # The 6 subtest successes are individually recorded, in addition 399 # to the whole test success. 400 expected = (['startTest', 'setUp', 'test'] 401 + 6 * ['addSubTestSuccess'] 402 + ['tearDown', 'addSuccess', 'stopTest']) 403 self._check_call_order__subtests_success(result, events, expected) 404 405 def test_run_call_order__subtests_success_legacy(self): 406 # With a legacy result, only the whole test success is recorded. 407 events = [] 408 result = LegacyLoggingResult(events) 409 expected = ['startTest', 'setUp', 'test', 'tearDown', 410 'addSuccess', 'stopTest'] 411 self._check_call_order__subtests_success(result, events, expected) 412 413 def test_run_call_order__subtests_failfast(self): 414 events = [] 415 result = LoggingResult(events) 416 result.failfast = True 417 418 class Foo(Test.LoggingTestCase): 419 def test(self): 420 super(Foo, self).test() 421 with self.subTest(i=1): 422 self.fail('failure') 423 with self.subTest(i=2): 424 self.fail('failure') 425 self.fail('failure') 426 427 expected = ['startTest', 'setUp', 'test', 428 'addSubTestFailure', 'tearDown', 'stopTest'] 429 Foo(events).run(result) 430 self.assertEqual(events, expected) 431 432 def test_subtests_failfast(self): 433 # Ensure proper test flow with subtests and failfast (issue #22894) 434 events = [] 435 436 class Foo(unittest.TestCase): 437 def test_a(self): 438 with self.subTest(): 439 events.append('a1') 440 events.append('a2') 441 442 def test_b(self): 443 with self.subTest(): 444 events.append('b1') 445 with self.subTest(): 446 self.fail('failure') 447 events.append('b2') 448 449 def test_c(self): 450 events.append('c') 451 452 result = unittest.TestResult() 453 result.failfast = True 454 suite = unittest.TestLoader().loadTestsFromTestCase(Foo) 455 suite.run(result) 456 457 expected = ['a1', 'a2', 'b1'] 458 self.assertEqual(events, expected) 459 460 def test_subtests_debug(self): 461 # Test debug() with a test that uses subTest() (bpo-34900) 462 events = [] 463 464 class Foo(unittest.TestCase): 465 def test_a(self): 466 events.append('test case') 467 with self.subTest(): 468 events.append('subtest 1') 469 470 Foo('test_a').debug() 471 472 self.assertEqual(events, ['test case', 'subtest 1']) 473 474 # "This class attribute gives the exception raised by the test() method. 475 # If a test framework needs to use a specialized exception, possibly to 476 # carry additional information, it must subclass this exception in 477 # order to ``play fair'' with the framework. The initial value of this 478 # attribute is AssertionError" 479 def test_failureException__default(self): 480 class Foo(unittest.TestCase): 481 def test(self): 482 pass 483 484 self.assertIs(Foo('test').failureException, AssertionError) 485 486 # "This class attribute gives the exception raised by the test() method. 487 # If a test framework needs to use a specialized exception, possibly to 488 # carry additional information, it must subclass this exception in 489 # order to ``play fair'' with the framework." 490 # 491 # Make sure TestCase.run() respects the designated failureException 492 def test_failureException__subclassing__explicit_raise(self): 493 events = [] 494 result = LoggingResult(events) 495 496 class Foo(unittest.TestCase): 497 def test(self): 498 raise RuntimeError() 499 500 failureException = RuntimeError 501 502 self.assertIs(Foo('test').failureException, RuntimeError) 503 504 505 Foo('test').run(result) 506 expected = ['startTest', 'addFailure', 'stopTest'] 507 self.assertEqual(events, expected) 508 509 # "This class attribute gives the exception raised by the test() method. 510 # If a test framework needs to use a specialized exception, possibly to 511 # carry additional information, it must subclass this exception in 512 # order to ``play fair'' with the framework." 513 # 514 # Make sure TestCase.run() respects the designated failureException 515 def test_failureException__subclassing__implicit_raise(self): 516 events = [] 517 result = LoggingResult(events) 518 519 class Foo(unittest.TestCase): 520 def test(self): 521 self.fail("foo") 522 523 failureException = RuntimeError 524 525 self.assertIs(Foo('test').failureException, RuntimeError) 526 527 528 Foo('test').run(result) 529 expected = ['startTest', 'addFailure', 'stopTest'] 530 self.assertEqual(events, expected) 531 532 # "The default implementation does nothing." 533 def test_setUp(self): 534 class Foo(unittest.TestCase): 535 def runTest(self): 536 pass 537 538 # ... and nothing should happen 539 Foo().setUp() 540 541 # "The default implementation does nothing." 542 def test_tearDown(self): 543 class Foo(unittest.TestCase): 544 def runTest(self): 545 pass 546 547 # ... and nothing should happen 548 Foo().tearDown() 549 550 # "Return a string identifying the specific test case." 551 # 552 # Because of the vague nature of the docs, I'm not going to lock this 553 # test down too much. Really all that can be asserted is that the id() 554 # will be a string (either 8-byte or unicode -- again, because the docs 555 # just say "string") 556 def test_id(self): 557 class Foo(unittest.TestCase): 558 def runTest(self): 559 pass 560 561 self.assertIsInstance(Foo().id(), str) 562 563 564 # "If result is omitted or None, a temporary result object is created, 565 # used, and is made available to the caller. As TestCase owns the 566 # temporary result startTestRun and stopTestRun are called. 567 568 def test_run__uses_defaultTestResult(self): 569 events = [] 570 defaultResult = LoggingResult(events) 571 572 class Foo(unittest.TestCase): 573 def test(self): 574 events.append('test') 575 576 def defaultTestResult(self): 577 return defaultResult 578 579 # Make run() find a result object on its own 580 result = Foo('test').run() 581 582 self.assertIs(result, defaultResult) 583 expected = ['startTestRun', 'startTest', 'test', 'addSuccess', 584 'stopTest', 'stopTestRun'] 585 self.assertEqual(events, expected) 586 587 588 # "The result object is returned to run's caller" 589 def test_run__returns_given_result(self): 590 591 class Foo(unittest.TestCase): 592 def test(self): 593 pass 594 595 result = unittest.TestResult() 596 597 retval = Foo('test').run(result) 598 self.assertIs(retval, result) 599 600 601 # "The same effect [as method run] may be had by simply calling the 602 # TestCase instance." 603 def test_call__invoking_an_instance_delegates_to_run(self): 604 resultIn = unittest.TestResult() 605 resultOut = unittest.TestResult() 606 607 class Foo(unittest.TestCase): 608 def test(self): 609 pass 610 611 def run(self, result): 612 self.assertIs(result, resultIn) 613 return resultOut 614 615 retval = Foo('test')(resultIn) 616 617 self.assertIs(retval, resultOut) 618 619 620 def testShortDescriptionWithoutDocstring(self): 621 self.assertIsNone(self.shortDescription()) 622 623 @unittest.skipIf(sys.flags.optimize >= 2, 624 "Docstrings are omitted with -O2 and above") 625 def testShortDescriptionWithOneLineDocstring(self): 626 """Tests shortDescription() for a method with a docstring.""" 627 self.assertEqual( 628 self.shortDescription(), 629 'Tests shortDescription() for a method with a docstring.') 630 631 @unittest.skipIf(sys.flags.optimize >= 2, 632 "Docstrings are omitted with -O2 and above") 633 def testShortDescriptionWithMultiLineDocstring(self): 634 """Tests shortDescription() for a method with a longer docstring. 635 636 This method ensures that only the first line of a docstring is 637 returned used in the short description, no matter how long the 638 whole thing is. 639 """ 640 self.assertEqual( 641 self.shortDescription(), 642 'Tests shortDescription() for a method with a longer ' 643 'docstring.') 644 645 @unittest.skipIf(sys.flags.optimize >= 2, 646 "Docstrings are omitted with -O2 and above") 647 def testShortDescriptionWhitespaceTrimming(self): 648 """ 649 Tests shortDescription() whitespace is trimmed, so that the first 650 line of nonwhite-space text becomes the docstring. 651 """ 652 self.assertEqual( 653 self.shortDescription(), 654 'Tests shortDescription() whitespace is trimmed, so that the first') 655 656 def testAddTypeEqualityFunc(self): 657 class SadSnake(object): 658 """Dummy class for test_addTypeEqualityFunc.""" 659 s1, s2 = SadSnake(), SadSnake() 660 self.assertFalse(s1 == s2) 661 def AllSnakesCreatedEqual(a, b, msg=None): 662 return type(a) == type(b) == SadSnake 663 self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual) 664 self.assertEqual(s1, s2) 665 # No this doesn't clean up and remove the SadSnake equality func 666 # from this TestCase instance but since it's local nothing else 667 # will ever notice that. 668 669 def testAssertIs(self): 670 thing = object() 671 self.assertIs(thing, thing) 672 self.assertRaises(self.failureException, self.assertIs, thing, object()) 673 674 def testAssertIsNot(self): 675 thing = object() 676 self.assertIsNot(thing, object()) 677 self.assertRaises(self.failureException, self.assertIsNot, thing, thing) 678 679 def testAssertIsInstance(self): 680 thing = [] 681 self.assertIsInstance(thing, list) 682 self.assertRaises(self.failureException, self.assertIsInstance, 683 thing, dict) 684 685 def testAssertNotIsInstance(self): 686 thing = [] 687 self.assertNotIsInstance(thing, dict) 688 self.assertRaises(self.failureException, self.assertNotIsInstance, 689 thing, list) 690 691 def testAssertIn(self): 692 animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'} 693 694 self.assertIn('a', 'abc') 695 self.assertIn(2, [1, 2, 3]) 696 self.assertIn('monkey', animals) 697 698 self.assertNotIn('d', 'abc') 699 self.assertNotIn(0, [1, 2, 3]) 700 self.assertNotIn('otter', animals) 701 702 self.assertRaises(self.failureException, self.assertIn, 'x', 'abc') 703 self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3]) 704 self.assertRaises(self.failureException, self.assertIn, 'elephant', 705 animals) 706 707 self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc') 708 self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3]) 709 self.assertRaises(self.failureException, self.assertNotIn, 'cow', 710 animals) 711 712 def testAssertDictContainsSubset(self): 713 with warnings.catch_warnings(): 714 warnings.simplefilter("ignore", DeprecationWarning) 715 716 self.assertDictContainsSubset({}, {}) 717 self.assertDictContainsSubset({}, {'a': 1}) 718 self.assertDictContainsSubset({'a': 1}, {'a': 1}) 719 self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2}) 720 self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2}) 721 722 with self.assertRaises(self.failureException): 723 self.assertDictContainsSubset({1: "one"}, {}) 724 725 with self.assertRaises(self.failureException): 726 self.assertDictContainsSubset({'a': 2}, {'a': 1}) 727 728 with self.assertRaises(self.failureException): 729 self.assertDictContainsSubset({'c': 1}, {'a': 1}) 730 731 with self.assertRaises(self.failureException): 732 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) 733 734 with self.assertRaises(self.failureException): 735 self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1}) 736 737 one = ''.join(chr(i) for i in range(255)) 738 # this used to cause a UnicodeDecodeError constructing the failure msg 739 with self.assertRaises(self.failureException): 740 self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'}) 741 742 def testAssertEqual(self): 743 equal_pairs = [ 744 ((), ()), 745 ({}, {}), 746 ([], []), 747 (set(), set()), 748 (frozenset(), frozenset())] 749 for a, b in equal_pairs: 750 # This mess of try excepts is to test the assertEqual behavior 751 # itself. 752 try: 753 self.assertEqual(a, b) 754 except self.failureException: 755 self.fail('assertEqual(%r, %r) failed' % (a, b)) 756 try: 757 self.assertEqual(a, b, msg='foo') 758 except self.failureException: 759 self.fail('assertEqual(%r, %r) with msg= failed' % (a, b)) 760 try: 761 self.assertEqual(a, b, 'foo') 762 except self.failureException: 763 self.fail('assertEqual(%r, %r) with third parameter failed' % 764 (a, b)) 765 766 unequal_pairs = [ 767 ((), []), 768 ({}, set()), 769 (set([4,1]), frozenset([4,2])), 770 (frozenset([4,5]), set([2,3])), 771 (set([3,4]), set([5,4]))] 772 for a, b in unequal_pairs: 773 self.assertRaises(self.failureException, self.assertEqual, a, b) 774 self.assertRaises(self.failureException, self.assertEqual, a, b, 775 'foo') 776 self.assertRaises(self.failureException, self.assertEqual, a, b, 777 msg='foo') 778 779 def testEquality(self): 780 self.assertListEqual([], []) 781 self.assertTupleEqual((), ()) 782 self.assertSequenceEqual([], ()) 783 784 a = [0, 'a', []] 785 b = [] 786 self.assertRaises(unittest.TestCase.failureException, 787 self.assertListEqual, a, b) 788 self.assertRaises(unittest.TestCase.failureException, 789 self.assertListEqual, tuple(a), tuple(b)) 790 self.assertRaises(unittest.TestCase.failureException, 791 self.assertSequenceEqual, a, tuple(b)) 792 793 b.extend(a) 794 self.assertListEqual(a, b) 795 self.assertTupleEqual(tuple(a), tuple(b)) 796 self.assertSequenceEqual(a, tuple(b)) 797 self.assertSequenceEqual(tuple(a), b) 798 799 self.assertRaises(self.failureException, self.assertListEqual, 800 a, tuple(b)) 801 self.assertRaises(self.failureException, self.assertTupleEqual, 802 tuple(a), b) 803 self.assertRaises(self.failureException, self.assertListEqual, None, b) 804 self.assertRaises(self.failureException, self.assertTupleEqual, None, 805 tuple(b)) 806 self.assertRaises(self.failureException, self.assertSequenceEqual, 807 None, tuple(b)) 808 self.assertRaises(self.failureException, self.assertListEqual, 1, 1) 809 self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1) 810 self.assertRaises(self.failureException, self.assertSequenceEqual, 811 1, 1) 812 813 self.assertDictEqual({}, {}) 814 815 c = { 'x': 1 } 816 d = {} 817 self.assertRaises(unittest.TestCase.failureException, 818 self.assertDictEqual, c, d) 819 820 d.update(c) 821 self.assertDictEqual(c, d) 822 823 d['x'] = 0 824 self.assertRaises(unittest.TestCase.failureException, 825 self.assertDictEqual, c, d, 'These are unequal') 826 827 self.assertRaises(self.failureException, self.assertDictEqual, None, d) 828 self.assertRaises(self.failureException, self.assertDictEqual, [], d) 829 self.assertRaises(self.failureException, self.assertDictEqual, 1, 1) 830 831 def testAssertSequenceEqualMaxDiff(self): 832 self.assertEqual(self.maxDiff, 80*8) 833 seq1 = 'a' + 'x' * 80**2 834 seq2 = 'b' + 'x' * 80**2 835 diff = '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(), 836 pprint.pformat(seq2).splitlines())) 837 # the +1 is the leading \n added by assertSequenceEqual 838 omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,) 839 840 self.maxDiff = len(diff)//2 841 try: 842 843 self.assertSequenceEqual(seq1, seq2) 844 except self.failureException as e: 845 msg = e.args[0] 846 else: 847 self.fail('assertSequenceEqual did not fail.') 848 self.assertLess(len(msg), len(diff)) 849 self.assertIn(omitted, msg) 850 851 self.maxDiff = len(diff) * 2 852 try: 853 self.assertSequenceEqual(seq1, seq2) 854 except self.failureException as e: 855 msg = e.args[0] 856 else: 857 self.fail('assertSequenceEqual did not fail.') 858 self.assertGreater(len(msg), len(diff)) 859 self.assertNotIn(omitted, msg) 860 861 self.maxDiff = None 862 try: 863 self.assertSequenceEqual(seq1, seq2) 864 except self.failureException as e: 865 msg = e.args[0] 866 else: 867 self.fail('assertSequenceEqual did not fail.') 868 self.assertGreater(len(msg), len(diff)) 869 self.assertNotIn(omitted, msg) 870 871 def testTruncateMessage(self): 872 self.maxDiff = 1 873 message = self._truncateMessage('foo', 'bar') 874 omitted = unittest.case.DIFF_OMITTED % len('bar') 875 self.assertEqual(message, 'foo' + omitted) 876 877 self.maxDiff = None 878 message = self._truncateMessage('foo', 'bar') 879 self.assertEqual(message, 'foobar') 880 881 self.maxDiff = 4 882 message = self._truncateMessage('foo', 'bar') 883 self.assertEqual(message, 'foobar') 884 885 def testAssertDictEqualTruncates(self): 886 test = unittest.TestCase('assertEqual') 887 def truncate(msg, diff): 888 return 'foo' 889 test._truncateMessage = truncate 890 try: 891 test.assertDictEqual({}, {1: 0}) 892 except self.failureException as e: 893 self.assertEqual(str(e), 'foo') 894 else: 895 self.fail('assertDictEqual did not fail') 896 897 def testAssertMultiLineEqualTruncates(self): 898 test = unittest.TestCase('assertEqual') 899 def truncate(msg, diff): 900 return 'foo' 901 test._truncateMessage = truncate 902 try: 903 test.assertMultiLineEqual('foo', 'bar') 904 except self.failureException as e: 905 self.assertEqual(str(e), 'foo') 906 else: 907 self.fail('assertMultiLineEqual did not fail') 908 909 def testAssertEqual_diffThreshold(self): 910 # check threshold value 911 self.assertEqual(self._diffThreshold, 2**16) 912 # disable madDiff to get diff markers 913 self.maxDiff = None 914 915 # set a lower threshold value and add a cleanup to restore it 916 old_threshold = self._diffThreshold 917 self._diffThreshold = 2**5 918 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) 919 920 # under the threshold: diff marker (^) in error message 921 s = 'x' * (2**4) 922 with self.assertRaises(self.failureException) as cm: 923 self.assertEqual(s + 'a', s + 'b') 924 self.assertIn('^', str(cm.exception)) 925 self.assertEqual(s + 'a', s + 'a') 926 927 # over the threshold: diff not used and marker (^) not in error message 928 s = 'x' * (2**6) 929 # if the path that uses difflib is taken, _truncateMessage will be 930 # called -- replace it with explodingTruncation to verify that this 931 # doesn't happen 932 def explodingTruncation(message, diff): 933 raise SystemError('this should not be raised') 934 old_truncate = self._truncateMessage 935 self._truncateMessage = explodingTruncation 936 self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate)) 937 938 s1, s2 = s + 'a', s + 'b' 939 with self.assertRaises(self.failureException) as cm: 940 self.assertEqual(s1, s2) 941 self.assertNotIn('^', str(cm.exception)) 942 self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2)) 943 self.assertEqual(s + 'a', s + 'a') 944 945 def testAssertEqual_shorten(self): 946 # set a lower threshold value and add a cleanup to restore it 947 old_threshold = self._diffThreshold 948 self._diffThreshold = 0 949 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) 950 951 s = 'x' * 100 952 s1, s2 = s + 'a', s + 'b' 953 with self.assertRaises(self.failureException) as cm: 954 self.assertEqual(s1, s2) 955 c = 'xxxx[35 chars]' + 'x' * 61 956 self.assertEqual(str(cm.exception), "'%sa' != '%sb'" % (c, c)) 957 self.assertEqual(s + 'a', s + 'a') 958 959 p = 'y' * 50 960 s1, s2 = s + 'a' + p, s + 'b' + p 961 with self.assertRaises(self.failureException) as cm: 962 self.assertEqual(s1, s2) 963 c = 'xxxx[85 chars]xxxxxxxxxxx' 964 self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, p, c, p)) 965 966 p = 'y' * 100 967 s1, s2 = s + 'a' + p, s + 'b' + p 968 with self.assertRaises(self.failureException) as cm: 969 self.assertEqual(s1, s2) 970 c = 'xxxx[91 chars]xxxxx' 971 d = 'y' * 40 + '[56 chars]yyyy' 972 self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, d, c, d)) 973 974 def testAssertCountEqual(self): 975 a = object() 976 self.assertCountEqual([1, 2, 3], [3, 2, 1]) 977 self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']) 978 self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2)) 979 self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"]) 980 self.assertRaises(self.failureException, self.assertCountEqual, 981 [1, 2] + [3] * 100, [1] * 100 + [2, 3]) 982 self.assertRaises(self.failureException, self.assertCountEqual, 983 [1, "2", "a", "a"], ["a", "2", True, 1]) 984 self.assertRaises(self.failureException, self.assertCountEqual, 985 [10], [10, 11]) 986 self.assertRaises(self.failureException, self.assertCountEqual, 987 [10, 11], [10]) 988 self.assertRaises(self.failureException, self.assertCountEqual, 989 [10, 11, 10], [10, 11]) 990 991 # Test that sequences of unhashable objects can be tested for sameness: 992 self.assertCountEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]]) 993 # Test that iterator of unhashable objects can be tested for sameness: 994 self.assertCountEqual(iter([1, 2, [], 3, 4]), 995 iter([1, 2, [], 3, 4])) 996 997 # hashable types, but not orderable 998 self.assertRaises(self.failureException, self.assertCountEqual, 999 [], [divmod, 'x', 1, 5j, 2j, frozenset()]) 1000 # comparing dicts 1001 self.assertCountEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}]) 1002 # comparing heterogeneous non-hashable sequences 1003 self.assertCountEqual([1, 'x', divmod, []], [divmod, [], 'x', 1]) 1004 self.assertRaises(self.failureException, self.assertCountEqual, 1005 [], [divmod, [], 'x', 1, 5j, 2j, set()]) 1006 self.assertRaises(self.failureException, self.assertCountEqual, 1007 [[1]], [[2]]) 1008 1009 # Same elements, but not same sequence length 1010 self.assertRaises(self.failureException, self.assertCountEqual, 1011 [1, 1, 2], [2, 1]) 1012 self.assertRaises(self.failureException, self.assertCountEqual, 1013 [1, 1, "2", "a", "a"], ["2", "2", True, "a"]) 1014 self.assertRaises(self.failureException, self.assertCountEqual, 1015 [1, {'b': 2}, None, True], [{'b': 2}, True, None]) 1016 1017 # Same elements which don't reliably compare, in 1018 # different order, see issue 10242 1019 a = [{2,4}, {1,2}] 1020 b = a[::-1] 1021 self.assertCountEqual(a, b) 1022 1023 # test utility functions supporting assertCountEqual() 1024 1025 diffs = set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce')) 1026 expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} 1027 self.assertEqual(diffs, expected) 1028 1029 diffs = unittest.util._count_diff_all_purpose([[]], []) 1030 self.assertEqual(diffs, [(1, 0, [])]) 1031 1032 diffs = set(unittest.util._count_diff_hashable('aaabccd', 'abbbcce')) 1033 expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')} 1034 self.assertEqual(diffs, expected) 1035 1036 def testAssertSetEqual(self): 1037 set1 = set() 1038 set2 = set() 1039 self.assertSetEqual(set1, set2) 1040 1041 self.assertRaises(self.failureException, self.assertSetEqual, None, set2) 1042 self.assertRaises(self.failureException, self.assertSetEqual, [], set2) 1043 self.assertRaises(self.failureException, self.assertSetEqual, set1, None) 1044 self.assertRaises(self.failureException, self.assertSetEqual, set1, []) 1045 1046 set1 = set(['a']) 1047 set2 = set() 1048 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) 1049 1050 set1 = set(['a']) 1051 set2 = set(['a']) 1052 self.assertSetEqual(set1, set2) 1053 1054 set1 = set(['a']) 1055 set2 = set(['a', 'b']) 1056 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) 1057 1058 set1 = set(['a']) 1059 set2 = frozenset(['a', 'b']) 1060 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) 1061 1062 set1 = set(['a', 'b']) 1063 set2 = frozenset(['a', 'b']) 1064 self.assertSetEqual(set1, set2) 1065 1066 set1 = set() 1067 set2 = "foo" 1068 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) 1069 self.assertRaises(self.failureException, self.assertSetEqual, set2, set1) 1070 1071 # make sure any string formatting is tuple-safe 1072 set1 = set([(0, 1), (2, 3)]) 1073 set2 = set([(4, 5)]) 1074 self.assertRaises(self.failureException, self.assertSetEqual, set1, set2) 1075 1076 def testInequality(self): 1077 # Try ints 1078 self.assertGreater(2, 1) 1079 self.assertGreaterEqual(2, 1) 1080 self.assertGreaterEqual(1, 1) 1081 self.assertLess(1, 2) 1082 self.assertLessEqual(1, 2) 1083 self.assertLessEqual(1, 1) 1084 self.assertRaises(self.failureException, self.assertGreater, 1, 2) 1085 self.assertRaises(self.failureException, self.assertGreater, 1, 1) 1086 self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2) 1087 self.assertRaises(self.failureException, self.assertLess, 2, 1) 1088 self.assertRaises(self.failureException, self.assertLess, 1, 1) 1089 self.assertRaises(self.failureException, self.assertLessEqual, 2, 1) 1090 1091 # Try Floats 1092 self.assertGreater(1.1, 1.0) 1093 self.assertGreaterEqual(1.1, 1.0) 1094 self.assertGreaterEqual(1.0, 1.0) 1095 self.assertLess(1.0, 1.1) 1096 self.assertLessEqual(1.0, 1.1) 1097 self.assertLessEqual(1.0, 1.0) 1098 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1) 1099 self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0) 1100 self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1) 1101 self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0) 1102 self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0) 1103 self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0) 1104 1105 # Try Strings 1106 self.assertGreater('bug', 'ant') 1107 self.assertGreaterEqual('bug', 'ant') 1108 self.assertGreaterEqual('ant', 'ant') 1109 self.assertLess('ant', 'bug') 1110 self.assertLessEqual('ant', 'bug') 1111 self.assertLessEqual('ant', 'ant') 1112 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug') 1113 self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant') 1114 self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug') 1115 self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant') 1116 self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant') 1117 self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant') 1118 1119 # Try bytes 1120 self.assertGreater(b'bug', b'ant') 1121 self.assertGreaterEqual(b'bug', b'ant') 1122 self.assertGreaterEqual(b'ant', b'ant') 1123 self.assertLess(b'ant', b'bug') 1124 self.assertLessEqual(b'ant', b'bug') 1125 self.assertLessEqual(b'ant', b'ant') 1126 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug') 1127 self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant') 1128 self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant', 1129 b'bug') 1130 self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant') 1131 self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant') 1132 self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant') 1133 1134 def testAssertMultiLineEqual(self): 1135 sample_text = """\ 1136http://www.python.org/doc/2.3/lib/module-unittest.html 1137test case 1138 A test case is the smallest unit of testing. [...] 1139""" 1140 revised_sample_text = """\ 1141http://www.python.org/doc/2.4.1/lib/module-unittest.html 1142test case 1143 A test case is the smallest unit of testing. [...] You may provide your 1144 own implementation that does not subclass from TestCase, of course. 1145""" 1146 sample_text_error = """\ 1147- http://www.python.org/doc/2.3/lib/module-unittest.html 1148? ^ 1149+ http://www.python.org/doc/2.4.1/lib/module-unittest.html 1150? ^^^ 1151 test case 1152- A test case is the smallest unit of testing. [...] 1153+ A test case is the smallest unit of testing. [...] You may provide your 1154? +++++++++++++++++++++ 1155+ own implementation that does not subclass from TestCase, of course. 1156""" 1157 self.maxDiff = None 1158 try: 1159 self.assertMultiLineEqual(sample_text, revised_sample_text) 1160 except self.failureException as e: 1161 # need to remove the first line of the error message 1162 error = str(e).split('\n', 1)[1] 1163 self.assertEqual(sample_text_error, error) 1164 1165 def testAssertEqualSingleLine(self): 1166 sample_text = "laden swallows fly slowly" 1167 revised_sample_text = "unladen swallows fly quickly" 1168 sample_text_error = """\ 1169- laden swallows fly slowly 1170? ^^^^ 1171+ unladen swallows fly quickly 1172? ++ ^^^^^ 1173""" 1174 try: 1175 self.assertEqual(sample_text, revised_sample_text) 1176 except self.failureException as e: 1177 # need to remove the first line of the error message 1178 error = str(e).split('\n', 1)[1] 1179 self.assertEqual(sample_text_error, error) 1180 1181 def testEqualityBytesWarning(self): 1182 if sys.flags.bytes_warning: 1183 def bytes_warning(): 1184 return self.assertWarnsRegex(BytesWarning, 1185 'Comparison between bytes and string') 1186 else: 1187 def bytes_warning(): 1188 return contextlib.ExitStack() 1189 1190 with bytes_warning(), self.assertRaises(self.failureException): 1191 self.assertEqual('a', b'a') 1192 with bytes_warning(): 1193 self.assertNotEqual('a', b'a') 1194 1195 a = [0, 'a'] 1196 b = [0, b'a'] 1197 with bytes_warning(), self.assertRaises(self.failureException): 1198 self.assertListEqual(a, b) 1199 with bytes_warning(), self.assertRaises(self.failureException): 1200 self.assertTupleEqual(tuple(a), tuple(b)) 1201 with bytes_warning(), self.assertRaises(self.failureException): 1202 self.assertSequenceEqual(a, tuple(b)) 1203 with bytes_warning(), self.assertRaises(self.failureException): 1204 self.assertSequenceEqual(tuple(a), b) 1205 with bytes_warning(), self.assertRaises(self.failureException): 1206 self.assertSequenceEqual('a', b'a') 1207 with bytes_warning(), self.assertRaises(self.failureException): 1208 self.assertSetEqual(set(a), set(b)) 1209 1210 with self.assertRaises(self.failureException): 1211 self.assertListEqual(a, tuple(b)) 1212 with self.assertRaises(self.failureException): 1213 self.assertTupleEqual(tuple(a), b) 1214 1215 a = [0, b'a'] 1216 b = [0] 1217 with self.assertRaises(self.failureException): 1218 self.assertListEqual(a, b) 1219 with self.assertRaises(self.failureException): 1220 self.assertTupleEqual(tuple(a), tuple(b)) 1221 with self.assertRaises(self.failureException): 1222 self.assertSequenceEqual(a, tuple(b)) 1223 with self.assertRaises(self.failureException): 1224 self.assertSequenceEqual(tuple(a), b) 1225 with self.assertRaises(self.failureException): 1226 self.assertSetEqual(set(a), set(b)) 1227 1228 a = [0] 1229 b = [0, b'a'] 1230 with self.assertRaises(self.failureException): 1231 self.assertListEqual(a, b) 1232 with self.assertRaises(self.failureException): 1233 self.assertTupleEqual(tuple(a), tuple(b)) 1234 with self.assertRaises(self.failureException): 1235 self.assertSequenceEqual(a, tuple(b)) 1236 with self.assertRaises(self.failureException): 1237 self.assertSequenceEqual(tuple(a), b) 1238 with self.assertRaises(self.failureException): 1239 self.assertSetEqual(set(a), set(b)) 1240 1241 with bytes_warning(), self.assertRaises(self.failureException): 1242 self.assertDictEqual({'a': 0}, {b'a': 0}) 1243 with self.assertRaises(self.failureException): 1244 self.assertDictEqual({}, {b'a': 0}) 1245 with self.assertRaises(self.failureException): 1246 self.assertDictEqual({b'a': 0}, {}) 1247 1248 with self.assertRaises(self.failureException): 1249 self.assertCountEqual([b'a', b'a'], [b'a', b'a', b'a']) 1250 with bytes_warning(): 1251 self.assertCountEqual(['a', b'a'], ['a', b'a']) 1252 with bytes_warning(), self.assertRaises(self.failureException): 1253 self.assertCountEqual(['a', 'a'], [b'a', b'a']) 1254 with bytes_warning(), self.assertRaises(self.failureException): 1255 self.assertCountEqual(['a', 'a', []], [b'a', b'a', []]) 1256 1257 def testAssertIsNone(self): 1258 self.assertIsNone(None) 1259 self.assertRaises(self.failureException, self.assertIsNone, False) 1260 self.assertIsNotNone('DjZoPloGears on Rails') 1261 self.assertRaises(self.failureException, self.assertIsNotNone, None) 1262 1263 def testAssertRegex(self): 1264 self.assertRegex('asdfabasdf', r'ab+') 1265 self.assertRaises(self.failureException, self.assertRegex, 1266 'saaas', r'aaaa') 1267 1268 def testAssertRaisesCallable(self): 1269 class ExceptionMock(Exception): 1270 pass 1271 def Stub(): 1272 raise ExceptionMock('We expect') 1273 self.assertRaises(ExceptionMock, Stub) 1274 # A tuple of exception classes is accepted 1275 self.assertRaises((ValueError, ExceptionMock), Stub) 1276 # *args and **kwargs also work 1277 self.assertRaises(ValueError, int, '19', base=8) 1278 # Failure when no exception is raised 1279 with self.assertRaises(self.failureException): 1280 self.assertRaises(ExceptionMock, lambda: 0) 1281 # Failure when the function is None 1282 with self.assertRaises(TypeError): 1283 self.assertRaises(ExceptionMock, None) 1284 # Failure when another exception is raised 1285 with self.assertRaises(ExceptionMock): 1286 self.assertRaises(ValueError, Stub) 1287 1288 def testAssertRaisesContext(self): 1289 class ExceptionMock(Exception): 1290 pass 1291 def Stub(): 1292 raise ExceptionMock('We expect') 1293 with self.assertRaises(ExceptionMock): 1294 Stub() 1295 # A tuple of exception classes is accepted 1296 with self.assertRaises((ValueError, ExceptionMock)) as cm: 1297 Stub() 1298 # The context manager exposes caught exception 1299 self.assertIsInstance(cm.exception, ExceptionMock) 1300 self.assertEqual(cm.exception.args[0], 'We expect') 1301 # *args and **kwargs also work 1302 with self.assertRaises(ValueError): 1303 int('19', base=8) 1304 # Failure when no exception is raised 1305 with self.assertRaises(self.failureException): 1306 with self.assertRaises(ExceptionMock): 1307 pass 1308 # Custom message 1309 with self.assertRaisesRegex(self.failureException, 'foobar'): 1310 with self.assertRaises(ExceptionMock, msg='foobar'): 1311 pass 1312 # Invalid keyword argument 1313 with self.assertRaisesRegex(TypeError, 'foobar'): 1314 with self.assertRaises(ExceptionMock, foobar=42): 1315 pass 1316 # Failure when another exception is raised 1317 with self.assertRaises(ExceptionMock): 1318 self.assertRaises(ValueError, Stub) 1319 1320 def testAssertRaisesNoExceptionType(self): 1321 with self.assertRaises(TypeError): 1322 self.assertRaises() 1323 with self.assertRaises(TypeError): 1324 self.assertRaises(1) 1325 with self.assertRaises(TypeError): 1326 self.assertRaises(object) 1327 with self.assertRaises(TypeError): 1328 self.assertRaises((ValueError, 1)) 1329 with self.assertRaises(TypeError): 1330 self.assertRaises((ValueError, object)) 1331 1332 def testAssertRaisesRefcount(self): 1333 # bpo-23890: assertRaises() must not keep objects alive longer 1334 # than expected 1335 def func() : 1336 try: 1337 raise ValueError 1338 except ValueError: 1339 raise ValueError 1340 1341 refcount = sys.getrefcount(func) 1342 self.assertRaises(ValueError, func) 1343 self.assertEqual(refcount, sys.getrefcount(func)) 1344 1345 def testAssertRaisesRegex(self): 1346 class ExceptionMock(Exception): 1347 pass 1348 1349 def Stub(): 1350 raise ExceptionMock('We expect') 1351 1352 self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub) 1353 self.assertRaisesRegex(ExceptionMock, 'expect$', Stub) 1354 with self.assertRaises(TypeError): 1355 self.assertRaisesRegex(ExceptionMock, 'expect$', None) 1356 1357 def testAssertNotRaisesRegex(self): 1358 self.assertRaisesRegex( 1359 self.failureException, '^Exception not raised by <lambda>$', 1360 self.assertRaisesRegex, Exception, re.compile('x'), 1361 lambda: None) 1362 self.assertRaisesRegex( 1363 self.failureException, '^Exception not raised by <lambda>$', 1364 self.assertRaisesRegex, Exception, 'x', 1365 lambda: None) 1366 # Custom message 1367 with self.assertRaisesRegex(self.failureException, 'foobar'): 1368 with self.assertRaisesRegex(Exception, 'expect', msg='foobar'): 1369 pass 1370 # Invalid keyword argument 1371 with self.assertRaisesRegex(TypeError, 'foobar'): 1372 with self.assertRaisesRegex(Exception, 'expect', foobar=42): 1373 pass 1374 1375 def testAssertRaisesRegexInvalidRegex(self): 1376 # Issue 20145. 1377 class MyExc(Exception): 1378 pass 1379 self.assertRaises(TypeError, self.assertRaisesRegex, MyExc, lambda: True) 1380 1381 def testAssertWarnsRegexInvalidRegex(self): 1382 # Issue 20145. 1383 class MyWarn(Warning): 1384 pass 1385 self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True) 1386 1387 def testAssertWarnsModifySysModules(self): 1388 # bpo-29620: handle modified sys.modules during iteration 1389 class Foo(types.ModuleType): 1390 @property 1391 def __warningregistry__(self): 1392 sys.modules['@bar@'] = 'bar' 1393 1394 sys.modules['@foo@'] = Foo('foo') 1395 try: 1396 self.assertWarns(UserWarning, warnings.warn, 'expected') 1397 finally: 1398 del sys.modules['@foo@'] 1399 del sys.modules['@bar@'] 1400 1401 def testAssertRaisesRegexMismatch(self): 1402 def Stub(): 1403 raise Exception('Unexpected') 1404 1405 self.assertRaisesRegex( 1406 self.failureException, 1407 r'"\^Expected\$" does not match "Unexpected"', 1408 self.assertRaisesRegex, Exception, '^Expected$', 1409 Stub) 1410 self.assertRaisesRegex( 1411 self.failureException, 1412 r'"\^Expected\$" does not match "Unexpected"', 1413 self.assertRaisesRegex, Exception, 1414 re.compile('^Expected$'), Stub) 1415 1416 def testAssertRaisesExcValue(self): 1417 class ExceptionMock(Exception): 1418 pass 1419 1420 def Stub(foo): 1421 raise ExceptionMock(foo) 1422 v = "particular value" 1423 1424 ctx = self.assertRaises(ExceptionMock) 1425 with ctx: 1426 Stub(v) 1427 e = ctx.exception 1428 self.assertIsInstance(e, ExceptionMock) 1429 self.assertEqual(e.args[0], v) 1430 1431 def testAssertRaisesRegexNoExceptionType(self): 1432 with self.assertRaises(TypeError): 1433 self.assertRaisesRegex() 1434 with self.assertRaises(TypeError): 1435 self.assertRaisesRegex(ValueError) 1436 with self.assertRaises(TypeError): 1437 self.assertRaisesRegex(1, 'expect') 1438 with self.assertRaises(TypeError): 1439 self.assertRaisesRegex(object, 'expect') 1440 with self.assertRaises(TypeError): 1441 self.assertRaisesRegex((ValueError, 1), 'expect') 1442 with self.assertRaises(TypeError): 1443 self.assertRaisesRegex((ValueError, object), 'expect') 1444 1445 def testAssertWarnsCallable(self): 1446 def _runtime_warn(): 1447 warnings.warn("foo", RuntimeWarning) 1448 # Success when the right warning is triggered, even several times 1449 self.assertWarns(RuntimeWarning, _runtime_warn) 1450 self.assertWarns(RuntimeWarning, _runtime_warn) 1451 # A tuple of warning classes is accepted 1452 self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn) 1453 # *args and **kwargs also work 1454 self.assertWarns(RuntimeWarning, 1455 warnings.warn, "foo", category=RuntimeWarning) 1456 # Failure when no warning is triggered 1457 with self.assertRaises(self.failureException): 1458 self.assertWarns(RuntimeWarning, lambda: 0) 1459 # Failure when the function is None 1460 with self.assertRaises(TypeError): 1461 self.assertWarns(RuntimeWarning, None) 1462 # Failure when another warning is triggered 1463 with warnings.catch_warnings(): 1464 # Force default filter (in case tests are run with -We) 1465 warnings.simplefilter("default", RuntimeWarning) 1466 with self.assertRaises(self.failureException): 1467 self.assertWarns(DeprecationWarning, _runtime_warn) 1468 # Filters for other warnings are not modified 1469 with warnings.catch_warnings(): 1470 warnings.simplefilter("error", RuntimeWarning) 1471 with self.assertRaises(RuntimeWarning): 1472 self.assertWarns(DeprecationWarning, _runtime_warn) 1473 1474 def testAssertWarnsContext(self): 1475 # Believe it or not, it is preferable to duplicate all tests above, 1476 # to make sure the __warningregistry__ $@ is circumvented correctly. 1477 def _runtime_warn(): 1478 warnings.warn("foo", RuntimeWarning) 1479 _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] 1480 with self.assertWarns(RuntimeWarning) as cm: 1481 _runtime_warn() 1482 # A tuple of warning classes is accepted 1483 with self.assertWarns((DeprecationWarning, RuntimeWarning)) as cm: 1484 _runtime_warn() 1485 # The context manager exposes various useful attributes 1486 self.assertIsInstance(cm.warning, RuntimeWarning) 1487 self.assertEqual(cm.warning.args[0], "foo") 1488 self.assertIn("test_case.py", cm.filename) 1489 self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) 1490 # Same with several warnings 1491 with self.assertWarns(RuntimeWarning): 1492 _runtime_warn() 1493 _runtime_warn() 1494 with self.assertWarns(RuntimeWarning): 1495 warnings.warn("foo", category=RuntimeWarning) 1496 # Failure when no warning is triggered 1497 with self.assertRaises(self.failureException): 1498 with self.assertWarns(RuntimeWarning): 1499 pass 1500 # Custom message 1501 with self.assertRaisesRegex(self.failureException, 'foobar'): 1502 with self.assertWarns(RuntimeWarning, msg='foobar'): 1503 pass 1504 # Invalid keyword argument 1505 with self.assertRaisesRegex(TypeError, 'foobar'): 1506 with self.assertWarns(RuntimeWarning, foobar=42): 1507 pass 1508 # Failure when another warning is triggered 1509 with warnings.catch_warnings(): 1510 # Force default filter (in case tests are run with -We) 1511 warnings.simplefilter("default", RuntimeWarning) 1512 with self.assertRaises(self.failureException): 1513 with self.assertWarns(DeprecationWarning): 1514 _runtime_warn() 1515 # Filters for other warnings are not modified 1516 with warnings.catch_warnings(): 1517 warnings.simplefilter("error", RuntimeWarning) 1518 with self.assertRaises(RuntimeWarning): 1519 with self.assertWarns(DeprecationWarning): 1520 _runtime_warn() 1521 1522 def testAssertWarnsNoExceptionType(self): 1523 with self.assertRaises(TypeError): 1524 self.assertWarns() 1525 with self.assertRaises(TypeError): 1526 self.assertWarns(1) 1527 with self.assertRaises(TypeError): 1528 self.assertWarns(object) 1529 with self.assertRaises(TypeError): 1530 self.assertWarns((UserWarning, 1)) 1531 with self.assertRaises(TypeError): 1532 self.assertWarns((UserWarning, object)) 1533 with self.assertRaises(TypeError): 1534 self.assertWarns((UserWarning, Exception)) 1535 1536 def testAssertWarnsRegexCallable(self): 1537 def _runtime_warn(msg): 1538 warnings.warn(msg, RuntimeWarning) 1539 self.assertWarnsRegex(RuntimeWarning, "o+", 1540 _runtime_warn, "foox") 1541 # Failure when no warning is triggered 1542 with self.assertRaises(self.failureException): 1543 self.assertWarnsRegex(RuntimeWarning, "o+", 1544 lambda: 0) 1545 # Failure when the function is None 1546 with self.assertRaises(TypeError): 1547 self.assertWarnsRegex(RuntimeWarning, "o+", None) 1548 # Failure when another warning is triggered 1549 with warnings.catch_warnings(): 1550 # Force default filter (in case tests are run with -We) 1551 warnings.simplefilter("default", RuntimeWarning) 1552 with self.assertRaises(self.failureException): 1553 self.assertWarnsRegex(DeprecationWarning, "o+", 1554 _runtime_warn, "foox") 1555 # Failure when message doesn't match 1556 with self.assertRaises(self.failureException): 1557 self.assertWarnsRegex(RuntimeWarning, "o+", 1558 _runtime_warn, "barz") 1559 # A little trickier: we ask RuntimeWarnings to be raised, and then 1560 # check for some of them. It is implementation-defined whether 1561 # non-matching RuntimeWarnings are simply re-raised, or produce a 1562 # failureException. 1563 with warnings.catch_warnings(): 1564 warnings.simplefilter("error", RuntimeWarning) 1565 with self.assertRaises((RuntimeWarning, self.failureException)): 1566 self.assertWarnsRegex(RuntimeWarning, "o+", 1567 _runtime_warn, "barz") 1568 1569 def testAssertWarnsRegexContext(self): 1570 # Same as above, but with assertWarnsRegex as a context manager 1571 def _runtime_warn(msg): 1572 warnings.warn(msg, RuntimeWarning) 1573 _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] 1574 with self.assertWarnsRegex(RuntimeWarning, "o+") as cm: 1575 _runtime_warn("foox") 1576 self.assertIsInstance(cm.warning, RuntimeWarning) 1577 self.assertEqual(cm.warning.args[0], "foox") 1578 self.assertIn("test_case.py", cm.filename) 1579 self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) 1580 # Failure when no warning is triggered 1581 with self.assertRaises(self.failureException): 1582 with self.assertWarnsRegex(RuntimeWarning, "o+"): 1583 pass 1584 # Custom message 1585 with self.assertRaisesRegex(self.failureException, 'foobar'): 1586 with self.assertWarnsRegex(RuntimeWarning, 'o+', msg='foobar'): 1587 pass 1588 # Invalid keyword argument 1589 with self.assertRaisesRegex(TypeError, 'foobar'): 1590 with self.assertWarnsRegex(RuntimeWarning, 'o+', foobar=42): 1591 pass 1592 # Failure when another warning is triggered 1593 with warnings.catch_warnings(): 1594 # Force default filter (in case tests are run with -We) 1595 warnings.simplefilter("default", RuntimeWarning) 1596 with self.assertRaises(self.failureException): 1597 with self.assertWarnsRegex(DeprecationWarning, "o+"): 1598 _runtime_warn("foox") 1599 # Failure when message doesn't match 1600 with self.assertRaises(self.failureException): 1601 with self.assertWarnsRegex(RuntimeWarning, "o+"): 1602 _runtime_warn("barz") 1603 # A little trickier: we ask RuntimeWarnings to be raised, and then 1604 # check for some of them. It is implementation-defined whether 1605 # non-matching RuntimeWarnings are simply re-raised, or produce a 1606 # failureException. 1607 with warnings.catch_warnings(): 1608 warnings.simplefilter("error", RuntimeWarning) 1609 with self.assertRaises((RuntimeWarning, self.failureException)): 1610 with self.assertWarnsRegex(RuntimeWarning, "o+"): 1611 _runtime_warn("barz") 1612 1613 def testAssertWarnsRegexNoExceptionType(self): 1614 with self.assertRaises(TypeError): 1615 self.assertWarnsRegex() 1616 with self.assertRaises(TypeError): 1617 self.assertWarnsRegex(UserWarning) 1618 with self.assertRaises(TypeError): 1619 self.assertWarnsRegex(1, 'expect') 1620 with self.assertRaises(TypeError): 1621 self.assertWarnsRegex(object, 'expect') 1622 with self.assertRaises(TypeError): 1623 self.assertWarnsRegex((UserWarning, 1), 'expect') 1624 with self.assertRaises(TypeError): 1625 self.assertWarnsRegex((UserWarning, object), 'expect') 1626 with self.assertRaises(TypeError): 1627 self.assertWarnsRegex((UserWarning, Exception), 'expect') 1628 1629 @contextlib.contextmanager 1630 def assertNoStderr(self): 1631 with captured_stderr() as buf: 1632 yield 1633 self.assertEqual(buf.getvalue(), "") 1634 1635 def assertLogRecords(self, records, matches): 1636 self.assertEqual(len(records), len(matches)) 1637 for rec, match in zip(records, matches): 1638 self.assertIsInstance(rec, logging.LogRecord) 1639 for k, v in match.items(): 1640 self.assertEqual(getattr(rec, k), v) 1641 1642 def testAssertLogsDefaults(self): 1643 # defaults: root logger, level INFO 1644 with self.assertNoStderr(): 1645 with self.assertLogs() as cm: 1646 log_foo.info("1") 1647 log_foobar.debug("2") 1648 self.assertEqual(cm.output, ["INFO:foo:1"]) 1649 self.assertLogRecords(cm.records, [{'name': 'foo'}]) 1650 1651 def testAssertLogsTwoMatchingMessages(self): 1652 # Same, but with two matching log messages 1653 with self.assertNoStderr(): 1654 with self.assertLogs() as cm: 1655 log_foo.info("1") 1656 log_foobar.debug("2") 1657 log_quux.warning("3") 1658 self.assertEqual(cm.output, ["INFO:foo:1", "WARNING:quux:3"]) 1659 self.assertLogRecords(cm.records, 1660 [{'name': 'foo'}, {'name': 'quux'}]) 1661 1662 def checkAssertLogsPerLevel(self, level): 1663 # Check level filtering 1664 with self.assertNoStderr(): 1665 with self.assertLogs(level=level) as cm: 1666 log_foo.warning("1") 1667 log_foobar.error("2") 1668 log_quux.critical("3") 1669 self.assertEqual(cm.output, ["ERROR:foo.bar:2", "CRITICAL:quux:3"]) 1670 self.assertLogRecords(cm.records, 1671 [{'name': 'foo.bar'}, {'name': 'quux'}]) 1672 1673 def testAssertLogsPerLevel(self): 1674 self.checkAssertLogsPerLevel(logging.ERROR) 1675 self.checkAssertLogsPerLevel('ERROR') 1676 1677 def checkAssertLogsPerLogger(self, logger): 1678 # Check per-logger filtering 1679 with self.assertNoStderr(): 1680 with self.assertLogs(level='DEBUG') as outer_cm: 1681 with self.assertLogs(logger, level='DEBUG') as cm: 1682 log_foo.info("1") 1683 log_foobar.debug("2") 1684 log_quux.warning("3") 1685 self.assertEqual(cm.output, ["INFO:foo:1", "DEBUG:foo.bar:2"]) 1686 self.assertLogRecords(cm.records, 1687 [{'name': 'foo'}, {'name': 'foo.bar'}]) 1688 # The outer catchall caught the quux log 1689 self.assertEqual(outer_cm.output, ["WARNING:quux:3"]) 1690 1691 def testAssertLogsPerLogger(self): 1692 self.checkAssertLogsPerLogger(logging.getLogger('foo')) 1693 self.checkAssertLogsPerLogger('foo') 1694 1695 def testAssertLogsFailureNoLogs(self): 1696 # Failure due to no logs 1697 with self.assertNoStderr(): 1698 with self.assertRaises(self.failureException): 1699 with self.assertLogs(): 1700 pass 1701 1702 def testAssertLogsFailureLevelTooHigh(self): 1703 # Failure due to level too high 1704 with self.assertNoStderr(): 1705 with self.assertRaises(self.failureException): 1706 with self.assertLogs(level='WARNING'): 1707 log_foo.info("1") 1708 1709 def testAssertLogsFailureLevelTooHigh_FilterInRootLogger(self): 1710 # Failure due to level too high - message propagated to root 1711 with self.assertNoStderr(): 1712 oldLevel = log_foo.level 1713 log_foo.setLevel(logging.INFO) 1714 try: 1715 with self.assertRaises(self.failureException): 1716 with self.assertLogs(level='WARNING'): 1717 log_foo.info("1") 1718 finally: 1719 log_foo.setLevel(oldLevel) 1720 1721 def testAssertLogsFailureMismatchingLogger(self): 1722 # Failure due to mismatching logger (and the logged message is 1723 # passed through) 1724 with self.assertLogs('quux', level='ERROR'): 1725 with self.assertRaises(self.failureException): 1726 with self.assertLogs('foo'): 1727 log_quux.error("1") 1728 1729 def testAssertLogsUnexpectedException(self): 1730 # Check unexpected exception will go through. 1731 with self.assertRaises(ZeroDivisionError): 1732 with self.assertLogs(): 1733 raise ZeroDivisionError("Unexpected") 1734 1735 def testAssertNoLogsDefault(self): 1736 with self.assertRaises(self.failureException) as cm: 1737 with self.assertNoLogs(): 1738 log_foo.info("1") 1739 log_foobar.debug("2") 1740 self.assertEqual( 1741 str(cm.exception), 1742 "Unexpected logs found: ['INFO:foo:1']", 1743 ) 1744 1745 def testAssertNoLogsFailureFoundLogs(self): 1746 with self.assertRaises(self.failureException) as cm: 1747 with self.assertNoLogs(): 1748 log_quux.error("1") 1749 log_foo.error("foo") 1750 1751 self.assertEqual( 1752 str(cm.exception), 1753 "Unexpected logs found: ['ERROR:quux:1', 'ERROR:foo:foo']", 1754 ) 1755 1756 def testAssertNoLogsPerLogger(self): 1757 with self.assertNoStderr(): 1758 with self.assertLogs(log_quux): 1759 with self.assertNoLogs(logger=log_foo): 1760 log_quux.error("1") 1761 1762 def testAssertNoLogsFailurePerLogger(self): 1763 # Failure due to unexpected logs for the given logger or its 1764 # children. 1765 with self.assertRaises(self.failureException) as cm: 1766 with self.assertLogs(log_quux): 1767 with self.assertNoLogs(logger=log_foo): 1768 log_quux.error("1") 1769 log_foobar.info("2") 1770 self.assertEqual( 1771 str(cm.exception), 1772 "Unexpected logs found: ['INFO:foo.bar:2']", 1773 ) 1774 1775 def testAssertNoLogsPerLevel(self): 1776 # Check per-level filtering 1777 with self.assertNoStderr(): 1778 with self.assertNoLogs(level="ERROR"): 1779 log_foo.info("foo") 1780 log_quux.debug("1") 1781 1782 def testAssertNoLogsFailurePerLevel(self): 1783 # Failure due to unexpected logs at the specified level. 1784 with self.assertRaises(self.failureException) as cm: 1785 with self.assertNoLogs(level="DEBUG"): 1786 log_foo.debug("foo") 1787 log_quux.debug("1") 1788 self.assertEqual( 1789 str(cm.exception), 1790 "Unexpected logs found: ['DEBUG:foo:foo', 'DEBUG:quux:1']", 1791 ) 1792 1793 def testAssertNoLogsUnexpectedException(self): 1794 # Check unexpected exception will go through. 1795 with self.assertRaises(ZeroDivisionError): 1796 with self.assertNoLogs(): 1797 raise ZeroDivisionError("Unexpected") 1798 1799 def testAssertNoLogsYieldsNone(self): 1800 with self.assertNoLogs() as value: 1801 pass 1802 self.assertIsNone(value) 1803 1804 def testDeprecatedMethodNames(self): 1805 """ 1806 Test that the deprecated methods raise a DeprecationWarning. See #9424. 1807 """ 1808 old = ( 1809 (self.failIfEqual, (3, 5)), 1810 (self.assertNotEquals, (3, 5)), 1811 (self.failUnlessEqual, (3, 3)), 1812 (self.assertEquals, (3, 3)), 1813 (self.failUnlessAlmostEqual, (2.0, 2.0)), 1814 (self.assertAlmostEquals, (2.0, 2.0)), 1815 (self.failIfAlmostEqual, (3.0, 5.0)), 1816 (self.assertNotAlmostEquals, (3.0, 5.0)), 1817 (self.failUnless, (True,)), 1818 (self.assert_, (True,)), 1819 (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')), 1820 (self.failIf, (False,)), 1821 (self.assertDictContainsSubset, (dict(a=1, b=2), dict(a=1, b=2, c=3))), 1822 (self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])), 1823 (self.assertRegexpMatches, ('bar', 'bar')), 1824 ) 1825 for meth, args in old: 1826 with self.assertWarns(DeprecationWarning): 1827 meth(*args) 1828 1829 # disable this test for now. When the version where the fail* methods will 1830 # be removed is decided, re-enable it and update the version 1831 def _testDeprecatedFailMethods(self): 1832 """Test that the deprecated fail* methods get removed in 3.x""" 1833 if sys.version_info[:2] < (3, 3): 1834 return 1835 deprecated_names = [ 1836 'failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual', 1837 'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf', 1838 'assertDictContainsSubset', 1839 ] 1840 for deprecated_name in deprecated_names: 1841 with self.assertRaises(AttributeError): 1842 getattr(self, deprecated_name) # remove these in 3.x 1843 1844 def testDeepcopy(self): 1845 # Issue: 5660 1846 class TestableTest(unittest.TestCase): 1847 def testNothing(self): 1848 pass 1849 1850 test = TestableTest('testNothing') 1851 1852 # This shouldn't blow up 1853 deepcopy(test) 1854 1855 def testPickle(self): 1856 # Issue 10326 1857 1858 # Can't use TestCase classes defined in Test class as 1859 # pickle does not work with inner classes 1860 test = unittest.TestCase('run') 1861 for protocol in range(pickle.HIGHEST_PROTOCOL + 1): 1862 1863 # blew up prior to fix 1864 pickled_test = pickle.dumps(test, protocol=protocol) 1865 unpickled_test = pickle.loads(pickled_test) 1866 self.assertEqual(test, unpickled_test) 1867 1868 # exercise the TestCase instance in a way that will invoke 1869 # the type equality lookup mechanism 1870 unpickled_test.assertEqual(set(), set()) 1871 1872 def testKeyboardInterrupt(self): 1873 def _raise(self=None): 1874 raise KeyboardInterrupt 1875 def nothing(self): 1876 pass 1877 1878 class Test1(unittest.TestCase): 1879 test_something = _raise 1880 1881 class Test2(unittest.TestCase): 1882 setUp = _raise 1883 test_something = nothing 1884 1885 class Test3(unittest.TestCase): 1886 test_something = nothing 1887 tearDown = _raise 1888 1889 class Test4(unittest.TestCase): 1890 def test_something(self): 1891 self.addCleanup(_raise) 1892 1893 for klass in (Test1, Test2, Test3, Test4): 1894 with self.assertRaises(KeyboardInterrupt): 1895 klass('test_something').run() 1896 1897 def testSkippingEverywhere(self): 1898 def _skip(self=None): 1899 raise unittest.SkipTest('some reason') 1900 def nothing(self): 1901 pass 1902 1903 class Test1(unittest.TestCase): 1904 test_something = _skip 1905 1906 class Test2(unittest.TestCase): 1907 setUp = _skip 1908 test_something = nothing 1909 1910 class Test3(unittest.TestCase): 1911 test_something = nothing 1912 tearDown = _skip 1913 1914 class Test4(unittest.TestCase): 1915 def test_something(self): 1916 self.addCleanup(_skip) 1917 1918 for klass in (Test1, Test2, Test3, Test4): 1919 result = unittest.TestResult() 1920 klass('test_something').run(result) 1921 self.assertEqual(len(result.skipped), 1) 1922 self.assertEqual(result.testsRun, 1) 1923 1924 def testSystemExit(self): 1925 def _raise(self=None): 1926 raise SystemExit 1927 def nothing(self): 1928 pass 1929 1930 class Test1(unittest.TestCase): 1931 test_something = _raise 1932 1933 class Test2(unittest.TestCase): 1934 setUp = _raise 1935 test_something = nothing 1936 1937 class Test3(unittest.TestCase): 1938 test_something = nothing 1939 tearDown = _raise 1940 1941 class Test4(unittest.TestCase): 1942 def test_something(self): 1943 self.addCleanup(_raise) 1944 1945 for klass in (Test1, Test2, Test3, Test4): 1946 result = unittest.TestResult() 1947 klass('test_something').run(result) 1948 self.assertEqual(len(result.errors), 1) 1949 self.assertEqual(result.testsRun, 1) 1950 1951 @support.cpython_only 1952 def testNoCycles(self): 1953 case = unittest.TestCase() 1954 wr = weakref.ref(case) 1955 with support.disable_gc(): 1956 del case 1957 self.assertFalse(wr()) 1958 1959 def test_no_exception_leak(self): 1960 # Issue #19880: TestCase.run() should not keep a reference 1961 # to the exception 1962 class MyException(Exception): 1963 ninstance = 0 1964 1965 def __init__(self): 1966 MyException.ninstance += 1 1967 Exception.__init__(self) 1968 1969 def __del__(self): 1970 MyException.ninstance -= 1 1971 1972 class TestCase(unittest.TestCase): 1973 def test1(self): 1974 raise MyException() 1975 1976 @unittest.expectedFailure 1977 def test2(self): 1978 raise MyException() 1979 1980 for method_name in ('test1', 'test2'): 1981 testcase = TestCase(method_name) 1982 testcase.run() 1983 gc_collect() # For PyPy or other GCs. 1984 self.assertEqual(MyException.ninstance, 0) 1985 1986 1987if __name__ == "__main__": 1988 unittest.main() 1989