Python:如何为子目录中的所有源文件运行unittest.main()?(Python: How to run unittest.main() for all source files in a

编程入门 行业动态 更新时间:2024-10-28 16:26:16
Python:如何为子目录中的所有源文件运行unittest.main()?(Python: How to run unittest.main() for all source files in a subdirectory?)

我正在开发一个具有多个源文件的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.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()

And run Python on either source, i.e.

$ python Foo.py ........... ---------------------------------------------------------------------- Ran 11 tests in 2.314s OK

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?

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.py

Contents 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 OK

Sorry for the silly question.

更多推荐

本文发布于:2023-08-03 02:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382939.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:源文件   何为   目录中   unittest   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!