Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyTest skip module_teardown()

I have following code in my tests module

def teardown_module():
    clean_database()
def test1(): pass
def test2(): assert 0

and I want teardown_module() (some cleanup code) to be called only if some test failed. Otherwise (if all passed) this code shouldn't have to be called. Can I do such a trick with PyTest?

like image 537
Most Wanted Avatar asked Oct 29 '25 16:10

Most Wanted


1 Answers

You can. But it is a little bit of a hack. As written here: http://pytest.org/latest/example/simple.html#making-test-result-information-available-in-fixtures you do the following, to set up an attribute for saving the status of each phase of the testcall:

# content of conftest.py
import pytest
@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
    rep = __multicall__.execute()
    setattr(item, "rep_" + rep.when, rep)
    return rep

and in the fixture you just examine the condition on those attributes like this:

import pytest
@pytest.yield_fixture(scope="module", autouse=True)
def myfixture(request):
    print "SETUP"
    yield
    # probably should not use "_collected" to iterate over test functions
    if any(call.rep_call.outcome != "passed" for call in request.node._collected):
        print "TEARDOWN"

This way if any of the tests associated with that module fixture is not "passed" (so "failed" or "skipped") then the condition holds.

like image 88
ntki Avatar answered Oct 31 '25 05:10

ntki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!