Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

unittest.TestResult.errors — recorded test errors

`unittest.TestResult.errors` pairs the object associated with each error with a formatted traceback string. With the default `failureException` (`AssertionError`), assertion failures in test methods not marked with `expectedFailure` are recorded separately in `failures`.

Version: Python 3.14; repository image, production runtime not attested

Syntax

result.errors  # result is an instance of unittest.TestResult
for test, traceback_text in result.errors:
    ...

unittest.TestResult.errors is an instance attribute, not a method. It contains a list of (test, traceback_text) tuples. The first item is the object associated with the error; the second is a formatted traceback string, not an exception object. For example, if setUpClass raises an exception, unittest can use an internal placeholder instead of a TestCase instance.

For a test method not marked with expectedFailure, unittest uses the test case’s failureException type to distinguish failures from errors. If the exception being recorded is of that type or a subclass, it goes into failures; otherwise, it goes into errors. The default failureException is AssertionError, so a raised ValueError goes into errors, while a failed assertion such as self.assertEqual(1, 2) goes into failures. If failureException is set to ValueError, a raised ValueError goes into failures instead. An AssertionError raised by setUpClass, however, is recorded in errors. An assertion failure in a test method marked with expectedFailure is recorded in expectedFailures. The default addError() implementation appends an entry to errors; normally, unittest records the outcome automatically.

The example shows both outcomes with the default failureException for test methods not marked with expectedFailure and checks the stored text without printing variable paths and line numbers. An empty errors list does not prove success: check result.wasSuccessful() to account for other unsuccessful outcomes too.

Examples

import unittest

class Demo(unittest.TestCase):
    def test_error(self):
        raise ValueError("demo")

    def test_failure(self):
        self.assertEqual(1, 2)

suite = unittest.TestSuite([
    Demo("test_error"),
    Demo("test_failure"),
])
result = unittest.TestResult()
suite.run(result)

print("errors:", len(result.errors))
print("failures:", len(result.failures))
test, traceback_text = result.errors[0]
print("test:", test.id().rsplit(".", 1)[-1])
print("message present:", "ValueError: demo" in traceback_text)
print("successful:", result.wasSuccessful())

Result

errors: 1
failures: 1
test: test_error
message present: True
successful: False

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources