jeudi 21 mai 2015

Result based method call after a unittest in Python

How do you call a function after each test in a Python unittest.TestCase derived class based on the test result?

For instance, lets 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 on_success() or on_fail() to be called after each test depending on the outcome of the test, e.g.

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

Can this be done and, if so, how?

Aucun commentaire:

Enregistrer un commentaire