如何为py.test设置动态默认参数?

use*_*338 3 python pytest

我有一个在 py.test 下工作的框架。py.test 可以使用参数 --html 和 --junitxml 生成美容报告。但是使用我的框架的客户并不总是在他们使用 py.test 的命令行中输入这个参数。我想让 py.test 在 py.test 与我的框架一起使用时总是生成报告。我想把这个报告放在日志文件夹中。所以我需要在运行时生成报告的路径。我可以通过固定装置做到这一点吗?或者也许是通过插件 API?

hoe*_*ing 5

首先,如果您想隐式地将命令行参数添加到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 报告现在放入临时文件中。


Dre*_*rew 5

把它放在 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)

出于以下几个原因,对于大多数人来说,接受的答案可能比必要的要复杂一些:

  • 装饰器没有帮助。什么时候执行这无关紧要。
  • 无需自定义 LogXML,因为您只需在此处设置属性即可使用。
  • slaveinput 特定于 pytest 插件 xdist。我认为没有必要对此进行检查,尤其是在您不使用 xdist 的情况下。