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

时间:2018-01-18 11:33:50

标签: python pytest

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

4 个答案:

答案 0 :(得分:2)

首先,如果要隐式将命令行参数添加到pytest,可以使用pytest.ini配置值中的addopts放置在测试根目录中:< / p>

[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报告现在放在临时文件中。

答案 1 :(得分:0)

使用参数配置pytest.ini文件:

# content of pytest.ini
[pytest]
addopts = --html=report.html --self-contained-html
;addopts = -vv -rw --html=./results/report.html --self-contained-html

答案 2 :(得分:0)

@ 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)

答案 3 :(得分:0)

将其放在conftest.py中即可:

def pytest_configure(config):
    if config.option.xmlpath is None:
        config.option.xmlpath = get_custom_xml_path() # implement this

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

  • 装饰器无济于事。何时执行无关紧要。
  • 无需创建自定义LogXML,因为您只需在此处设置属性即可使用。
  • slaveinput特定于pytest插件xdist。我认为没有必要进行检查,特别是如果您不使用xdist。