首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何设置py.test的动态默认参数?

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

Stack Overflow用户
提问于 2018-01-18 19:33:50
回答 3查看 2.3K关注 0票数 3

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-01-18 20:40:04

首先,如果您想隐式地将命令行参数添加到pytest中,您可以使用位于测试根目录中的pytest.iniaddopts配置值:

代码语言:javascript
复制
[pytest]
addopts=--verbose --junit-xml=/tmp/myreport.xml  # etc

当然,如果您希望动态计算存储报告的目录,则不能将其放入配置中,需要扩展pytest。最好的地方应该是pytest_configure钩子。示例:

代码语言:javascript
复制
# 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值。

示例运行:

代码语言:javascript
复制
$ 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报告现在放在一个临时文件中。

票数 3
EN

Stack Overflow用户

发布于 2018-01-18 20:37:06

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

代码语言:javascript
复制
# content of pytest.ini
[pytest]
addopts = --html=report.html --self-contained-html
;addopts = -vv -rw --html=./results/report.html --self-contained-html
票数 0
EN

Stack Overflow用户

发布于 2018-02-07 17:45:39

@hoefling的答案在conftest.py中非常适合我。这里的代码看起来更简单。

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48320357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档