5
from test import support
11
class Test_TestResult(unittest.TestCase):
12
# Note: there are not separate tests for TestResult.wasSuccessful(),
13
# TestResult.errors, TestResult.failures, TestResult.testsRun or
14
# TestResult.shouldStop because these only have meaning in terms of
15
# other TestResult methods.
17
# Accordingly, tests for the aforenamed attributes are incorporated
18
# in with the tests for the defining methods.
19
################################################################
22
result = unittest.TestResult()
24
self.assertTrue(result.wasSuccessful())
25
self.assertEqual(len(result.errors), 0)
26
self.assertEqual(len(result.failures), 0)
27
self.assertEqual(result.testsRun, 0)
28
self.assertEqual(result.shouldStop, False)
29
self.assertIsNone(result._stdout_buffer)
30
self.assertIsNone(result._stderr_buffer)
32
# "This method can be called to signal that the set of tests being
33
# run should be aborted by setting the TestResult's shouldStop
36
result = unittest.TestResult()
40
self.assertEqual(result.shouldStop, True)
42
# "Called when the test case test is about to be run. The default
43
# implementation simply increments the instance's testsRun counter."
44
def test_startTest(self):
45
class Foo(unittest.TestCase):
51
result = unittest.TestResult()
53
result.startTest(test)
55
self.assertTrue(result.wasSuccessful())
56
self.assertEqual(len(result.errors), 0)
57
self.assertEqual(len(result.failures), 0)
58
self.assertEqual(result.testsRun, 1)
59
self.assertEqual(result.shouldStop, False)
63
# "Called after the test case test has been executed, regardless of
64
# the outcome. The default implementation does nothing."
65
def test_stopTest(self):
66
class Foo(unittest.TestCase):
72
result = unittest.TestResult()
74
result.startTest(test)
76
self.assertTrue(result.wasSuccessful())
77
self.assertEqual(len(result.errors), 0)
78
self.assertEqual(len(result.failures), 0)
79
self.assertEqual(result.testsRun, 1)
80
self.assertEqual(result.shouldStop, False)
84
# Same tests as above; make sure nothing has changed
85
self.assertTrue(result.wasSuccessful())
86
self.assertEqual(len(result.errors), 0)
87
self.assertEqual(len(result.failures), 0)
88
self.assertEqual(result.testsRun, 1)
89
self.assertEqual(result.shouldStop, False)
91
# "Called before and after tests are run. The default implementation does nothing."
92
def test_startTestRun_stopTestRun(self):
93
result = unittest.TestResult()
99
# "Called when the test case test succeeds"
101
# "wasSuccessful() - Returns True if all tests run so far have passed,
102
# otherwise returns False"
104
# "testsRun - The total number of tests run so far."
106
# "errors - A list containing 2-tuples of TestCase instances and
107
# formatted tracebacks. Each tuple represents a test which raised an
108
# unexpected exception. Contains formatted
109
# tracebacks instead of sys.exc_info() results."
111
# "failures - A list containing 2-tuples of TestCase instances and
112
# formatted tracebacks. Each tuple represents a test where a failure was
113
# explicitly signalled using the TestCase.fail*() or TestCase.assert*()
114
# methods. Contains formatted tracebacks instead
115
# of sys.exc_info() results."
116
def test_addSuccess(self):
117
class Foo(unittest.TestCase):
123
result = unittest.TestResult()
125
result.startTest(test)
126
result.addSuccess(test)
127
result.stopTest(test)
129
self.assertTrue(result.wasSuccessful())
130
self.assertEqual(len(result.errors), 0)
131
self.assertEqual(len(result.failures), 0)
132
self.assertEqual(result.testsRun, 1)
133
self.assertEqual(result.shouldStop, False)
135
# "addFailure(test, err)"
137
# "Called when the test case test signals a failure. err is a tuple of
138
# the form returned by sys.exc_info(): (type, value, traceback)"
140
# "wasSuccessful() - Returns True if all tests run so far have passed,
141
# otherwise returns False"
143
# "testsRun - The total number of tests run so far."
145
# "errors - A list containing 2-tuples of TestCase instances and
146
# formatted tracebacks. Each tuple represents a test which raised an
147
# unexpected exception. Contains formatted
148
# tracebacks instead of sys.exc_info() results."
150
# "failures - A list containing 2-tuples of TestCase instances and
151
# formatted tracebacks. Each tuple represents a test where a failure was
152
# explicitly signalled using the TestCase.fail*() or TestCase.assert*()
153
# methods. Contains formatted tracebacks instead
154
# of sys.exc_info() results."
155
def test_addFailure(self):
156
class Foo(unittest.TestCase):
164
exc_info_tuple = sys.exc_info()
166
result = unittest.TestResult()
168
result.startTest(test)
169
result.addFailure(test, exc_info_tuple)
170
result.stopTest(test)
172
self.assertFalse(result.wasSuccessful())
173
self.assertEqual(len(result.errors), 0)
174
self.assertEqual(len(result.failures), 1)
175
self.assertEqual(result.testsRun, 1)
176
self.assertEqual(result.shouldStop, False)
178
test_case, formatted_exc = result.failures[0]
179
self.assertIs(test_case, test)
180
self.assertIsInstance(formatted_exc, str)
182
# "addError(test, err)"
184
# "Called when the test case test raises an unexpected exception err
185
# is a tuple of the form returned by sys.exc_info():
186
# (type, value, traceback)"
188
# "wasSuccessful() - Returns True if all tests run so far have passed,
189
# otherwise returns False"
191
# "testsRun - The total number of tests run so far."
193
# "errors - A list containing 2-tuples of TestCase instances and
194
# formatted tracebacks. Each tuple represents a test which raised an
195
# unexpected exception. Contains formatted
196
# tracebacks instead of sys.exc_info() results."
198
# "failures - A list containing 2-tuples of TestCase instances and
199
# formatted tracebacks. Each tuple represents a test where a failure was
200
# explicitly signalled using the TestCase.fail*() or TestCase.assert*()
201
# methods. Contains formatted tracebacks instead
202
# of sys.exc_info() results."
203
def test_addError(self):
204
class Foo(unittest.TestCase):
212
exc_info_tuple = sys.exc_info()
214
result = unittest.TestResult()
216
result.startTest(test)
217
result.addError(test, exc_info_tuple)
218
result.stopTest(test)
220
self.assertFalse(result.wasSuccessful())
221
self.assertEqual(len(result.errors), 1)
222
self.assertEqual(len(result.failures), 0)
223
self.assertEqual(result.testsRun, 1)
224
self.assertEqual(result.shouldStop, False)
226
test_case, formatted_exc = result.errors[0]
227
self.assertIs(test_case, test)
228
self.assertIsInstance(formatted_exc, str)
230
def test_addSubTest(self):
231
class Foo(unittest.TestCase):
234
with self.subTest(foo=1):
235
subtest = self._subtest
238
except ZeroDivisionError:
239
exc_info_tuple = sys.exc_info()
240
# Register an error by hand (to check the API)
241
result.addSubTest(test, subtest, exc_info_tuple)
242
# Now trigger a failure
243
self.fail("some recognizable failure")
247
result = unittest.TestResult()
251
self.assertFalse(result.wasSuccessful())
252
self.assertEqual(len(result.errors), 1)
253
self.assertEqual(len(result.failures), 1)
254
self.assertEqual(result.testsRun, 1)
255
self.assertEqual(result.shouldStop, False)
257
test_case, formatted_exc = result.errors[0]
258
self.assertIs(test_case, subtest)
259
self.assertIn("ZeroDivisionError", formatted_exc)
260
test_case, formatted_exc = result.failures[0]
261
self.assertIs(test_case, subtest)
262
self.assertIn("some recognizable failure", formatted_exc)
264
def testGetDescriptionWithoutDocstring(self):
265
result = unittest.TextTestResult(None, True, 1)
267
result.getDescription(self),
268
'testGetDescriptionWithoutDocstring (' + __name__ +
271
def testGetSubTestDescriptionWithoutDocstring(self):
272
with self.subTest(foo=1, bar=2):
273
result = unittest.TextTestResult(None, True, 1)
275
result.getDescription(self._subtest),
276
'testGetSubTestDescriptionWithoutDocstring (' + __name__ +
277
'.Test_TestResult) (bar=2, foo=1)')
278
with self.subTest('some message'):
279
result = unittest.TextTestResult(None, True, 1)
281
result.getDescription(self._subtest),
282
'testGetSubTestDescriptionWithoutDocstring (' + __name__ +
283
'.Test_TestResult) [some message]')
285
def testGetSubTestDescriptionWithoutDocstringAndParams(self):
287
result = unittest.TextTestResult(None, True, 1)
289
result.getDescription(self._subtest),
290
'testGetSubTestDescriptionWithoutDocstringAndParams '
291
'(' + __name__ + '.Test_TestResult) (<subtest>)')
293
def testGetNestedSubTestDescriptionWithoutDocstring(self):
294
with self.subTest(foo=1):
295
with self.subTest(bar=2):
296
result = unittest.TextTestResult(None, True, 1)
298
result.getDescription(self._subtest),
299
'testGetNestedSubTestDescriptionWithoutDocstring '
300
'(' + __name__ + '.Test_TestResult) (bar=2, foo=1)')
302
@unittest.skipIf(sys.flags.optimize >= 2,
303
"Docstrings are omitted with -O2 and above")
304
def testGetDescriptionWithOneLineDocstring(self):
305
"""Tests getDescription() for a method with a docstring."""
306
result = unittest.TextTestResult(None, True, 1)
308
result.getDescription(self),
309
('testGetDescriptionWithOneLineDocstring '
310
'(' + __name__ + '.Test_TestResult)\n'
311
'Tests getDescription() for a method with a docstring.'))
313
@unittest.skipIf(sys.flags.optimize >= 2,
314
"Docstrings are omitted with -O2 and above")
315
def testGetSubTestDescriptionWithOneLineDocstring(self):
316
"""Tests getDescription() for a method with a docstring."""
317
result = unittest.TextTestResult(None, True, 1)
318
with self.subTest(foo=1, bar=2):
320
result.getDescription(self._subtest),
321
('testGetSubTestDescriptionWithOneLineDocstring '
322
'(' + __name__ + '.Test_TestResult) (bar=2, foo=1)\n'
323
'Tests getDescription() for a method with a docstring.'))
325
@unittest.skipIf(sys.flags.optimize >= 2,
326
"Docstrings are omitted with -O2 and above")
327
def testGetDescriptionWithMultiLineDocstring(self):
328
"""Tests getDescription() for a method with a longer docstring.
329
The second line of the docstring.
331
result = unittest.TextTestResult(None, True, 1)
333
result.getDescription(self),
334
('testGetDescriptionWithMultiLineDocstring '
335
'(' + __name__ + '.Test_TestResult)\n'
336
'Tests getDescription() for a method with a longer '
339
@unittest.skipIf(sys.flags.optimize >= 2,
340
"Docstrings are omitted with -O2 and above")
341
def testGetSubTestDescriptionWithMultiLineDocstring(self):
342
"""Tests getDescription() for a method with a longer docstring.
343
The second line of the docstring.
345
result = unittest.TextTestResult(None, True, 1)
346
with self.subTest(foo=1, bar=2):
348
result.getDescription(self._subtest),
349
('testGetSubTestDescriptionWithMultiLineDocstring '
350
'(' + __name__ + '.Test_TestResult) (bar=2, foo=1)\n'
351
'Tests getDescription() for a method with a longer '
354
def testStackFrameTrimming(self):
356
class tb_frame(object):
358
result = unittest.TestResult()
359
self.assertFalse(result._is_relevant_tb_level(Frame))
361
Frame.tb_frame.f_globals['__unittest'] = True
362
self.assertTrue(result._is_relevant_tb_level(Frame))
364
def testFailFast(self):
365
result = unittest.TestResult()
366
result._exc_info_to_string = lambda *_: ''
367
result.failfast = True
368
result.addError(None, None)
369
self.assertTrue(result.shouldStop)
371
result = unittest.TestResult()
372
result._exc_info_to_string = lambda *_: ''
373
result.failfast = True
374
result.addFailure(None, None)
375
self.assertTrue(result.shouldStop)
377
result = unittest.TestResult()
378
result._exc_info_to_string = lambda *_: ''
379
result.failfast = True
380
result.addUnexpectedSuccess(None)
381
self.assertTrue(result.shouldStop)
383
def testFailFastSetByRunner(self):
384
runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True)
386
self.assertTrue(result.failfast)
387
result = runner.run(test)
390
classDict = dict(unittest.TestResult.__dict__)
391
for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
395
def __init__(self, stream=None, descriptions=None, verbosity=None):
399
self.shouldStop = False
402
classDict['__init__'] = __init__
403
OldResult = type('OldResult', (object,), classDict)
405
class Test_OldTestResult(unittest.TestCase):
407
def assertOldResultWarning(self, test, failures):
408
with support.check_warnings(("TestResult has no add.+ method,",
412
self.assertEqual(len(result.failures), failures)
414
def testOldTestResult(self):
415
class Test(unittest.TestCase):
417
self.skipTest('foobar')
418
@unittest.expectedFailure
419
def testExpectedFail(self):
421
@unittest.expectedFailure
422
def testUnexpectedSuccess(self):
425
for test_name, should_pass in (('testSkip', True),
426
('testExpectedFail', True),
427
('testUnexpectedSuccess', False)):
428
test = Test(test_name)
429
self.assertOldResultWarning(test, int(not should_pass))
431
def testOldTestTesultSetup(self):
432
class Test(unittest.TestCase):
434
self.skipTest('no reason')
437
self.assertOldResultWarning(Test('testFoo'), 0)
439
def testOldTestResultClass(self):
440
@unittest.skip('no reason')
441
class Test(unittest.TestCase):
444
self.assertOldResultWarning(Test('testFoo'), 0)
446
def testOldResultWithRunner(self):
447
class Test(unittest.TestCase):
450
runner = unittest.TextTestRunner(resultclass=OldResult,
451
stream=io.StringIO())
452
# This will raise an exception if TextTestRunner can't handle old
453
# test result objects
454
runner.run(Test('testFoo'))
457
class MockTraceback(object):
459
def format_exception(*_):
460
return ['A traceback']
462
def restore_traceback():
463
unittest.result.traceback = traceback
466
class TestOutputBuffering(unittest.TestCase):
469
self._real_out = sys.stdout
470
self._real_err = sys.stderr
473
sys.stdout = self._real_out
474
sys.stderr = self._real_err
476
def testBufferOutputOff(self):
477
real_out = self._real_out
478
real_err = self._real_err
480
result = unittest.TestResult()
481
self.assertFalse(result.buffer)
483
self.assertIs(real_out, sys.stdout)
484
self.assertIs(real_err, sys.stderr)
486
result.startTest(self)
488
self.assertIs(real_out, sys.stdout)
489
self.assertIs(real_err, sys.stderr)
491
def testBufferOutputStartTestAddSuccess(self):
492
real_out = self._real_out
493
real_err = self._real_err
495
result = unittest.TestResult()
496
self.assertFalse(result.buffer)
500
self.assertIs(real_out, sys.stdout)
501
self.assertIs(real_err, sys.stderr)
503
result.startTest(self)
505
self.assertIsNot(real_out, sys.stdout)
506
self.assertIsNot(real_err, sys.stderr)
507
self.assertIsInstance(sys.stdout, io.StringIO)
508
self.assertIsInstance(sys.stderr, io.StringIO)
509
self.assertIsNot(sys.stdout, sys.stderr)
511
out_stream = sys.stdout
512
err_stream = sys.stderr
514
result._original_stdout = io.StringIO()
515
result._original_stderr = io.StringIO()
518
print('bar', file=sys.stderr)
520
self.assertEqual(out_stream.getvalue(), 'foo\n')
521
self.assertEqual(err_stream.getvalue(), 'bar\n')
523
self.assertEqual(result._original_stdout.getvalue(), '')
524
self.assertEqual(result._original_stderr.getvalue(), '')
526
result.addSuccess(self)
527
result.stopTest(self)
529
self.assertIs(sys.stdout, result._original_stdout)
530
self.assertIs(sys.stderr, result._original_stderr)
532
self.assertEqual(result._original_stdout.getvalue(), '')
533
self.assertEqual(result._original_stderr.getvalue(), '')
535
self.assertEqual(out_stream.getvalue(), '')
536
self.assertEqual(err_stream.getvalue(), '')
539
def getStartedResult(self):
540
result = unittest.TestResult()
542
result.startTest(self)
545
def testBufferOutputAddErrorOrFailure(self):
546
unittest.result.traceback = MockTraceback
547
self.addCleanup(restore_traceback)
549
for message_attr, add_attr, include_error in [
550
('errors', 'addError', True),
551
('failures', 'addFailure', False),
552
('errors', 'addError', True),
553
('failures', 'addFailure', False)
555
result = self.getStartedResult()
556
buffered_out = sys.stdout
557
buffered_err = sys.stderr
558
result._original_stdout = io.StringIO()
559
result._original_stderr = io.StringIO()
561
print('foo', file=sys.stdout)
563
print('bar', file=sys.stderr)
566
addFunction = getattr(result, add_attr)
567
addFunction(self, (None, None, None))
568
result.stopTest(self)
570
result_list = getattr(result, message_attr)
571
self.assertEqual(len(result_list), 1)
573
test, message = result_list[0]
574
expectedOutMessage = textwrap.dedent("""
578
expectedErrMessage = ''
580
expectedErrMessage = textwrap.dedent("""
585
expectedFullMessage = 'A traceback%s%s' % (expectedOutMessage, expectedErrMessage)
587
self.assertIs(test, self)
588
self.assertEqual(result._original_stdout.getvalue(), expectedOutMessage)
589
self.assertEqual(result._original_stderr.getvalue(), expectedErrMessage)
590
self.assertMultiLineEqual(message, expectedFullMessage)
592
def testBufferSetupClass(self):
593
result = unittest.TestResult()
596
class Foo(unittest.TestCase):
602
suite = unittest.TestSuite([Foo('test_foo')])
604
self.assertEqual(len(result.errors), 1)
606
def testBufferTearDownClass(self):
607
result = unittest.TestResult()
610
class Foo(unittest.TestCase):
612
def tearDownClass(cls):
616
suite = unittest.TestSuite([Foo('test_foo')])
618
self.assertEqual(len(result.errors), 1)
620
def testBufferSetUpModule(self):
621
result = unittest.TestResult()
624
class Foo(unittest.TestCase):
627
class Module(object):
632
Foo.__module__ = 'Module'
633
sys.modules['Module'] = Module
634
self.addCleanup(sys.modules.pop, 'Module')
635
suite = unittest.TestSuite([Foo('test_foo')])
637
self.assertEqual(len(result.errors), 1)
639
def testBufferTearDownModule(self):
640
result = unittest.TestResult()
643
class Foo(unittest.TestCase):
646
class Module(object):
648
def tearDownModule():
651
Foo.__module__ = 'Module'
652
sys.modules['Module'] = Module
653
self.addCleanup(sys.modules.pop, 'Module')
654
suite = unittest.TestSuite([Foo('test_foo')])
656
self.assertEqual(len(result.errors), 1)
659
if __name__ == '__main__':