从 Python 中的子目录运行所有测试 [英] Run all tests from subdirectories in Python
问题描述
我在试图让我的所有单元测试在 Python 中运行时不知所措.我已经搜索了大约 30 个不同的帖子和单元测试文档,但仍然无法弄清楚.
I am at my wits end with trying to get all my unittest to run in Python. I have searched about 30 different posts and the unit test documentation but still cannot figure it out.
首先我有两个测试类,我可以单独运行每个类并且所有测试都通过:
First I have two test classes that I can run each individually and all the tests pass:
文件:unittest.subfolder1.TestObject1.py
File: unittest.subfolder1.TestObject1.py
class TestObject1(unittest.TestCase):
def test_case1(self):
...some code...
...some assertions...
if __name__ == '__main__':
unittest.main()
文件:unittest.subfolder2.TestObject2.py
File: unittest.subfolder2.TestObject2.py
class TestObject2(unittest.TestCase):
def test_case1(self):
...some code...
...some assertions...
if __name__ == '__main__':
unittest.main()
从unittest"上方的顶级目录开始,我试图让我们 unittest.discover
找到并运行我的所有测试:
Starting in the top level directory above 'unittest' I am trying to us unittest.discover
to find and run all my tests:
import unittest
loader = unittest.TestLoader()
suite = loader.discover('unittest')
unittest.TextTestRunner().run(suite)
当我这样做时,我收到错误 `ModuleNotFoundError: No module named 'subfolder1.TestObject1'
When I do this I get the error `ModuleNotFoundError: No module named 'subfolder1.TestObject1'
我做错了什么?
推荐答案
所以我不得不做我自己的解决方法,但至少我可以让它们以上述文件结构运行.它要求我每次给它一个新的文件路径时重新实例化TestLoader和TestSuite,所以首先我需要在unittest目录中收集所有相关的文件路径.
So I had to do my own workaround but at least I can get them all to run with the above file structure. It requires that I reinstantiate the TestLoader and the TestSuite each time I give it a new file path, so first I need to collect all relevant file paths in the unittest directory.
import os
import unittest
import traceback
class UnitTestLauncher(object):
def runTests(self):
#logging.INFO("Running unit tests...")
lsPaths = []
#Find all relevant subdirectories that contain unit tests
#Exclude 'unittest' directory, but include subdirectories, with code `path != 'unittest'`
for path,subdirs,files in os.walk('unittest'):
if "pycache" not in path and path != 'unittest':
lsPaths.append(path)
#loop through subdirectories and run individually
for path in lsPaths:
loader = unittest.TestLoader()
suite = unittest.TestSuite()
suite = loader.discover(path)
unittest.TextTestRunner().run(suite)
这个解决方案并不完美,每个不同的目录都作为一行输出出现,因此您必须手动查看每一行以查找失败的测试.
This solution is not perfect and each different directory comes out as a line of output so you have to look through each line manually for failed tests.
这篇关于从 Python 中的子目录运行所有测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!