[英]How can I execute tearDown and setUp method for all unittest.TestCase classes
I have one class BaseTest and all tests are extended from it.我有一个 BaseTest 类,所有测试都是从它扩展而来的。 Tests are located in different modules and packages.
测试位于不同的模块和包中。 setUpClass and tearDownClass methods are executed before each unittest.TestCase class.
setUpClass 和 tearDownClass 方法在每个 unittest.TestCase 类之前执行。 How can I execute setUp and tearDown only once.
如何只执行一次 setUp 和 tearDown。 Before and after all tests.
在所有测试之前和之后。
this is example of code:这是代码示例:
import unittest
class BaseTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("setUpClass")
@classmethod
def tearDownClass(cls):
print("tearDownClass")
if __name__ == '__main__':
unittest.main()
module2.py:模块2.py:
class TestOne(BaseTest):
def test_one(self):
print("Test One")
class TestTwo(BaseTest):
def test_two(self):
print("Test Two")
if __name__ == '__main__':
unittest.main()
module3.py模块3.py
class TestThree(BaseTest):
def test_three(self):
print("Test Three")
class TestFour(BaseTest):
def test_four(self):
print("Test Four")
if __name__ == '__main__':
unittest.main()
module4.py模块4.py
class TestFive(BaseTest):
def test_five(self):
print("Test Five")
if __name__ == '__main__':
unittest.main()
its possible to do with unittest
copy the answer from https://stackoverflow.com/a/64892396/2679740 here它可能与
unittest
从https://stackoverflow.com/a/64892396/2679740这里复制答案
you can do it by defining startTestRun
, stopTestRun
of unittest.TestResult
class.您可以通过定义
unittest.TestResult
类的startTestRun
、 stopTestRun
来实现。
by adding following code to my tests/__init__.py
i managed to achieve it.通过将以下代码添加到我的
tests/__init__.py
我设法实现了它。 this code runs only once for all tests(regardless of number of test classes and test files).此代码仅对所有测试运行一次(无论测试类和测试文件的数量如何)。
def startTestRun(self):
"""
https://docs.python.org/3/library/unittest.html#unittest.TestResult.startTestRun
Called once before any tests are executed.
:return:
"""
DockerCompose().start()
setattr(unittest.TestResult, 'startTestRun', startTestRun)
def stopTestRun(self):
"""
https://docs.python.org/3/library/unittest.html#unittest.TestResult.stopTestRun
Called once after all tests are executed.
:return:
"""
DockerCompose().compose.stop()
setattr(unittest.TestResult, 'stopTestRun', stopTestRun)
I don't think unittest has a facility for universal setup and teardown.我认为 unittest 没有通用设置和拆卸工具。 You should look into pytest, its fixtures are more powerful.
你应该看看 pytest,它的装置更强大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.