我正在开发一个包含多个源文件的 Python 模块,每个源文件都有自己的测试类,这些测试类源自 unittest就在源头。考虑目录结构:
dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
要测试 Foo.py 或 Bar.py,我会在 Foo.py 和 Bar.py 源文件的末尾添加:
if __name__ == "__main__":
unittest.main()
并在任一源上运行 Python,即
$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
理想情况下,我会让“test.py”自动在 dirBar 中搜索任何 unittest 派生类,然后调用一次“unittest.main()”。在实践中做到这一点的最佳方法是什么?
我尝试使用 Python 调用 execfile对于 dirBar 中的每个 *.py 文件,它为找到的第一个 .py 文件运行一次并退出调用 test.py,然后我必须通过在每个源文件中添加 unittest.main() 来复制我的代码——这违反了干燥原则。
最佳答案
从 Python 2.7 开始,测试发现在 unittest 包中是自动化的。来自 docs :
Unittest supports simple test discovery. In order to be compatible with test discovery, all of the test files must be modules or packages importable from the top-level directory of the project (this means that their filenames must be valid identifiers).
Test discovery is implemented in
TestLoader.discover()
, but can also be used from the command line. The basic command-line usage is:cd project_directory python -m unittest discover
默认情况下,它会查找名为 test*.py
的包,但这可以更改,因此您可以使用类似
python -m unittest discover --pattern=*.py
代替您的 test.py 脚本。
关于Python:如何为子目录中的所有源文件运行 unittest.main()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/644821/