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