6

By default pytest use test function names or test files names in pytest reports

is there any Best way to add test description (Long test name) in the report with out renaming the files or functions using pytest?

Can we do this by updating the testcase name at run-time like ?

  1. request.node.name
request.node.name = "Very Very Very Very Very long long long long name name name name"
  1. Description after test-name
def test_ok():
"""Very Very Very Very Very long long long long name name name name"""
    print("ok")
gdm
  • 7,647
  • 3
  • 41
  • 71
Lava Sangeetham
  • 2,943
  • 4
  • 38
  • 54

1 Answers1

12

Using the pytest_runtest_makereport hook, the reported name can be adjusted for each test. (Note that hooks must be placed within a plugin, or a conftest.py)

# conftest.py

import pytest

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()

    test_fn = item.obj
    docstring = getattr(test_fn, '__doc__')
    if docstring:
        report.nodeid = docstring


# test_it.py

def test_ok():
    """Very Very Very Very Very long long long long name name name name"""
    print("ok")

This will produce output similar to:

tests/test_stuff.py::test_ok 
Very Very Very Very Very long long long long name name name name <- tests/test_stuff.py PASSED [100%]

See "hookwrapper: executing around other hooks" for more info on the outcome = yield and outcome.get_result() business.

Romain
  • 19,910
  • 6
  • 56
  • 65
theY4Kman
  • 5,572
  • 2
  • 32
  • 38
  • The above function is changing only report description. but still it is printing as "tests/test_stuff.py::test_ok " Is it possible to change the testcase name? – Lava Sangeetham Jan 31 '20 at 23:21
  • 1
    Unfortunately this approach doesn't work with xdist. [An assertion in the xdist code](https://github.com/pytest-dev/pytest-xdist/blob/348a9567242bdf9920799f548fb40a057573e3bf/src/xdist/remote.py#L120) fails if `report.nodeid` is changed. – John29 Jul 14 '21 at 21:24
  • @John29 [Here](https://stackoverflow.com/a/61002385/3534491) is an approach that does not modify nodeid. – Marduk Feb 27 '22 at 10:22
  • @LavaSangeetham Check [pytest-spec](https://pypi.org/project/pytest-spec/) – Marduk Feb 27 '22 at 10:24