一般情况下pytest-html生成的报告,如果有用例执行失败是会显示执行脚本的所有代码的。

这样当用例多的时候,生成的报告可以会很大,当然有时我们也不想自己的代码在报告中显示出来。下面的代码就实现了在报告中让这些代码不显示的功能。
import pytest
@pytest.mark.hookwrapper
def pytest_runtest_makereport():
outcome = yield
report = outcome.get_result()
if report.when == 'call' and report.passed is False:
for i, v in enumerate(report.longrepr.reprtraceback.reprentries[0].lines[::-1]): # 逆向遍历
if not v.startswith('E'):
index = len(report.longrepr.reprtraceback.reprentries[0].lines) - i
report.longrepr.reprtraceback.reprentries[0].lines \
= report.longrepr.reprtraceback.reprentries[0].lines[index:]
break
核心是找到在这里要输出的内容(这里找的是longrepr.reprtraceback.reprentries,试了其他的属性没有成功),删除以不是以"E"开头的行就可以了。 没有再深入研究(其实是没找到),猜测pytest-html后续对以"E"开头的行做了红色的处理。
下面再执行一遍测试代码,看看报告中自己的代码已经被去除了。

更新:
用到pytest-check这个插件,也可以达到这个效果。不过这个插件本意是在assert时报错的时候不退出,尽可能把所有验证执行完,可以见下面的例子。
from pytest_check import check
def test_check():
with check: assert 1==2
with check: assert 2==3, '2 is not equal to 3!'
with check: assert 3==4
报告结果:

网友评论