Home > Blockchain >  Python unittest startTestRun to execute setup only once before all tests
Python unittest startTestRun to execute setup only once before all tests

Time:01-19

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...')

CodePudding user response:

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)

CodePudding user response:

import sys
sys.path.insert(0, '../src')
import vader
import unittest

class TestVader(unittest.TestCase):


    def setUp(self):
        self.testDbData = [DATA]

    def test_build_training_data(self):
        
        dataStruct = vader.build_data_struct(self.testDbData)
    
    def test_get_points(self):
        dataStruct = vader.build_data_struct(self.testDbData)

this is what i did for one of my project

  • Related