3
from StringIO import StringIO
4
from test import test_support
10
class Test_TestResult(unittest.TestCase):
11
# Note: there are not separate tests for TestResult.wasSuccessful(),
12
# TestResult.errors, TestResult.failures, TestResult.testsRun or
13
# TestResult.shouldStop because these only have meaning in terms of
14
# other TestResult methods.
16
# Accordingly, tests for the aforenamed attributes are incorporated
17
# in with the tests for the defining methods.
18
################################################################
21
result = unittest.TestResult()
23
self.assertTrue(result.wasSuccessful())
24
self.assertEqual(len(result.errors), 0)
25
self.assertEqual(len(result.failures), 0)
26
self.assertEqual(result.testsRun, 0)
27
self.assertEqual(result.shouldStop, False)
28
self.assertIsNone(result._stdout_buffer)
29
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.assertTrue(test_case is 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.assertTrue(test_case is test)
228
self.assertIsInstance(formatted_exc, str)
230
def testGetDescriptionWithoutDocstring(self):
231
result = unittest.TextTestResult(None, True, 1)
233
result.getDescription(self),
234
'testGetDescriptionWithoutDocstring (' + __name__ +
237
@unittest.skipIf(sys.flags.optimize >= 2,
238
"Docstrings are omitted with -O2 and above")
239
def testGetDescriptionWithOneLineDocstring(self):
240
"""Tests getDescription() for a method with a docstring."""
241
result = unittest.TextTestResult(None, True, 1)
243
result.getDescription(self),
244
('testGetDescriptionWithOneLineDocstring '
245
'(' + __name__ + '.Test_TestResult)\n'
246
'Tests getDescription() for a method with a docstring.'))
248
@unittest.skipIf(sys.flags.optimize >= 2,
249
"Docstrings are omitted with -O2 and above")
250
def testGetDescriptionWithMultiLineDocstring(self):
251
"""Tests getDescription() for a method with a longer docstring.
252
The second line of the docstring.
254
result = unittest.TextTestResult(None, True, 1)
256
result.getDescription(self),
257
('testGetDescriptionWithMultiLineDocstring '
258
'(' + __name__ + '.Test_TestResult)\n'
259
'Tests getDescription() for a method with a longer '
262
def testStackFrameTrimming(self):
264
class tb_frame(object):
266
result = unittest.TestResult()
267
self.assertFalse(result._is_relevant_tb_level(Frame))
269
Frame.tb_frame.f_globals['__unittest'] = True
270
self.assertTrue(result._is_relevant_tb_level(Frame))
272
def testFailFast(self):
273
result = unittest.TestResult()
274
result._exc_info_to_string = lambda *_: ''
275
result.failfast = True
276
result.addError(None, None)
277
self.assertTrue(result.shouldStop)
279
result = unittest.TestResult()
280
result._exc_info_to_string = lambda *_: ''
281
result.failfast = True
282
result.addFailure(None, None)
283
self.assertTrue(result.shouldStop)
285
result = unittest.TestResult()
286
result._exc_info_to_string = lambda *_: ''
287
result.failfast = True
288
result.addUnexpectedSuccess(None)
289
self.assertTrue(result.shouldStop)
291
def testFailFastSetByRunner(self):
292
runner = unittest.TextTestRunner(stream=StringIO(), failfast=True)
294
self.assertTrue(result.failfast)
298
classDict = dict(unittest.TestResult.__dict__)
299
for m in ('addSkip', 'addExpectedFailure', 'addUnexpectedSuccess',
303
def __init__(self, stream=None, descriptions=None, verbosity=None):
307
self.shouldStop = False
310
classDict['__init__'] = __init__
311
OldResult = type('OldResult', (object,), classDict)
313
class Test_OldTestResult(unittest.TestCase):
315
def assertOldResultWarning(self, test, failures):
316
with test_support.check_warnings(("TestResult has no add.+ method,",
320
self.assertEqual(len(result.failures), failures)
322
def testOldTestResult(self):
323
class Test(unittest.TestCase):
325
self.skipTest('foobar')
326
@unittest.expectedFailure
327
def testExpectedFail(self):
329
@unittest.expectedFailure
330
def testUnexpectedSuccess(self):
333
for test_name, should_pass in (('testSkip', True),
334
('testExpectedFail', True),
335
('testUnexpectedSuccess', False)):
336
test = Test(test_name)
337
self.assertOldResultWarning(test, int(not should_pass))
339
def testOldTestTesultSetup(self):
340
class Test(unittest.TestCase):
342
self.skipTest('no reason')
345
self.assertOldResultWarning(Test('testFoo'), 0)
347
def testOldTestResultClass(self):
348
@unittest.skip('no reason')
349
class Test(unittest.TestCase):
352
self.assertOldResultWarning(Test('testFoo'), 0)
354
def testOldResultWithRunner(self):
355
class Test(unittest.TestCase):
358
runner = unittest.TextTestRunner(resultclass=OldResult,
360
# This will raise an exception if TextTestRunner can't handle old
361
# test result objects
362
runner.run(Test('testFoo'))
365
class MockTraceback(object):
367
def format_exception(*_):
368
return ['A traceback']
370
def restore_traceback():
371
unittest.result.traceback = traceback
374
class TestOutputBuffering(unittest.TestCase):
377
self._real_out = sys.stdout
378
self._real_err = sys.stderr
381
sys.stdout = self._real_out
382
sys.stderr = self._real_err
384
def testBufferOutputOff(self):
385
real_out = self._real_out
386
real_err = self._real_err
388
result = unittest.TestResult()
389
self.assertFalse(result.buffer)
391
self.assertIs(real_out, sys.stdout)
392
self.assertIs(real_err, sys.stderr)
394
result.startTest(self)
396
self.assertIs(real_out, sys.stdout)
397
self.assertIs(real_err, sys.stderr)
399
def testBufferOutputStartTestAddSuccess(self):
400
real_out = self._real_out
401
real_err = self._real_err
403
result = unittest.TestResult()
404
self.assertFalse(result.buffer)
408
self.assertIs(real_out, sys.stdout)
409
self.assertIs(real_err, sys.stderr)
411
result.startTest(self)
413
self.assertIsNot(real_out, sys.stdout)
414
self.assertIsNot(real_err, sys.stderr)
415
self.assertIsInstance(sys.stdout, StringIO)
416
self.assertIsInstance(sys.stderr, StringIO)
417
self.assertIsNot(sys.stdout, sys.stderr)
419
out_stream = sys.stdout
420
err_stream = sys.stderr
422
result._original_stdout = StringIO()
423
result._original_stderr = StringIO()
426
print >> sys.stderr, 'bar'
428
self.assertEqual(out_stream.getvalue(), 'foo\n')
429
self.assertEqual(err_stream.getvalue(), 'bar\n')
431
self.assertEqual(result._original_stdout.getvalue(), '')
432
self.assertEqual(result._original_stderr.getvalue(), '')
434
result.addSuccess(self)
435
result.stopTest(self)
437
self.assertIs(sys.stdout, result._original_stdout)
438
self.assertIs(sys.stderr, result._original_stderr)
440
self.assertEqual(result._original_stdout.getvalue(), '')
441
self.assertEqual(result._original_stderr.getvalue(), '')
443
self.assertEqual(out_stream.getvalue(), '')
444
self.assertEqual(err_stream.getvalue(), '')
447
def getStartedResult(self):
448
result = unittest.TestResult()
450
result.startTest(self)
453
def testBufferOutputAddErrorOrFailure(self):
454
unittest.result.traceback = MockTraceback
455
self.addCleanup(restore_traceback)
457
for message_attr, add_attr, include_error in [
458
('errors', 'addError', True),
459
('failures', 'addFailure', False),
460
('errors', 'addError', True),
461
('failures', 'addFailure', False)
463
result = self.getStartedResult()
464
buffered_out = sys.stdout
465
buffered_err = sys.stderr
466
result._original_stdout = StringIO()
467
result._original_stderr = StringIO()
469
print >> sys.stdout, 'foo'
471
print >> sys.stderr, 'bar'
474
addFunction = getattr(result, add_attr)
475
addFunction(self, (None, None, None))
476
result.stopTest(self)
478
result_list = getattr(result, message_attr)
479
self.assertEqual(len(result_list), 1)
481
test, message = result_list[0]
482
expectedOutMessage = textwrap.dedent("""
486
expectedErrMessage = ''
488
expectedErrMessage = textwrap.dedent("""
492
expectedFullMessage = 'A traceback%s%s' % (expectedOutMessage, expectedErrMessage)
494
self.assertIs(test, self)
495
self.assertEqual(result._original_stdout.getvalue(), expectedOutMessage)
496
self.assertEqual(result._original_stderr.getvalue(), expectedErrMessage)
497
self.assertMultiLineEqual(message, expectedFullMessage)
499
def testBufferSetupClass(self):
500
result = unittest.TestResult()
503
class Foo(unittest.TestCase):
509
suite = unittest.TestSuite([Foo('test_foo')])
511
self.assertEqual(len(result.errors), 1)
513
def testBufferTearDownClass(self):
514
result = unittest.TestResult()
517
class Foo(unittest.TestCase):
519
def tearDownClass(cls):
523
suite = unittest.TestSuite([Foo('test_foo')])
525
self.assertEqual(len(result.errors), 1)
527
def testBufferSetUpModule(self):
528
result = unittest.TestResult()
531
class Foo(unittest.TestCase):
534
class Module(object):
539
Foo.__module__ = 'Module'
540
sys.modules['Module'] = Module
541
self.addCleanup(sys.modules.pop, 'Module')
542
suite = unittest.TestSuite([Foo('test_foo')])
544
self.assertEqual(len(result.errors), 1)
546
def testBufferTearDownModule(self):
547
result = unittest.TestResult()
550
class Foo(unittest.TestCase):
553
class Module(object):
555
def tearDownModule():
558
Foo.__module__ = 'Module'
559
sys.modules['Module'] = Module
560
self.addCleanup(sys.modules.pop, 'Module')
561
suite = unittest.TestSuite([Foo('test_foo')])
563
self.assertEqual(len(result.errors), 1)
566
if __name__ == '__main__':