vendredi 28 avril 2017

How to make each TestCase call a hook after setUp?

In my project I have a subclass of TestCase (call it BaseTest) which does some stuff to prepare and then reset the testing environment, and a large number of actual test case subclasses (about 80) which each have their own unique setUp methods.

I want each of the individual test case subclasses to call a particular hook at the end of their setUp methods. I would like to do this without making a change to every one of those methods.

Basically, the situation looks roughly like this example file:

import unittest


class BaseTest(unittest.TestCase):
    def setUp(self):
        super().setUp()
        print('prepping env')

    def tearDown(self):
        super().tearDown()
        print('resetting env')

    def post_setup_hook(self):
        print('in post_setup_hook')


class TestFeatureA(BaseTest):
    def setUp(self):
        super().setUp()
        print('prepping a')

    def tearDown(self):
        super().tearDown()

    def test_0(self):
        print('testing a0')

    def test_1(self):
        print('testing a1')


class TestFeatureB(BaseTest):
    def setUp(self):
        super().setUp()
        print('prepping b')

    def tearDown(self):
        super().tearDown()

    def test_0(self):
        print('testing b0')

    def test_1(self):
        print('testing b1')


if __name__ == '__main__':
    unittest.main()

I would like the result of running python -m unittest example to print 'in post setup hook' after each time it prints 'prepping a' or 'prepping b', but without modifying TestFeatureA or TestFeatureB. Can this be done?

Note that I'm using python 3.6. I don't think this will run in python 2.x.

Aucun commentaire:

Enregistrer un commentaire