Method call based on result after unittest in Python

How do you call a function after each test in a Python derived class unittest.TestCase

based on the result of the test?

For example, let's say we have the following test class:

import sys
from unittest import TestCase

class TestFeedback(TestCase):
  def msg(self, text):
    sys.stdout.write(text + ' ...')

  def on_fail(self):
    sys.stdout.write(' FAILED!\n')

  def on_success(self):
    sys.stdout.write(' SUCCEEDED!\n')

  def test_something(self):
    self.msg('Testing whether True == 1')
    self.assertTrue(True == 1)

  def test_another(self):
    self.msg('Testing whether None == 0')
    self.assertEqual(None, 0)

      

I would like the methods to be called after each test, on_success()

or on_fail()

depending on the result of the test, for example.

>>> unittest.main()
...
Testing whether True == 1 ... SUCCEEDED!
Testing whether None == 0 ... FAILED!
<etc.>

      

Can this be done, and if so, how?

+3


source to share


1 answer


As of now, I don't think you can do it. The object has TestResult

disappeared before you go to your method tearDown

, which is likely to be the simplest.

Instead, you can flip your own TestSuite

(see here for a basic explanation), which should give you access to the results for each test. The downside is that you have to add each test individually or create your own detection method.

Another option is to pass the error message into your statements; messages will be printed with an error:

self.assertEqual(None, 0, 'None is not 0')

      



What's your ultimate goal? Running unittests will tell you which tests have failed with trace information, so I assume you have a different target.

Edit :
Ok, I think one solution would be to write your own custom class TestCase

and override the method __call__

(note: I haven't tested this):

from unittest import TestCase    
class CustomTestCase(TestCase):
    def __call__(self, *args, **kwds):
        result = self.run(*args, **kwds)
        <do something with result>
        return result

      

Edit 2 :
Another possible solution ... check this answer

+2


source







All Articles