2016-09-20 75 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'} 
    )