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