2016-09-20 329 views
0

我想用pytest自定义html报告。 举例来说,如果我有一个目录结构,如:如何自定义使用py.test生成的html报告文件?

tests 
    temp1 
     test_temp1.py 
    conftest.py 

一个conftest.py文件也是在测试中的目录,它应该是共同在测试目录中的所有子目录。 什么夹具和hookwrappers可以我在conftest.py用来改变使用以下命令生成的HTML文件的内容:

py.test测试/ temp1目录/ test_temp1.py --html = report.html

+0

你使用pytest-html插件吗? –

回答

3

看起来你使用的是像pytest-html这样的插件。 如果是这种情况检查该插件的文档提供了所有的钩子。

为pytest-HTML下面是提供的钩子 您可以添加从夹具修改request.config._html.environment改变报告的环境部分:

@pytest.fixture(autouse=True) 
def _environment(request): 
    request.config._environment.append(('foo', 'bar')) 

您可以通过创建一个“额外的细节添加到HTML报告'报告对象列表。下面的示例将不同类型的使用pytest_runtest_makereport钩群众演员,可以在一个插件或conftest.py文件来实现:

import pytest 
@pytest.mark.hookwrapper 
def pytest_runtest_makereport(item, call): 
    pytest_html = item.config.pluginmanager.getplugin('html') 
    outcome = yield 
    report = outcome.get_result() 
    extra = getattr(report, 'extra', []) 
    if report.when == 'call': 
     # always add url to report 
     extra.append(pytest_html.extras.url('http://www.example.com/')) 
     xfail = hasattr(report, 'wasxfail') 
     if (report.skipped and xfail) or (report.failed and not xfail): 
      # only add additional html on failure 
      extra.append(pytest_html.extras.html('<div>Additional HTML</div>')) 
     report.extra = extra 
+0

谢谢,我试过了,它工作。但是,如果我想添加更多的HTML元素,现在呢?例如,我想添加表和列到现有的。我在哪里可以获得更多关于它的细节? – Mickstjohn09

+0

代码位于下方位置,您可以根据需要修改或覆盖功能。 'Python27 \ Lib \ site-packages \ pytest_html' –

+1

saurabh baid,确定'request.config._environment.append(('foo','bar'))''能够修改** Environment **表吗?在pytest-html的最新版本中,也没有'config'也没有'HTMLReport'有'_environment' attr –

1

UPDATE:在最新的版本中,如果你想修改环境表html报告,加到你的conftest.py下一个代码:

@pytest.fixture(scope='session', autouse=True) 
def configure_html_report_env(request) 
    request.config._metadata.update(
     {'foo': 'bar'} 
    )