channel_t
channel_t

Reputation: 51

Basic pytest teardown that runs on test completion

I am minimally using pytest as a generic test runner for large automated integration tests against various API products at work, and I've been trying to find an equally generic example of a teardown function that runs on completion of any test, regardless of success or failure.

My typical use pattern is super linear and usually goes something like this:

def test_1():
    <logic>
    assert something

def test_2():
    <logic>
    assert something

def test_3():
    <logic>
    assert something

Occasionally, when it makes sense to do so, at the top of my script I toss in a setup fixture with an autouse argument set to "True" that runs on the launch of every script:

@pytest.fixture(scope="session", autouse=True)
def setup_something():
    testhelper = TestHelper
    testhelper.create_something(host="somehost", channel="somechannel")

def test_1():
    <logic>
    assert something

def test_2():
    <logic>
    assert something

def test_3():
    <logic>
    assert something

Up until recently, disposable docker environments have allowed me to get away with skipping the entire teardown process, but I'm in a bit of pinch where one of those is not available right now. Ideally, without diverting from the same linear pattern I've already been using, how would I implement another pytest fixture that does something like:

@pytest.fixture
def teardown():
    testhelper = TestHelper
    testhelper.delete_something(thing=something)

when the run is completed?

Upvotes: 4

Views: 5150

Answers (2)

Bruno Oliveira
Bruno Oliveira

Reputation: 15245

Every fixture may have a tear down part:

@pytest.fixture
def something(request):
   # setup code
   def finalize():
       # teardown code
   request.addfinalizer(finalize)
   return fixture_result

Or as I usually use it:

@pytest.fixture
def something():
    # setup code
    yield fixture_result
    # teardown code

Note that in pytest pre-3.0, the decorator required for the latter idiom was @pytest.yield_fixture. Since 3.0, however, one can just use the regular @pytest.fixture decorator, and @pytest.yield_fixture is deprecated.

See more here

Upvotes: 6

sax
sax

Reputation: 3796

you can use these functions in your conftest.py

def pytest_runtest_setup(item):
    pass    

def pytest_runtest_teardown(item):
    pass

see here for docs

Upvotes: 1

Related Questions