4

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?

channel_t
  • 51
  • 1
  • 3

2 Answers2

6

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

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Bruno Oliveira
  • 13,694
  • 5
  • 43
  • 41
1

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

sax
  • 3,708
  • 19
  • 22