9

I want to get the test name and test result during runtime.

I have setup and tearDown methods in my script. In setup, I need to get the test name, and in tearDown I need to get the test result and test execution time.

Is there a way I can do this?

jpyams
  • 4,030
  • 9
  • 41
  • 66
user1822881
  • 203
  • 1
  • 3
  • 7

3 Answers3

15

You can, using a hook.

I have these files in my test directory:

./rest/
├── conftest.py
├── __init__.py
└── test_rest_author.py

In test_rest_author.py I have three functions, startup, teardown and test_tc15, but I only want to show the result and name for test_tc15.

Create a conftest.py file if you don't have one yet and add this:

import pytest
from _pytest.runner import runtestprotocol

def pytest_runtest_protocol(item, nextitem):
    reports = runtestprotocol(item, nextitem=nextitem)
    for report in reports:
        if report.when == 'call':
            print '\n%s --- %s' % (item.name, report.outcome)
    return True

The hook pytest_runtest_protocol implements the runtest_setup/call/teardown protocol for the given test item, including capturing exceptions and calling reporting hooks. It is called when any test finishes (like startup or teardown or your test).

If you run your script you can see the result and name of the test:

$ py.test ./rest/test_rest_author.py
====== test session starts ======
/test_rest_author.py::TestREST::test_tc15 PASSED
test_tc15 --- passed
======== 1 passed in 1.47 seconds =======

See also the docs on pytest hooks and conftest.py.

jpyams
  • 4,030
  • 9
  • 41
  • 66
  • This unfortuantely didn't help me enough. I have a finalizer to a fixture, and this finalizer may mark the outcome as failed. But the finalizer is executed before pytest_runtest_protocol – Kjeld Flarup Mar 20 '18 at 13:08
1

unittest.TestCase.id() this will return the complete Details including class name , method name . From this we can extract test method name. Getting the results during can be achieved by checking if there any exceptions in executing the test. If the test fails then there wil be an exception if sys.exc_info() returns None then test is pass else test will be fail.

user1822881
  • 203
  • 1
  • 3
  • 7
0

Using pytest_runtest_protocol as suggested with fixture marker solved my problem. In my case it was enough just to use reports = runtestprotocol(item, nextitem=nextitem) within my pytest html fixture. So to finalize the item element contains the information you need.

Many Thanks.

H3tz
  • 1
  • 2