多个模块的Python单元测试覆盖率 [英] Python unit test coverage for multiple modules
问题描述
我搜索了很长时间,但出乎意料的是,没有找到满意的答案.
我的Python项目中有多个模块/文件,我编写了使用 unittest
的单元测试.这样的结构使得我在一个目录中(例如 myproject/production
)具有生产模块 module_A.py
和 module_B.py
并进行相应的测试-将文件 test_module_A.py
和 test_module_B.py
放在同级目录中(例如 myproject/tests
).
现在,我已经安装了 coverage.py
,并希望运行与该项目相关的所有测试(即,所有前缀为 test_
(来自 tests
目录),并收到一份覆盖率报告,其中显示了所有生产模块( module_A.py
和 module_B.py
>).
我发现可以通过从 myproject/tests
目录运行以下命令来做到这一点:
-
覆盖擦除
-
coverage run -a --source myproject.production test_module_A.py
-
coverage run -a --source myproject.production test_module_B.py
-
覆盖率报告
这给了我一张不错的表格,其中列出了我所有的生产模块及其覆盖范围.到目前为止一切顺利.
但是我可以只用一个命令来执行此操作吗?假设我没有要包含在一个报告中的2个或20个或200个测试,那么手工"执行此操作似乎很荒谬.>
必须有一种自动化的方法,但是我似乎找不到它.当然,shell脚本可以做到这一点,但这相当笨拙.我正在考虑类似于 unittest discover
的方法,但是对于 coverage.py
来说,这似乎不起作用.
或者我可以使用coverage-API来完成此操作吗?到目前为止,我没有运气尝试.
.
解决方案:(感谢Ned Batchelder先生)
从 myproject/tests
目录运行:
coverage run --source myproject.production -m unittest discover&&覆盖率报告
一行,完全按照需要做.
这应该做到:
coverage.py运行-m unittest发现
I searched for a long time and surprisingly found no satisfactory answer.
I have multiple modules/files in my Python project that I wrote unit tests for using unittest
. The structure is such that I have production-modules module_A.py
and module_B.py
in one directory (say myproject/production
) and corresponding test-files test_module_A.py
and test_module_B.py
in a sibling directory (say myproject/tests
).
Now I have coverage.py
installed and want to run all the tests associated with the project (i.e. all .py
-files with the prefix test_
from the tests
directory) and receive a coverage report showing the coverage for all the production-modules (module_A.py
and module_B.py
).
I figured out that I can do this by running the following commands from the myproject/tests
directory:
coverage erase
coverage run -a --source myproject.production test_module_A.py
coverage run -a --source myproject.production test_module_B.py
coverage report
This gives me that nice table with all my production modules listed and their coverage results. So far so good.
But can I do this with just one command? Assuming I have not 2 but 20 or 200 tests that I want to include in one report, doing this "by hand" seems ridiculous.
There must be a way to automate this, but I can't seem to find it. Sure a shell-script might do it, but that is rather clumsy. I am thinking of something akin to unittest discover
, but for coverage.py
this doesn't seem to work.
Or could I accomplish this using the coverage-API somehow? So far I had no luck trying.
.
SOLUTION: (credit to Mr. Ned Batchelder)
From myproject/tests
directory run:
coverage run --source myproject.production -m unittest discover && coverage report
One line, doing exactly what was needed.
This should do it:
coverage.py run -m unittest discover
这篇关于多个模块的Python单元测试覆盖率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!