vendredi 6 mars 2015

Use docstrings to list tests in py.test

Here is a simple test file:



# test_single.py
def test_addition():
"Two plus two is still four"
assert 2 + 2 == 4

def test_addition2():
"One plus one is still two"
assert 1 + 1 == 2


The default output in py.test is like



$ py.test test_single.py -v
[...]
test_single.py::test_addition PASSED
test_single.py::test_addition2 PASSED


I would like to have



Two plus two is still four PASSED
One plus one is still two PASSED


i.e. use the docstrings as descriptions for the tests.


I tried to use a customization in a conftest.py file:



import pytest

@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
# execute all other hooks to obtain the report object
rep = __multicall__.execute()
if rep.when == "call":
extra = item._obj.__doc__.strip()
rep.nodeid = extra
return rep


that is close, but it repeats the filename on every line:



$ py.test test_single.py
======================================================================================== test session starts =========================================================================================
platform darwin -- Python 2.7.7 -- py-1.4.26 -- pytest-2.6.4
plugins: greendots, osxnotify, pycharm
collected 2 items

test_single.py
And two plus two is still four .
test_single.py
And one plus one is still two .

====================================================================================== 2 passed in 0.11 seconds ======================================================================================


How can I avoid the lines with test_single.py in the output, or maybe print it only once?


Looking into the source of py.test and some of its plugins did not help.


I am aware of the pytest-spec plugin, but that uses the function's name as a description. I don't want to write def test_two_plus_two_is_four().


Aucun commentaire:

Enregistrer un commentaire