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