Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(33287)

Delta Between Two Patch Sets: Lib/unittest/test/test_case.py

Issue 15836: unittest assertRaises should verify excClass is actually a BaseException class
Left Patch Set: Created 7 years ago
Right Patch Set: Created 4 years, 4 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
LEFTRIGHT
1 import contextlib
1 import difflib 2 import difflib
2 import pprint 3 import pprint
3 import pickle 4 import pickle
4 import re 5 import re
5 import sys 6 import sys
7 import logging
6 import warnings 8 import warnings
7 import weakref 9 import weakref
8 import inspect 10 import inspect
9 11
10 from copy import deepcopy 12 from copy import deepcopy
11 from test import support 13 from test import support
12 14
13 import unittest 15 import unittest
14 16
15 from .support import ( 17 from unittest.test.support import (
16 TestEquality, TestHashing, LoggingResult, 18 TestEquality, TestHashing, LoggingResult, LegacyLoggingResult,
17 ResultWithNoStartTestRunStopTestRun 19 ResultWithNoStartTestRunStopTestRun
18 ) 20 )
21 from test.support import captured_stderr
22
23
24 log_foo = logging.getLogger('foo')
25 log_foobar = logging.getLogger('foo.bar')
26 log_quux = logging.getLogger('quux')
19 27
20 28
21 class Test(object): 29 class Test(object):
22 "Keep these TestCase classes out of the main namespace" 30 "Keep these TestCase classes out of the main namespace"
23 31
24 class Foo(unittest.TestCase): 32 class Foo(unittest.TestCase):
25 def runTest(self): pass 33 def runTest(self): pass
26 def test1(self): pass 34 def test1(self): pass
27 35
28 class Bar(Foo): 36 class Bar(Foo):
(...skipping 261 matching lines...) Expand 10 before | Expand all | Expand 10 after
290 def test_run_call_order_default_result(self): 298 def test_run_call_order_default_result(self):
291 299
292 class Foo(unittest.TestCase): 300 class Foo(unittest.TestCase):
293 def defaultTestResult(self): 301 def defaultTestResult(self):
294 return ResultWithNoStartTestRunStopTestRun() 302 return ResultWithNoStartTestRunStopTestRun()
295 def test(self): 303 def test(self):
296 pass 304 pass
297 305
298 Foo('test').run() 306 Foo('test').run()
299 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 a 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_event s):
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
300 # "This class attribute gives the exception raised by the test() method. 428 # "This class attribute gives the exception raised by the test() method.
301 # If a test framework needs to use a specialized exception, possibly to 429 # If a test framework needs to use a specialized exception, possibly to
302 # carry additional information, it must subclass this exception in 430 # carry additional information, it must subclass this exception in
303 # order to ``play fair'' with the framework. The initial value of this 431 # order to ``play fair'' with the framework. The initial value of this
304 # attribute is AssertionError" 432 # attribute is AssertionError"
305 def test_failureException__default(self): 433 def test_failureException__default(self):
306 class Foo(unittest.TestCase): 434 class Foo(unittest.TestCase):
307 def test(self): 435 def test(self):
308 pass 436 pass
309 437
310 self.assertTrue(Foo('test').failureException is AssertionError) 438 self.assertIs(Foo('test').failureException, AssertionError)
311 439
312 # "This class attribute gives the exception raised by the test() method. 440 # "This class attribute gives the exception raised by the test() method.
313 # If a test framework needs to use a specialized exception, possibly to 441 # If a test framework needs to use a specialized exception, possibly to
314 # carry additional information, it must subclass this exception in 442 # carry additional information, it must subclass this exception in
315 # order to ``play fair'' with the framework." 443 # order to ``play fair'' with the framework."
316 # 444 #
317 # Make sure TestCase.run() respects the designated failureException 445 # Make sure TestCase.run() respects the designated failureException
318 def test_failureException__subclassing__explicit_raise(self): 446 def test_failureException__subclassing__explicit_raise(self):
319 events = [] 447 events = []
320 result = LoggingResult(events) 448 result = LoggingResult(events)
321 449
322 class Foo(unittest.TestCase): 450 class Foo(unittest.TestCase):
323 def test(self): 451 def test(self):
324 raise RuntimeError() 452 raise RuntimeError()
325 453
326 failureException = RuntimeError 454 failureException = RuntimeError
327 455
328 self.assertTrue(Foo('test').failureException is RuntimeError) 456 self.assertIs(Foo('test').failureException, RuntimeError)
329 457
330 458
331 Foo('test').run(result) 459 Foo('test').run(result)
332 expected = ['startTest', 'addFailure', 'stopTest'] 460 expected = ['startTest', 'addFailure', 'stopTest']
333 self.assertEqual(events, expected) 461 self.assertEqual(events, expected)
334 462
335 # "This class attribute gives the exception raised by the test() method. 463 # "This class attribute gives the exception raised by the test() method.
336 # If a test framework needs to use a specialized exception, possibly to 464 # If a test framework needs to use a specialized exception, possibly to
337 # carry additional information, it must subclass this exception in 465 # carry additional information, it must subclass this exception in
338 # order to ``play fair'' with the framework." 466 # order to ``play fair'' with the framework."
339 # 467 #
340 # Make sure TestCase.run() respects the designated failureException 468 # Make sure TestCase.run() respects the designated failureException
341 def test_failureException__subclassing__implicit_raise(self): 469 def test_failureException__subclassing__implicit_raise(self):
342 events = [] 470 events = []
343 result = LoggingResult(events) 471 result = LoggingResult(events)
344 472
345 class Foo(unittest.TestCase): 473 class Foo(unittest.TestCase):
346 def test(self): 474 def test(self):
347 self.fail("foo") 475 self.fail("foo")
348 476
349 failureException = RuntimeError 477 failureException = RuntimeError
350 478
351 self.assertTrue(Foo('test').failureException is RuntimeError) 479 self.assertIs(Foo('test').failureException, RuntimeError)
352 480
353 481
354 Foo('test').run(result) 482 Foo('test').run(result)
355 expected = ['startTest', 'addFailure', 'stopTest'] 483 expected = ['startTest', 'addFailure', 'stopTest']
356 self.assertEqual(events, expected) 484 self.assertEqual(events, expected)
357 485
358 # "The default implementation does nothing." 486 # "The default implementation does nothing."
359 def test_setUp(self): 487 def test_setUp(self):
360 class Foo(unittest.TestCase): 488 class Foo(unittest.TestCase):
361 def runTest(self): 489 def runTest(self):
(...skipping 291 matching lines...) Expand 10 before | Expand all | Expand 10 after
653 omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,) 781 omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,)
654 782
655 self.maxDiff = len(diff)//2 783 self.maxDiff = len(diff)//2
656 try: 784 try:
657 785
658 self.assertSequenceEqual(seq1, seq2) 786 self.assertSequenceEqual(seq1, seq2)
659 except self.failureException as e: 787 except self.failureException as e:
660 msg = e.args[0] 788 msg = e.args[0]
661 else: 789 else:
662 self.fail('assertSequenceEqual did not fail.') 790 self.fail('assertSequenceEqual did not fail.')
663 self.assertTrue(len(msg) < len(diff)) 791 self.assertLess(len(msg), len(diff))
664 self.assertIn(omitted, msg) 792 self.assertIn(omitted, msg)
665 793
666 self.maxDiff = len(diff) * 2 794 self.maxDiff = len(diff) * 2
667 try: 795 try:
668 self.assertSequenceEqual(seq1, seq2) 796 self.assertSequenceEqual(seq1, seq2)
669 except self.failureException as e: 797 except self.failureException as e:
670 msg = e.args[0] 798 msg = e.args[0]
671 else: 799 else:
672 self.fail('assertSequenceEqual did not fail.') 800 self.fail('assertSequenceEqual did not fail.')
673 self.assertTrue(len(msg) > len(diff)) 801 self.assertGreater(len(msg), len(diff))
674 self.assertNotIn(omitted, msg) 802 self.assertNotIn(omitted, msg)
675 803
676 self.maxDiff = None 804 self.maxDiff = None
677 try: 805 try:
678 self.assertSequenceEqual(seq1, seq2) 806 self.assertSequenceEqual(seq1, seq2)
679 except self.failureException as e: 807 except self.failureException as e:
680 msg = e.args[0] 808 msg = e.args[0]
681 else: 809 else:
682 self.fail('assertSequenceEqual did not fail.') 810 self.fail('assertSequenceEqual did not fail.')
683 self.assertTrue(len(msg) > len(diff)) 811 self.assertGreater(len(msg), len(diff))
684 self.assertNotIn(omitted, msg) 812 self.assertNotIn(omitted, msg)
685 813
686 def testTruncateMessage(self): 814 def testTruncateMessage(self):
687 self.maxDiff = 1 815 self.maxDiff = 1
688 message = self._truncateMessage('foo', 'bar') 816 message = self._truncateMessage('foo', 'bar')
689 omitted = unittest.case.DIFF_OMITTED % len('bar') 817 omitted = unittest.case.DIFF_OMITTED % len('bar')
690 self.assertEqual(message, 'foo' + omitted) 818 self.assertEqual(message, 'foo' + omitted)
691 819
692 self.maxDiff = None 820 self.maxDiff = None
693 message = self._truncateMessage('foo', 'bar') 821 message = self._truncateMessage('foo', 'bar')
(...skipping 28 matching lines...) Expand all
722 self.fail('assertMultiLineEqual did not fail') 850 self.fail('assertMultiLineEqual did not fail')
723 851
724 def testAssertEqual_diffThreshold(self): 852 def testAssertEqual_diffThreshold(self):
725 # check threshold value 853 # check threshold value
726 self.assertEqual(self._diffThreshold, 2**16) 854 self.assertEqual(self._diffThreshold, 2**16)
727 # disable madDiff to get diff markers 855 # disable madDiff to get diff markers
728 self.maxDiff = None 856 self.maxDiff = None
729 857
730 # set a lower threshold value and add a cleanup to restore it 858 # set a lower threshold value and add a cleanup to restore it
731 old_threshold = self._diffThreshold 859 old_threshold = self._diffThreshold
732 self._diffThreshold = 2**8 860 self._diffThreshold = 2**5
733 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold)) 861 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold))
734 862
735 # under the threshold: diff marker (^) in error message 863 # under the threshold: diff marker (^) in error message
736 s = 'x' * (2**7) 864 s = 'x' * (2**4)
737 with self.assertRaises(self.failureException) as cm: 865 with self.assertRaises(self.failureException) as cm:
738 self.assertEqual(s + 'a', s + 'b') 866 self.assertEqual(s + 'a', s + 'b')
739 self.assertIn('^', str(cm.exception)) 867 self.assertIn('^', str(cm.exception))
740 self.assertEqual(s + 'a', s + 'a') 868 self.assertEqual(s + 'a', s + 'a')
741 869
742 # over the threshold: diff not used and marker (^) not in error message 870 # over the threshold: diff not used and marker (^) not in error message
743 s = 'x' * (2**9) 871 s = 'x' * (2**6)
744 # if the path that uses difflib is taken, _truncateMessage will be 872 # if the path that uses difflib is taken, _truncateMessage will be
745 # called -- replace it with explodingTruncation to verify that this 873 # called -- replace it with explodingTruncation to verify that this
746 # doesn't happen 874 # doesn't happen
747 def explodingTruncation(message, diff): 875 def explodingTruncation(message, diff):
748 raise SystemError('this should not be raised') 876 raise SystemError('this should not be raised')
749 old_truncate = self._truncateMessage 877 old_truncate = self._truncateMessage
750 self._truncateMessage = explodingTruncation 878 self._truncateMessage = explodingTruncation
751 self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate)) 879 self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate))
752 880
753 s1, s2 = s + 'a', s + 'b' 881 s1, s2 = s + 'a', s + 'b'
754 with self.assertRaises(self.failureException) as cm: 882 with self.assertRaises(self.failureException) as cm:
755 self.assertEqual(s1, s2) 883 self.assertEqual(s1, s2)
756 self.assertNotIn('^', str(cm.exception)) 884 self.assertNotIn('^', str(cm.exception))
757 self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2)) 885 self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2))
758 self.assertEqual(s + 'a', s + 'a') 886 self.assertEqual(s + 'a', s + 'a')
887
888 def testAssertEqual_shorten(self):
889 # set a lower threshold value and add a cleanup to restore it
890 old_threshold = self._diffThreshold
891 self._diffThreshold = 0
892 self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold))
893
894 s = 'x' * 100
895 s1, s2 = s + 'a', s + 'b'
896 with self.assertRaises(self.failureException) as cm:
897 self.assertEqual(s1, s2)
898 c = 'xxxx[35 chars]' + 'x' * 61
899 self.assertEqual(str(cm.exception), "'%sa' != '%sb'" % (c, c))
900 self.assertEqual(s + 'a', s + 'a')
901
902 p = 'y' * 50
903 s1, s2 = s + 'a' + p, s + 'b' + p
904 with self.assertRaises(self.failureException) as cm:
905 self.assertEqual(s1, s2)
906 c = 'xxxx[85 chars]xxxxxxxxxxx'
907 self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, p, c, p))
908
909 p = 'y' * 100
910 s1, s2 = s + 'a' + p, s + 'b' + p
911 with self.assertRaises(self.failureException) as cm:
912 self.assertEqual(s1, s2)
913 c = 'xxxx[91 chars]xxxxx'
914 d = 'y' * 40 + '[56 chars]yyyy'
915 self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, d, c, d))
759 916
760 def testAssertCountEqual(self): 917 def testAssertCountEqual(self):
761 a = object() 918 a = object()
762 self.assertCountEqual([1, 2, 3], [3, 2, 1]) 919 self.assertCountEqual([1, 2, 3], [3, 2, 1])
763 self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo']) 920 self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
764 self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2)) 921 self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
765 self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"]) 922 self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
766 self.assertRaises(self.failureException, self.assertCountEqual, 923 self.assertRaises(self.failureException, self.assertCountEqual,
767 [1, 2] + [3] * 100, [1] * 100 + [2, 3]) 924 [1, 2] + [3] * 100, [1] * 100 + [2, 3])
768 self.assertRaises(self.failureException, self.assertCountEqual, 925 self.assertRaises(self.failureException, self.assertCountEqual,
(...skipping 170 matching lines...) Expand 10 before | Expand all | Expand 10 after
939 + A test case is the smallest unit of testing. [...] You may provide your 1096 + A test case is the smallest unit of testing. [...] You may provide your
940 ? +++++++++++++++++++++ 1097 ? +++++++++++++++++++++
941 + own implementation that does not subclass from TestCase, of course. 1098 + own implementation that does not subclass from TestCase, of course.
942 """ 1099 """
943 self.maxDiff = None 1100 self.maxDiff = None
944 try: 1101 try:
945 self.assertMultiLineEqual(sample_text, revised_sample_text) 1102 self.assertMultiLineEqual(sample_text, revised_sample_text)
946 except self.failureException as e: 1103 except self.failureException as e:
947 # need to remove the first line of the error message 1104 # need to remove the first line of the error message
948 error = str(e).split('\n', 1)[1] 1105 error = str(e).split('\n', 1)[1]
949 1106 self.assertEqual(sample_text_error, error)
950 # no fair testing ourself with ourself, and assertEqual is used for strings 1107
951 # so can't use assertEqual either. Just use assertTrue. 1108 def testAssertEqualSingleLine(self):
952 self.assertTrue(sample_text_error == error)
953
954 def testAsertEqualSingleLine(self):
955 sample_text = "laden swallows fly slowly" 1109 sample_text = "laden swallows fly slowly"
956 revised_sample_text = "unladen swallows fly quickly" 1110 revised_sample_text = "unladen swallows fly quickly"
957 sample_text_error = """\ 1111 sample_text_error = """\
958 - laden swallows fly slowly 1112 - laden swallows fly slowly
959 ? ^^^^ 1113 ? ^^^^
960 + unladen swallows fly quickly 1114 + unladen swallows fly quickly
961 ? ++ ^^^^^ 1115 ? ++ ^^^^^
962 """ 1116 """
963 try: 1117 try:
964 self.assertEqual(sample_text, revised_sample_text) 1118 self.assertEqual(sample_text, revised_sample_text)
965 except self.failureException as e: 1119 except self.failureException as e:
1120 # need to remove the first line of the error message
966 error = str(e).split('\n', 1)[1] 1121 error = str(e).split('\n', 1)[1]
967 self.assertTrue(sample_text_error == error) 1122 self.assertEqual(sample_text_error, error)
968 1123
969 def testAssertIsNone(self): 1124 def testAssertIsNone(self):
970 self.assertIsNone(None) 1125 self.assertIsNone(None)
971 self.assertRaises(self.failureException, self.assertIsNone, False) 1126 self.assertRaises(self.failureException, self.assertIsNone, False)
972 self.assertIsNotNone('DjZoPloGears on Rails') 1127 self.assertIsNotNone('DjZoPloGears on Rails')
973 self.assertRaises(self.failureException, self.assertIsNotNone, None) 1128 self.assertRaises(self.failureException, self.assertIsNotNone, None)
974 1129
975 def testAssertRegex(self): 1130 def testAssertRegex(self):
976 self.assertRegex('asdfabasdf', r'ab+') 1131 self.assertRegex('asdfabasdf', r'ab+')
977 self.assertRaises(self.failureException, self.assertRegex, 1132 self.assertRaises(self.failureException, self.assertRegex,
978 'saaas', r'aaaa') 1133 'saaas', r'aaaa')
979 1134
1135 def testAssertRaisesCallable(self):
1136 class ExceptionMock(Exception):
1137 pass
1138 def Stub():
1139 raise ExceptionMock('We expect')
1140 self.assertRaises(ExceptionMock, Stub)
1141 # A tuple of exception classes is accepted
1142 self.assertRaises((ValueError, ExceptionMock), Stub)
1143 # *args and **kwargs also work
1144 self.assertRaises(ValueError, int, '19', base=8)
1145 # Failure when no exception is raised
1146 with self.assertRaises(self.failureException):
1147 self.assertRaises(ExceptionMock, lambda: 0)
1148 # Failure when the function is None
1149 with self.assertWarns(DeprecationWarning):
1150 self.assertRaises(ExceptionMock, None)
1151 # Failure when another exception is raised
1152 with self.assertRaises(ExceptionMock):
1153 self.assertRaises(ValueError, Stub)
1154
1155 def testAssertRaisesContext(self):
1156 class ExceptionMock(Exception):
1157 pass
1158 def Stub():
1159 raise ExceptionMock('We expect')
1160 with self.assertRaises(ExceptionMock):
1161 Stub()
1162 # A tuple of exception classes is accepted
1163 with self.assertRaises((ValueError, ExceptionMock)) as cm:
1164 Stub()
1165 # The context manager exposes caught exception
1166 self.assertIsInstance(cm.exception, ExceptionMock)
1167 self.assertEqual(cm.exception.args[0], 'We expect')
1168 # *args and **kwargs also work
1169 with self.assertRaises(ValueError):
1170 int('19', base=8)
1171 # Failure when no exception is raised
1172 with self.assertRaises(self.failureException):
1173 with self.assertRaises(ExceptionMock):
1174 pass
1175 # Custom message
1176 with self.assertRaisesRegex(self.failureException, 'foobar'):
1177 with self.assertRaises(ExceptionMock, msg='foobar'):
1178 pass
1179 # Invalid keyword argument
1180 with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \
1181 self.assertRaises(AssertionError):
1182 with self.assertRaises(ExceptionMock, foobar=42):
1183 pass
1184 # Failure when another exception is raised
1185 with self.assertRaises(ExceptionMock):
1186 self.assertRaises(ValueError, Stub)
1187
1188 def testAssertRaisesNoExceptionType(self):
1189 with self.assertRaises(TypeError):
1190 self.assertRaises()
1191 with self.assertRaises(TypeError):
1192 self.assertRaises(1)
1193 with self.assertRaises(TypeError):
1194 self.assertRaises(object)
1195 with self.assertRaises(TypeError):
1196 self.assertRaises((ValueError, 1))
1197 with self.assertRaises(TypeError):
1198 self.assertRaises((ValueError, object))
1199
980 def testAssertRaisesRegex(self): 1200 def testAssertRaisesRegex(self):
981 class ExceptionMock(Exception): 1201 class ExceptionMock(Exception):
982 pass 1202 pass
983 1203
984 def Stub(): 1204 def Stub():
985 raise ExceptionMock('We expect') 1205 raise ExceptionMock('We expect')
986 1206
987 self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub) 1207 self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub)
988 self.assertRaisesRegex(ExceptionMock, 'expect$', Stub) 1208 self.assertRaisesRegex(ExceptionMock, 'expect$', Stub)
1209 with self.assertWarns(DeprecationWarning):
1210 self.assertRaisesRegex(ExceptionMock, 'expect$', None)
989 1211
990 def testAssertNotRaisesRegex(self): 1212 def testAssertNotRaisesRegex(self):
991 self.assertRaisesRegex( 1213 self.assertRaisesRegex(
992 self.failureException, '^Exception not raised by <lambda>$', 1214 self.failureException, '^Exception not raised by <lambda>$',
993 self.assertRaisesRegex, Exception, re.compile('x'), 1215 self.assertRaisesRegex, Exception, re.compile('x'),
994 lambda: None) 1216 lambda: None)
995 self.assertRaisesRegex( 1217 self.assertRaisesRegex(
996 self.failureException, '^Exception not raised by <lambda>$', 1218 self.failureException, '^Exception not raised by <lambda>$',
997 self.assertRaisesRegex, Exception, 'x', 1219 self.assertRaisesRegex, Exception, 'x',
998 lambda: None) 1220 lambda: None)
1221 # Custom message
1222 with self.assertRaisesRegex(self.failureException, 'foobar'):
1223 with self.assertRaisesRegex(Exception, 'expect', msg='foobar'):
1224 pass
1225 # Invalid keyword argument
1226 with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \
1227 self.assertRaises(AssertionError):
1228 with self.assertRaisesRegex(Exception, 'expect', foobar=42):
1229 pass
1230
1231 def testAssertRaisesRegexInvalidRegex(self):
1232 # Issue 20145.
1233 class MyExc(Exception):
1234 pass
1235 self.assertRaises(TypeError, self.assertRaisesRegex, MyExc, lambda: True )
1236
1237 def testAssertWarnsRegexInvalidRegex(self):
1238 # Issue 20145.
1239 class MyWarn(Warning):
1240 pass
1241 self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True )
999 1242
1000 def testAssertRaisesRegexMismatch(self): 1243 def testAssertRaisesRegexMismatch(self):
1001 def Stub(): 1244 def Stub():
1002 raise Exception('Unexpected') 1245 raise Exception('Unexpected')
1003 1246
1004 self.assertRaisesRegex( 1247 self.assertRaisesRegex(
1005 self.failureException, 1248 self.failureException,
1006 r'"\^Expected\$" does not match "Unexpected"', 1249 r'"\^Expected\$" does not match "Unexpected"',
1007 self.assertRaisesRegex, Exception, '^Expected$', 1250 self.assertRaisesRegex, Exception, '^Expected$',
1008 Stub) 1251 Stub)
(...skipping 11 matching lines...) Expand all
1020 raise ExceptionMock(foo) 1263 raise ExceptionMock(foo)
1021 v = "particular value" 1264 v = "particular value"
1022 1265
1023 ctx = self.assertRaises(ExceptionMock) 1266 ctx = self.assertRaises(ExceptionMock)
1024 with ctx: 1267 with ctx:
1025 Stub(v) 1268 Stub(v)
1026 e = ctx.exception 1269 e = ctx.exception
1027 self.assertIsInstance(e, ExceptionMock) 1270 self.assertIsInstance(e, ExceptionMock)
1028 self.assertEqual(e.args[0], v) 1271 self.assertEqual(e.args[0], v)
1029 1272
1030 def testAssertRaisesNoExceptionType(self): 1273 def testAssertRaisesRegexNoExceptionType(self):
r.david.murray 2012/09/01 03:00:27 Using assertRaises to test itself seems a little b
illicitonion 2012/09/01 03:35:38 Agree :) Done
1031 ctx = self.assertRaises(TypeError) 1274 with self.assertRaises(TypeError):
1032 with ctx: 1275 self.assertRaisesRegex()
1033 self.assertRaises(1) 1276 with self.assertRaises(TypeError):
1034 self.assertIsInstance(ctx.exception, TypeError) 1277 self.assertRaisesRegex(ValueError)
1035 1278 with self.assertRaises(TypeError):
1036 ctx = self.assertRaises(TypeError) 1279 self.assertRaisesRegex(1, 'expect')
1037 with ctx: 1280 with self.assertRaises(TypeError):
1038 self.assertRaises(object) 1281 self.assertRaisesRegex(object, 'expect')
1039 self.assertIsInstance(ctx.exception, TypeError) 1282 with self.assertRaises(TypeError):
1040 1283 self.assertRaisesRegex((ValueError, 1), 'expect')
1041 ctx = self.assertRaises(TypeError) 1284 with self.assertRaises(TypeError):
1042 with ctx: 1285 self.assertRaisesRegex((ValueError, object), 'expect')
1043 self.assertRaises((TypeError, 1))
1044 self.assertIsInstance(ctx.exception, TypeError)
1045
1046 ctx = self.assertRaises(TypeError)
1047 with ctx:
1048 self.assertRaises((object, 1))
1049 self.assertIsInstance(ctx.exception, TypeError)
1050 1286
1051 def testAssertWarnsCallable(self): 1287 def testAssertWarnsCallable(self):
1052 def _runtime_warn(): 1288 def _runtime_warn():
1053 warnings.warn("foo", RuntimeWarning) 1289 warnings.warn("foo", RuntimeWarning)
1054 # Success when the right warning is triggered, even several times 1290 # Success when the right warning is triggered, even several times
1055 self.assertWarns(RuntimeWarning, _runtime_warn) 1291 self.assertWarns(RuntimeWarning, _runtime_warn)
1056 self.assertWarns(RuntimeWarning, _runtime_warn) 1292 self.assertWarns(RuntimeWarning, _runtime_warn)
1057 # A tuple of warning classes is accepted 1293 # A tuple of warning classes is accepted
1058 self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn) 1294 self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn)
1059 # *args and **kwargs also work 1295 # *args and **kwargs also work
1060 self.assertWarns(RuntimeWarning, 1296 self.assertWarns(RuntimeWarning,
1061 warnings.warn, "foo", category=RuntimeWarning) 1297 warnings.warn, "foo", category=RuntimeWarning)
1062 # Failure when no warning is triggered 1298 # Failure when no warning is triggered
1063 with self.assertRaises(self.failureException): 1299 with self.assertRaises(self.failureException):
1064 self.assertWarns(RuntimeWarning, lambda: 0) 1300 self.assertWarns(RuntimeWarning, lambda: 0)
1301 # Failure when the function is None
1302 with self.assertWarns(DeprecationWarning):
1303 self.assertWarns(RuntimeWarning, None)
1065 # Failure when another warning is triggered 1304 # Failure when another warning is triggered
1066 with warnings.catch_warnings(): 1305 with warnings.catch_warnings():
1067 # Force default filter (in case tests are run with -We) 1306 # Force default filter (in case tests are run with -We)
1068 warnings.simplefilter("default", RuntimeWarning) 1307 warnings.simplefilter("default", RuntimeWarning)
1069 with self.assertRaises(self.failureException): 1308 with self.assertRaises(self.failureException):
1070 self.assertWarns(DeprecationWarning, _runtime_warn) 1309 self.assertWarns(DeprecationWarning, _runtime_warn)
1071 # Filters for other warnings are not modified 1310 # Filters for other warnings are not modified
1072 with warnings.catch_warnings(): 1311 with warnings.catch_warnings():
1073 warnings.simplefilter("error", RuntimeWarning) 1312 warnings.simplefilter("error", RuntimeWarning)
1074 with self.assertRaises(RuntimeWarning): 1313 with self.assertRaises(RuntimeWarning):
1075 self.assertWarns(DeprecationWarning, _runtime_warn) 1314 self.assertWarns(DeprecationWarning, _runtime_warn)
1076 1315
1077 def testAssertWarnsContext(self): 1316 def testAssertWarnsContext(self):
1078 # Believe it or not, it is preferrable to duplicate all tests above, 1317 # Believe it or not, it is preferable to duplicate all tests above,
1079 # to make sure the __warningregistry__ $@ is circumvented correctly. 1318 # to make sure the __warningregistry__ $@ is circumvented correctly.
1080 def _runtime_warn(): 1319 def _runtime_warn():
1081 warnings.warn("foo", RuntimeWarning) 1320 warnings.warn("foo", RuntimeWarning)
1082 _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] 1321 _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
1083 with self.assertWarns(RuntimeWarning) as cm: 1322 with self.assertWarns(RuntimeWarning) as cm:
1084 _runtime_warn() 1323 _runtime_warn()
1085 # A tuple of warning classes is accepted 1324 # A tuple of warning classes is accepted
1086 with self.assertWarns((DeprecationWarning, RuntimeWarning)) as cm: 1325 with self.assertWarns((DeprecationWarning, RuntimeWarning)) as cm:
1087 _runtime_warn() 1326 _runtime_warn()
1088 # The context manager exposes various useful attributes 1327 # The context manager exposes various useful attributes
1089 self.assertIsInstance(cm.warning, RuntimeWarning) 1328 self.assertIsInstance(cm.warning, RuntimeWarning)
1090 self.assertEqual(cm.warning.args[0], "foo") 1329 self.assertEqual(cm.warning.args[0], "foo")
1091 self.assertIn("test_case.py", cm.filename) 1330 self.assertIn("test_case.py", cm.filename)
1092 self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) 1331 self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
1093 # Same with several warnings 1332 # Same with several warnings
1094 with self.assertWarns(RuntimeWarning): 1333 with self.assertWarns(RuntimeWarning):
1095 _runtime_warn() 1334 _runtime_warn()
1096 _runtime_warn() 1335 _runtime_warn()
1097 with self.assertWarns(RuntimeWarning): 1336 with self.assertWarns(RuntimeWarning):
1098 warnings.warn("foo", category=RuntimeWarning) 1337 warnings.warn("foo", category=RuntimeWarning)
1099 # Failure when no warning is triggered 1338 # Failure when no warning is triggered
1100 with self.assertRaises(self.failureException): 1339 with self.assertRaises(self.failureException):
1101 with self.assertWarns(RuntimeWarning): 1340 with self.assertWarns(RuntimeWarning):
1102 pass 1341 pass
1342 # Custom message
1343 with self.assertRaisesRegex(self.failureException, 'foobar'):
1344 with self.assertWarns(RuntimeWarning, msg='foobar'):
1345 pass
1346 # Invalid keyword argument
1347 with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \
1348 self.assertRaises(AssertionError):
1349 with self.assertWarns(RuntimeWarning, foobar=42):
1350 pass
1103 # Failure when another warning is triggered 1351 # Failure when another warning is triggered
1104 with warnings.catch_warnings(): 1352 with warnings.catch_warnings():
1105 # Force default filter (in case tests are run with -We) 1353 # Force default filter (in case tests are run with -We)
1106 warnings.simplefilter("default", RuntimeWarning) 1354 warnings.simplefilter("default", RuntimeWarning)
1107 with self.assertRaises(self.failureException): 1355 with self.assertRaises(self.failureException):
1108 with self.assertWarns(DeprecationWarning): 1356 with self.assertWarns(DeprecationWarning):
1109 _runtime_warn() 1357 _runtime_warn()
1110 # Filters for other warnings are not modified 1358 # Filters for other warnings are not modified
1111 with warnings.catch_warnings(): 1359 with warnings.catch_warnings():
1112 warnings.simplefilter("error", RuntimeWarning) 1360 warnings.simplefilter("error", RuntimeWarning)
1113 with self.assertRaises(RuntimeWarning): 1361 with self.assertRaises(RuntimeWarning):
1114 with self.assertWarns(DeprecationWarning): 1362 with self.assertWarns(DeprecationWarning):
1115 _runtime_warn() 1363 _runtime_warn()
1116 1364
1365 def testAssertWarnsNoExceptionType(self):
1366 with self.assertRaises(TypeError):
1367 self.assertWarns()
1368 with self.assertRaises(TypeError):
1369 self.assertWarns(1)
1370 with self.assertRaises(TypeError):
1371 self.assertWarns(object)
1372 with self.assertRaises(TypeError):
1373 self.assertWarns((UserWarning, 1))
1374 with self.assertRaises(TypeError):
1375 self.assertWarns((UserWarning, object))
1376 with self.assertRaises(TypeError):
1377 self.assertWarns((UserWarning, Exception))
1378
1117 def testAssertWarnsRegexCallable(self): 1379 def testAssertWarnsRegexCallable(self):
1118 def _runtime_warn(msg): 1380 def _runtime_warn(msg):
1119 warnings.warn(msg, RuntimeWarning) 1381 warnings.warn(msg, RuntimeWarning)
1120 self.assertWarnsRegex(RuntimeWarning, "o+", 1382 self.assertWarnsRegex(RuntimeWarning, "o+",
1121 _runtime_warn, "foox") 1383 _runtime_warn, "foox")
1122 # Failure when no warning is triggered 1384 # Failure when no warning is triggered
1123 with self.assertRaises(self.failureException): 1385 with self.assertRaises(self.failureException):
1124 self.assertWarnsRegex(RuntimeWarning, "o+", 1386 self.assertWarnsRegex(RuntimeWarning, "o+",
1125 lambda: 0) 1387 lambda: 0)
1388 # Failure when the function is None
1389 with self.assertWarns(DeprecationWarning):
1390 self.assertWarnsRegex(RuntimeWarning, "o+", None)
1126 # Failure when another warning is triggered 1391 # Failure when another warning is triggered
1127 with warnings.catch_warnings(): 1392 with warnings.catch_warnings():
1128 # Force default filter (in case tests are run with -We) 1393 # Force default filter (in case tests are run with -We)
1129 warnings.simplefilter("default", RuntimeWarning) 1394 warnings.simplefilter("default", RuntimeWarning)
1130 with self.assertRaises(self.failureException): 1395 with self.assertRaises(self.failureException):
1131 self.assertWarnsRegex(DeprecationWarning, "o+", 1396 self.assertWarnsRegex(DeprecationWarning, "o+",
1132 _runtime_warn, "foox") 1397 _runtime_warn, "foox")
1133 # Failure when message doesn't match 1398 # Failure when message doesn't match
1134 with self.assertRaises(self.failureException): 1399 with self.assertRaises(self.failureException):
1135 self.assertWarnsRegex(RuntimeWarning, "o+", 1400 self.assertWarnsRegex(RuntimeWarning, "o+",
(...skipping 16 matching lines...) Expand all
1152 with self.assertWarnsRegex(RuntimeWarning, "o+") as cm: 1417 with self.assertWarnsRegex(RuntimeWarning, "o+") as cm:
1153 _runtime_warn("foox") 1418 _runtime_warn("foox")
1154 self.assertIsInstance(cm.warning, RuntimeWarning) 1419 self.assertIsInstance(cm.warning, RuntimeWarning)
1155 self.assertEqual(cm.warning.args[0], "foox") 1420 self.assertEqual(cm.warning.args[0], "foox")
1156 self.assertIn("test_case.py", cm.filename) 1421 self.assertIn("test_case.py", cm.filename)
1157 self.assertEqual(cm.lineno, _runtime_warn_lineno + 1) 1422 self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
1158 # Failure when no warning is triggered 1423 # Failure when no warning is triggered
1159 with self.assertRaises(self.failureException): 1424 with self.assertRaises(self.failureException):
1160 with self.assertWarnsRegex(RuntimeWarning, "o+"): 1425 with self.assertWarnsRegex(RuntimeWarning, "o+"):
1161 pass 1426 pass
1427 # Custom message
1428 with self.assertRaisesRegex(self.failureException, 'foobar'):
1429 with self.assertWarnsRegex(RuntimeWarning, 'o+', msg='foobar'):
1430 pass
1431 # Invalid keyword argument
1432 with self.assertWarnsRegex(DeprecationWarning, 'foobar'), \
1433 self.assertRaises(AssertionError):
1434 with self.assertWarnsRegex(RuntimeWarning, 'o+', foobar=42):
1435 pass
1162 # Failure when another warning is triggered 1436 # Failure when another warning is triggered
1163 with warnings.catch_warnings(): 1437 with warnings.catch_warnings():
1164 # Force default filter (in case tests are run with -We) 1438 # Force default filter (in case tests are run with -We)
1165 warnings.simplefilter("default", RuntimeWarning) 1439 warnings.simplefilter("default", RuntimeWarning)
1166 with self.assertRaises(self.failureException): 1440 with self.assertRaises(self.failureException):
1167 with self.assertWarnsRegex(DeprecationWarning, "o+"): 1441 with self.assertWarnsRegex(DeprecationWarning, "o+"):
1168 _runtime_warn("foox") 1442 _runtime_warn("foox")
1169 # Failure when message doesn't match 1443 # Failure when message doesn't match
1170 with self.assertRaises(self.failureException): 1444 with self.assertRaises(self.failureException):
1171 with self.assertWarnsRegex(RuntimeWarning, "o+"): 1445 with self.assertWarnsRegex(RuntimeWarning, "o+"):
1172 _runtime_warn("barz") 1446 _runtime_warn("barz")
1173 # A little trickier: we ask RuntimeWarnings to be raised, and then 1447 # A little trickier: we ask RuntimeWarnings to be raised, and then
1174 # check for some of them. It is implementation-defined whether 1448 # check for some of them. It is implementation-defined whether
1175 # non-matching RuntimeWarnings are simply re-raised, or produce a 1449 # non-matching RuntimeWarnings are simply re-raised, or produce a
1176 # failureException. 1450 # failureException.
1177 with warnings.catch_warnings(): 1451 with warnings.catch_warnings():
1178 warnings.simplefilter("error", RuntimeWarning) 1452 warnings.simplefilter("error", RuntimeWarning)
1179 with self.assertRaises((RuntimeWarning, self.failureException)): 1453 with self.assertRaises((RuntimeWarning, self.failureException)):
1180 with self.assertWarnsRegex(RuntimeWarning, "o+"): 1454 with self.assertWarnsRegex(RuntimeWarning, "o+"):
1181 _runtime_warn("barz") 1455 _runtime_warn("barz")
1456
1457 def testAssertWarnsRegexNoExceptionType(self):
1458 with self.assertRaises(TypeError):
1459 self.assertWarnsRegex()
1460 with self.assertRaises(TypeError):
1461 self.assertWarnsRegex(UserWarning)
1462 with self.assertRaises(TypeError):
1463 self.assertWarnsRegex(1, 'expect')
1464 with self.assertRaises(TypeError):
1465 self.assertWarnsRegex(object, 'expect')
1466 with self.assertRaises(TypeError):
1467 self.assertWarnsRegex((UserWarning, 1), 'expect')
1468 with self.assertRaises(TypeError):
1469 self.assertWarnsRegex((UserWarning, object), 'expect')
1470 with self.assertRaises(TypeError):
1471 self.assertWarnsRegex((UserWarning, Exception), 'expect')
1472
1473 @contextlib.contextmanager
1474 def assertNoStderr(self):
1475 with captured_stderr() as buf:
1476 yield
1477 self.assertEqual(buf.getvalue(), "")
1478
1479 def assertLogRecords(self, records, matches):
1480 self.assertEqual(len(records), len(matches))
1481 for rec, match in zip(records, matches):
1482 self.assertIsInstance(rec, logging.LogRecord)
1483 for k, v in match.items():
1484 self.assertEqual(getattr(rec, k), v)
1485
1486 def testAssertLogsDefaults(self):
1487 # defaults: root logger, level INFO
1488 with self.assertNoStderr():
1489 with self.assertLogs() as cm:
1490 log_foo.info("1")
1491 log_foobar.debug("2")
1492 self.assertEqual(cm.output, ["INFO:foo:1"])
1493 self.assertLogRecords(cm.records, [{'name': 'foo'}])
1494
1495 def testAssertLogsTwoMatchingMessages(self):
1496 # Same, but with two matching log messages
1497 with self.assertNoStderr():
1498 with self.assertLogs() as cm:
1499 log_foo.info("1")
1500 log_foobar.debug("2")
1501 log_quux.warning("3")
1502 self.assertEqual(cm.output, ["INFO:foo:1", "WARNING:quux:3"])
1503 self.assertLogRecords(cm.records,
1504 [{'name': 'foo'}, {'name': 'quux'}])
1505
1506 def checkAssertLogsPerLevel(self, level):
1507 # Check level filtering
1508 with self.assertNoStderr():
1509 with self.assertLogs(level=level) as cm:
1510 log_foo.warning("1")
1511 log_foobar.error("2")
1512 log_quux.critical("3")
1513 self.assertEqual(cm.output, ["ERROR:foo.bar:2", "CRITICAL:quux:3"])
1514 self.assertLogRecords(cm.records,
1515 [{'name': 'foo.bar'}, {'name': 'quux'}])
1516
1517 def testAssertLogsPerLevel(self):
1518 self.checkAssertLogsPerLevel(logging.ERROR)
1519 self.checkAssertLogsPerLevel('ERROR')
1520
1521 def checkAssertLogsPerLogger(self, logger):
1522 # Check per-logger filtering
1523 with self.assertNoStderr():
1524 with self.assertLogs(level='DEBUG') as outer_cm:
1525 with self.assertLogs(logger, level='DEBUG') as cm:
1526 log_foo.info("1")
1527 log_foobar.debug("2")
1528 log_quux.warning("3")
1529 self.assertEqual(cm.output, ["INFO:foo:1", "DEBUG:foo.bar:2"])
1530 self.assertLogRecords(cm.records,
1531 [{'name': 'foo'}, {'name': 'foo.bar'}])
1532 # The outer catchall caught the quux log
1533 self.assertEqual(outer_cm.output, ["WARNING:quux:3"])
1534
1535 def testAssertLogsPerLogger(self):
1536 self.checkAssertLogsPerLogger(logging.getLogger('foo'))
1537 self.checkAssertLogsPerLogger('foo')
1538
1539 def testAssertLogsFailureNoLogs(self):
1540 # Failure due to no logs
1541 with self.assertNoStderr():
1542 with self.assertRaises(self.failureException):
1543 with self.assertLogs():
1544 pass
1545
1546 def testAssertLogsFailureLevelTooHigh(self):
1547 # Failure due to level too high
1548 with self.assertNoStderr():
1549 with self.assertRaises(self.failureException):
1550 with self.assertLogs(level='WARNING'):
1551 log_foo.info("1")
1552
1553 def testAssertLogsFailureMismatchingLogger(self):
1554 # Failure due to mismatching logger (and the logged message is
1555 # passed through)
1556 with self.assertLogs('quux', level='ERROR'):
1557 with self.assertRaises(self.failureException):
1558 with self.assertLogs('foo'):
1559 log_quux.error("1")
1182 1560
1183 def testDeprecatedMethodNames(self): 1561 def testDeprecatedMethodNames(self):
1184 """ 1562 """
1185 Test that the deprecated methods raise a DeprecationWarning. See #9424. 1563 Test that the deprecated methods raise a DeprecationWarning. See #9424.
1186 """ 1564 """
1187 old = ( 1565 old = (
1188 (self.failIfEqual, (3, 5)), 1566 (self.failIfEqual, (3, 5)),
1189 (self.assertNotEquals, (3, 5)), 1567 (self.assertNotEquals, (3, 5)),
1190 (self.failUnlessEqual, (3, 3)), 1568 (self.failUnlessEqual, (3, 3)),
1191 (self.assertEquals, (3, 3)), 1569 (self.assertEquals, (3, 3)),
(...skipping 135 matching lines...) Expand 10 before | Expand all | Expand 10 after
1327 self.assertEqual(len(result.errors), 1) 1705 self.assertEqual(len(result.errors), 1)
1328 self.assertEqual(result.testsRun, 1) 1706 self.assertEqual(result.testsRun, 1)
1329 1707
1330 @support.cpython_only 1708 @support.cpython_only
1331 def testNoCycles(self): 1709 def testNoCycles(self):
1332 case = unittest.TestCase() 1710 case = unittest.TestCase()
1333 wr = weakref.ref(case) 1711 wr = weakref.ref(case)
1334 with support.disable_gc(): 1712 with support.disable_gc():
1335 del case 1713 del case
1336 self.assertFalse(wr()) 1714 self.assertFalse(wr())
1715
1716 def test_no_exception_leak(self):
1717 # Issue #19880: TestCase.run() should not keep a reference
1718 # to the exception
1719 class MyException(Exception):
1720 ninstance = 0
1721
1722 def __init__(self):
1723 MyException.ninstance += 1
1724 Exception.__init__(self)
1725
1726 def __del__(self):
1727 MyException.ninstance -= 1
1728
1729 class TestCase(unittest.TestCase):
1730 def test1(self):
1731 raise MyException()
1732
1733 @unittest.expectedFailure
1734 def test2(self):
1735 raise MyException()
1736
1737 for method_name in ('test1', 'test2'):
1738 testcase = TestCase(method_name)
1739 testcase.run()
1740 self.assertEqual(MyException.ninstance, 0)
1741
1742
1743 if __name__ == "__main__":
1744 unittest.main()
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+