Python:如何为子目录中的所有源文件运行 unittest.main()? [英] Python: How to run unittest.main() for all source files in a subdirectory?
问题描述
我正在开发一个包含多个源文件的 Python 模块,每个源文件都有自己的测试类,这些测试类派生自 unittest 就在源代码中.考虑目录结构:
I am developing a Python module with several source files, each with its own test class derived from unittest right in the source. Consider the directory structure:
dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
要测试 Foo.py 或 Bar.py,我会在 Foo.py 和 Bar.py 源文件的末尾添加:
To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:
if __name__ == "__main__":
unittest.main()
并在任一源上运行 Python,即
And run Python on either source, i.e.
$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
理想情况下,我会让test.py"自动搜索任何 unittest 派生类的 dirBar 并调用unittest.main()".在实践中做到这一点的最佳方法是什么?
Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice?
我尝试使用 Python 为每个 *.py 文件调用 execfiledirBar,它为找到的第一个 .py 文件运行一次 &退出调用 test.py,然后我必须通过在每个源文件中添加 unittest.main() 来复制我的代码——这违反了 DRY 原则.
I tried using Python to call execfile for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles.
推荐答案
我知道有一个显而易见的解决方案:
I knew there was an obvious solution:
dirFoo\
__init__.py
test.py
dirBar\
__init__.py
Foo.py
Bar.py
dirFoo/test.py 的内容
Contents of dirFoo/test.py
from dirBar import *
import unittest
if __name__ == "__main__":
unittest.main()
运行测试:
$ python test.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.305s
OK
这篇关于Python:如何为子目录中的所有源文件运行 unittest.main()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!