0

How can I display the amount of time taken for each test executed by pytest?

I've investigated pytest-timeout, pytest-timeit, and pytest-benchmark. pytest-benchmark is closest, but requires wrapping every test manually.

The most pressing need is to figure out why testing under Py 3.x takes almost twice as long as Py 2.7. There are 231 top-level tests in the package I want to test (as identified by pytest), so wrapping all of these is not trivial.

Reece
  • 7,616
  • 4
  • 30
  • 46
  • 2
    have you checked https://stackoverflow.com/questions/27884404/printing-test-execution-times-and-pinning-down-slow-tests-with-py-test – Rajat Mishra Jul 24 '18 at 03:49
  • 1
    Have a look at https://docs.pytest.org/en/latest/usage.html#profiling-test-execution-duration – Sanju Jul 26 '18 at 14:06

1 Answers1

6

You can achieve this by autouse fixture and pytest_runtest_makereport

Add below code to your root conftest.py. It would print out test duration for every test.

@pytest.fixture(scope='function', autouse=True)
def testcase_result(request):
    print("Test '{}' STARTED".format(request.node.nodeid))
    def fin():
        print("Test '{}' COMPLETED".format(request.node.nodeid))
        print("Test '{}' DURATION={}".format(request.node.nodeid,request.node.rep_call.duration))
    request.addfinalizer(fin)


@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
    rep = __multicall__.execute()
    setattr(item, "rep_" + rep.when, rep)
    return rep

Hope it would help you !

Chanda Korat
  • 2,453
  • 2
  • 19
  • 23
  • 3
    This is a fine response and very educational. However, I think the better answer is provided in the question that others referenced re: --durations=0 (https://stackoverflow.com/questions/27884404/printing-test-execution-times-and-pinning-down-slow-tests-with-py-test). – Reece Aug 04 '18 at 19:18