Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether test has failed within fixture

Tags:

testing

pytest

I am debugging an intermittent test failure. For this purposes I want to dump a lot of debug information if a test failed. Dumping debug stuff is quite slow process which produces a lot of data, so I do not want to do this for every test.

I am using pytest and yield autouse fixture should work great

@pytest.yield_fixture(scope="function", autouse=True)
def dump_on_failue(request):
    prepare_debug_dump()

    yield

    if test_failed(request):
        debug_dump()

The problem is that I can't figure out how do I detect whether test has failed or not. There was a questions already and even note on pytest website:

    if request.node.rep_setup.failed:
        print ("setting up a test failed!", request.node.nodeid)
    elif request.node.rep_setup.passed:
        if request.node.rep_call.failed:
            print ("executing test failed", request.node.nodeid)

Unfortunately this code does not work anymore. There are no rep_setup and rep_calls symbols in node object. I tried to dig request and node object, but no luck.

Anybody knows how to detect whether test failed?

like image 526
Oleksandr Masliuchenko Avatar asked Jul 11 '16 11:07

Oleksandr Masliuchenko


1 Answers

There are no rep_setup and rep_calls symbols in node object.

No.rep_setup and rep_calls symbols are still there.

Add this code into your root conftest.py. It will check pass/fail for every test function.

import pytest

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

@pytest.fixture(scope='function', autouse=True)
def test_debug_log(request):
    def test_result():
        if request.node.rep_setup.failed:
            print ("setting up a test failed!", request.node.nodeid)
        elif request.node.rep_setup.passed:
            if request.node.rep_call.failed:
                print ("executing test failed", request.node.nodeid)
    request.addfinalizer(test_result)
like image 131
Chanda Korat Avatar answered Nov 07 '22 15:11

Chanda Korat