我正在开发一个具有多个源文件的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.main()”。 在实践中最好的方法是什么?
我尝试使用Python为dirBar中的每个* .py文件调用execfile ,它为第一个.py文件运行一次,并退出调用test.py,然后我必须通过添加unittest.main()来复制我的代码每个源文件 - 违反DRY原则。
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.pyTo 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()And run Python on either source, i.e.
$ python Foo.py ........... ---------------------------------------------------------------------- Ran 11 tests in 2.314s OKIdeally, 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?
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.
最满意答案
从Python 2.7开始,测试发现在unittest软件包中自动化。 从文档 :
Unittest支持简单的测试发现。 为了与测试发现兼容,所有测试文件必须是从项目顶级目录导入的模块或软件包(这意味着它们的文件名必须是有效的标识符)。
测试发现在TestLoader.discover() ,但也可以从命令行使用。 基本的命令行用法是:
cd project_directory python -m unittest discover
默认情况下,它将查找名为test*.py包,但是可以更改它,以便您可以使用类似的东西
python -m unittest discover --pattern=*.py代替你的test.py脚本。
I knew there was an obvious solution:
dirFoo\ __init__.py test.py dirBar\ __init__.py Foo.py Bar.pyContents of dirFoo/test.py
from dirBar import * import unittest if __name__ == "__main__": unittest.main()Run the tests:
$ python test.py ........... ---------------------------------------------------------------------- Ran 11 tests in 2.305s OKSorry for the silly question.
更多推荐
发布评论