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

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

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

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