Debian Codegraph @

lib-python/3/unittest/test/test_case.py

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