Search code examples
pythonpython-3.xunit-testingpython-unittest

Python unittest startTestRun to execute setup only once before all tests


I have several test files in different directories.

\tests
    \subtestdir1
        -__init__.py
        -test1.py
    \subtestdir2
        -__init__.py
        -test2.py
    -__init__.py
    -test3.py

I need to do some setups only once before all tests in all test files.

According to https://stackoverflow.com/a/66252981, the top-level __init__.py looks like this:

import unittest


OLD_TEST_RUN = unittest.result.TestResult.startTestRun


def startTestRun(self):
    print('once before all tests')
    OLD_TEST_RUN(self)


unittest.result.TestResult.startTestRun = startTestRun

I've tried this too: https://stackoverflow.com/a/64892396/3337597

import unittest


def startTestRun(self):
    print('once before all tests')


setattr(unittest.TestResult, 'startTestRun', startTestRun)

In both cases, all tests ran successfully, but startTestRun doesn't execute. I couldn't figure out why. I appreciate any clarification.

(I use unittest.TestCase and run my tests by right click on the tests directory and clicking Run 'Python tests in test...')


Solution

  • The problem was that in those 2 answers, the startTestRun method was not in any class. It should be like this:

    import unittest
    
    class TestResult(object):
        def startTestRun(self):
            print('once before all tests')
    
    
    setattr(unittest.TestResult, 'startTestRun', TestResult.startTestRun)
    

    If you need to tidy up after all tests, that's the same with stopTestRun:

    import unittest
    
    class TestResult(object):
        def stopTestRun(self):
            print('once after all tests')
    
    
    setattr(unittest.TestResult, 'stopTestRun', TestResult.stopTestRun)