我有一个在 py.test 下工作的框架。py.test 可以使用参数 --html 和 --junitxml 生成美容报告。但是使用我的框架的客户并不总是在他们使用 py.test 的命令行中输入这个参数。我想让 py.test 在 py.test 与我的框架一起使用时总是生成报告。我想把这个报告放在日志文件夹中。所以我需要在运行时生成报告的路径。我可以通过固定装置做到这一点吗?或者也许是通过插件 API?
首先,如果您想隐式地将命令行参数添加到pytest,您可以使用pytest.ini放置在测试根目录中的addopts配置值:
[pytest]
addopts=--verbose --junit-xml=/tmp/myreport.xml # etc
Run Code Online (Sandbox Code Playgroud)
当然,如果你想动态计算存储报告的目录,那么你不能将其放在配置中,并且需要扩展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)
Run Code Online (Sandbox Code Playgroud)
如果删除第一个if块,则将pytest完全忽略--junit-xml通过命令行传递的参数或addopts配置中的值。
运行示例:
[pytest]
addopts=--verbose --junit-xml=/tmp/myreport.xml # etc
Run Code Online (Sandbox Code Playgroud)
xml 报告现在放入临时文件中。
把它放在 conftest.py 中就足够了:
def pytest_configure(config):
if config.option.xmlpath is None:
config.option.xmlpath = get_custom_xml_path() # implement this
Run Code Online (Sandbox Code Playgroud)
出于以下几个原因,对于大多数人来说,接受的答案可能比必要的要复杂一些: