如何使用 pytest-cov 生成覆盖报告并打印到终端?

时间:2021-02-19 15:32:25

标签: python pytest code-coverage pytest-cov

背景

我刚开始使用 pytest 和 pytest-cov,从 unittest + coverage.py 切换过来

我首先将我的自动化测试设置为以这种方式运行:

python3 -m pytest --cov=myapplication

这给了我这样的输出到终端:

----------- coverage: platform linux, python 3.8.5-final-0 -----------
Name                        Stmts   Miss  Cover
-----------------------------------------------
myapplication/__init__.py       0      0   100%
myapplication/file.py          30     30     0%
myapplication/another_file.py  20      6    70%
[...]
-----------------------------------------------
TOTAL                        1195    464    61%

然后我想生成一个xml报告所以我改变了命令:

python3 -m pytest --cov-report xml:coverage.xml --cov=myapplication

问题

我遇到的问题是,在添加 --cov-report xml:coverage.xml 后,我不再获得任何输出到终端

看着the documentation for pytest-cov,我发现:

<块引用>

这三个报告选项输出到文件而不在终端上显示任何内容: [继续显示 xml、html 和注释报告选项]

问题

如何在同一测试运行中生成报告并打印到终端? (这甚至可能吗?)

(我可以运行测试套件两次,但如果可以,我想一次完成所有事情)


我正在使用这些版本:

  • Python 3.8.5
  • pytest 6.2.2(撰写本文时的最新版本)
  • pytest-cov 2.11.1 (-"-)

1 个答案:

答案 0 :(得分:2)

您可以通过使用终端输出格式之一指定另一个 --cov-report 参数来实现此目的。您可以有 --cov-report term--cov-report term-missing。例如:

python3 -m pytest --cov-report term --cov-report xml:coverage.xml --cov=myapplication

请参阅 pytest-cov docs you linked to 了解 termterm-missing 的工作原理。