我有一个在py.test下工作的框架。py.test可以使用params --html和--junitxml生成美容报告。但是使用我的框架的客户并不总是在使用py.test的命令行中输入这个参数。当py.test与我的框架一起使用时,我想让py.test总是生成报告。我想把这个报告放在日志文件夹里。所以我需要在运行时为报告生成路径。我可以通过固定装置来做这件事吗?或者可能是通过插件API?
发布于 2018-01-18 20:40:04
首先,如果您想隐式地将命令行参数添加到pytest
中,您可以使用位于测试根目录中的pytest.ini
和addopts
配置值:
[pytest]
addopts=--verbose --junit-xml=/tmp/myreport.xml # etc
当然,如果您希望动态计算存储报告的目录,则不能将其放入配置中,需要扩展pytest
。最好的地方应该是pytest_configure
钩子。示例:
# conftest.py
import tempfile
import pytest
from _pytest.junitxml import LogXML
@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
if config.option.xmlpath: # was passed via config or command line
return # let pytest handle it
if not hasattr(config, 'slaveinput'):
with tempfile.NamedTemporaryFile(suffix='.xml') as tmpfile:
xmlpath = tmpfile.name
config._xml = LogXML(xmlpath, config.option.junitprefix, config.getini('junit_suite_name'))
config.pluginmanager.register(config._xml)
如果删除第一个if
块,则pytest
将完全忽略通过命令行传递的--junit-xml
arg或配置中的addopts
值。
示例运行:
$ pytest
=================================== test session starts ====================================
platform darwin -- Python 3.6.3, pytest-3.3.1, py-1.5.2, pluggy-0.6.0
rootdir: /Users/hoefling/projects/private/stackoverflow/so-48320357, inifile:
plugins: forked-0.2, asyncio-0.8.0, xdist-1.22.0, mock-1.6.3, hypothesis-3.44.4
collected 1 item
test_spam.py . [100%]
--- generated xml file: /var/folders/_y/2qk6029j4c7bwv0ddk3p96r00000gn/T/tmp1tleknm3.xml ---
================================ 1 passed in 0.01 seconds ==================================
xml报告现在放在一个临时文件中。
发布于 2018-01-18 20:37:06
使用参数配置pytest.ini文件:
# content of pytest.ini
[pytest]
addopts = --html=report.html --self-contained-html
;addopts = -vv -rw --html=./results/report.html --self-contained-html
发布于 2018-02-07 17:45:39
@hoefling的答案在conftest.py中非常适合我。这里的代码看起来更简单。
def pytest_configure(config):
if not config.option.xmlpath and not hasattr(config, 'slaveinput'):
xmlpath = "test_report_" + str(int(time.time())) + ".xml"
config._xml = LogXML(xmlpath, config.option.junitprefix, config.getini('junit_suite_name'))
config.pluginmanager.register(config._xml)
https://stackoverflow.com/questions/48320357
复制相似问题