简体   繁体   English

Python unittest startTestRun 在所有测试之前只执行一次设置

[英]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:根据https://stackoverflow.com/a/66252981 ,顶级__init__.py看起来像这样:

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我也试过这个: 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.在这两种情况下,所有测试都成功运行,但 startTestRun 没有执行。 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...') (我使用 unittest.TestCase 并通过右键单击测试目录并单击运行“测试中的 Python 测试...”来运行我的测试)

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这是我为我的一个项目所做的

The problem was that in those 2 answers, the startTestRun method was not in any class. It should be like this:问题是在这 2 个答案中, startTestRun方法不在任何 class 中。它应该是这样的:

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 :如果您需要在所有测试后进行整理,这与stopTestRun相同:

import unittest

class TestResult(object):
    def stopTestRun(self):
        print('once after all tests')


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM