Last active
March 13, 2025 12:03
-
-
Save hynekcer/1b0a260ef72dae05fe9611904d7b9675 to your computer and use it in GitHub Desktop.
Getting Python's unittest results in a tearDown() method (my SO answer, question 4414234)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Getting Python's unittest results in a tearDown() method | |
https://stackoverflow.com/questions/4414234/getting-pythons-unittest-results-in-a-teardown-method#39606065 | |
""" | |
import unittest | |
class MyTest(unittest.TestCase): | |
def tearDown(self): | |
if hasattr(self._outcome, 'errors'): | |
# Python 3.4 - 3.10 (These two methods have no side effects) | |
result = self.defaultTestResult() | |
self._feedErrorsToResult(result, self._outcome.errors) | |
else: | |
# Python 3.11+ | |
result = self._outcome.result | |
ok = all(test != self for test, text in result.errors + result.failures) | |
# Demo output: (print short info immediately - not important) | |
if ok: | |
print('\nOK: %s' % (self.id(),)) | |
for typ, errors in (('ERROR', result.errors), ('FAIL', result.failures)): | |
for test, text in errors: | |
if test is self: | |
# the full traceback is in the variable `text` | |
msg = [x for x in text.split('\n')[1:] | |
if not x.startswith(' ')][0] | |
print("\n\n%s: %s\n %s" % (typ, self.id(), msg)) | |
def list2reason(self, exc_list): | |
if exc_list and exc_list[-1][0] is self: | |
return exc_list[-1][1] | |
# demo tests | |
def test_success(self): | |
self.assertEqual(1, 1) | |
def test_fail(self): | |
self.assertEqual(2, 1) | |
def test_error(self): | |
self.assertEqual(1 / 0, 1) | |
@unittest.expectedFailure | |
def test_expected_fail(self): | |
self.assertEqual(2, 1) | |
@unittest.expectedFailure | |
def test_expected_error(self): | |
self.assertEqual(1 / 0, 1) | |
@unittest.expectedFailure | |
def test_unexpected_success(self): | |
self.assertEqual(1, 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Work perfectly for me 😄
Python 3.11.9