How to show custom description for each test in pytest html report

2.2k views Asked by At

I am looking for a solution to include custom description for each test (I have about 15-20 tests in a test.py file). I want to show the description for each test in pytest html report. Something like "Login test" for test1, "User name input" for test2 etc. I have a conftest.py in the folder where the .py tests are present.

import pytest
from py.xml import html
@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(2, html.th('Custom Description'))

@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    custom_description = getattr(report, "custom_description", "")
    cells.insert(2, html.td(custom_description))

@pytest.fixture(scope='function')
def custom_description(request):
    return request.function.__doc__

My test function looks like this. def test_001(custom_description, request): print('This is test 1') assert True request.node.report_custom_description = "This is a login test"

def test_002(custom_description, request):
    print('This is test 2')
    assert True
    request.node.report_custom_description = "This is user name test"

The html report is showing the extra column (Custom Description) I added, but its not showing anything under that column. Its just empty. I tried removing the empty quote in custom_description = getattr(report, "custom_description", "") but that throws error.

Any help is much appreciated.

2

There are 2 answers

2
pL3b On

Is it necessary to set this description in dynamically in a test?

Please have a look at the solution based on your code that uses test docstring as a custom description:

import pytest
from py.xml import html

@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(2, html.th('Custom Description'))

@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    custom_description = getattr(report, "custom_description", "")
    cells.insert(2, html.td(custom_description))

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    outcome._result.custom_description = item.function.__doc__

Here I implement hook wrapper for hook pytest_runtest_makereport.

As stated in docs, it returns TestReport instance, so you can use a hook wrapper (generator function) that yields this instance. Then you just modify it with an item.function.__doc__ property.

Also your tests will be simpler:

def test_001():
    """This is a login test"""
    print('This is test 1')
    assert True

def test_002():
    """This is user name test"""
    print('This is test 2')
    assert True

Report: Report

0
Ram On

Found a solution to that warning. I had to decorate with @pytest.hookimpl(optionalhook=True) in both def pytest_html_results_table_header(cells) and def pytest_html_results_table_row(report, cells)