Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Fixtures

Yield Fixtures and Cleanup

Use yield in pytest fixtures to run teardown code after a test, learn what happens when setup or a test fails, order of cleanup, and the addfinalizer alternative.

Many resources must be cleaned up after use: a file opened for writing, a database connection, a temporary folder, a running server, a patched global setting. A test that leaves such things behind pollutes the next test, and the failures it causes show up far away from the real cause.

pytest solves this with the yield fixture. Instead of return, you yield the value. Everything before the yield is setup; everything after it is teardown, and pytest guarantees the teardown runs after the test has finished, whether it passed or failed.

return versus yield

Python A yield fixture with teardown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The SETUP and TEARDOWN lines show that the connection is opened and closed around each test. The code after yield is your teardown, and the statements after it run in a finally-like fashion: no try/finally is needed in the fixture.

sequenceDiagram
    participant P as pytest
    participant F as fixture
    participant T as test
    P->>F: run until yield (setup)
    F-->>P: yielded value
    P->>T: call test with the value
    T-->>P: pass or fail
    P->>F: resume after yield (teardown)

Teardown runs after the test, even if the test failed.

Cleanup happens even when the test fails

That guarantee is the whole point. See it in action with a failing test:

Python Teardown runs after a failing test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first test fails, yet the second shows that teardown ran. (Tests normally should not depend on each other like this; it is used here only to make the cleanup visible.)

What if setup itself fails?

If an exception is raised before the yield, the fixture never produced a value. pytest reports an error (not a failure) for the test and does not run the code after yield, because the generator never got there:

Python Errors in setup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The report says ERROR at setup of test_uses_broken. That wording tells you immediately that the problem is in a fixture, not in the test body.

When a fixture does several things before the yield, a failure halfway can leave earlier steps uncleaned. Keep setup simple, or split it into several fixtures so each can clean up on its own.

Teardown order

Fixtures are torn down in the reverse order of setup, like nested with blocks: the last one created is the first one cleaned. This matters when one resource depends on another (close the cursor before the connection).

Python Reverse order teardown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You will see SETUP server, SETUP client, then TEARDOWN client, then TEARDOWN server.

yield with a with statement

Because a fixture is a generator, you can wrap the yield in with, and the context manager closes the resource for you:

Python
@pytest.fixture
def log_file(tmp_path):
    with open(tmp_path / "app.log", "w") as handle:
        yield handle              # file closes when the fixture ends

This is the idiomatic way to write most cleanup. It uses the built-in tmp_path fixture, which you will meet shortly.

addfinalizer: the alternative

A fixture can also register cleanup functions through the request object. This predates yield and is still useful when a fixture creates several things and needs to clean each regardless of whether later steps succeed:

Python request.addfinalizer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Finalizers also run in reverse order of registration. With yield you can achieve the same with several nested try/finally or a single contextlib.ExitStack. For new code, prefer yield; use addfinalizer when it genuinely reads better.

Teardown that can fail

If code after yield raises, pytest reports an error at teardown for that test, even though the test itself passed. Keep cleanup code simple and tolerant: for example, delete a file with missing_ok=True.

Python
@pytest.fixture
def scratch_file(tmp_path):
    path = tmp_path / "scratch.txt"
    path.write_text("data")
    yield path
    path.unlink(missing_ok=True)    # tolerate tests that already deleted it

Safe patterns

Situation Pattern
open and close one resource with around yield
several resources one fixture each, or ExitStack
undo a global change prefer the built-in monkeypatch fixture (see monkeypatch)
temporary files use tmp_path instead of cleaning by hand
expensive setup shared by many tests scope="module" or "session" and yield once

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a yield fixture, which code runs after the test finishes?

    The code after yield is the teardown; pytest resumes the generator once the test is done.
  2. 2. If a test fails, does the code after yield still run?

    pytest guarantees teardown even after a failure.
  3. 3. A fixture raises an exception before its yield. How does pytest report the test?

    Problems outside the test body are errors. The code after yield does not run because setup never finished.
  4. 4. In what order are fixtures torn down?

    Like nested with-blocks, the last fixture set up is the first to be cleaned up.

Summary

  • Use yield value in a fixture: code before it is setup, code after it is teardown.
  • Teardown runs after the test, whether it passed or failed.
  • An exception during setup is reported as an error and skips the rest of that fixture.
  • Fixtures are torn down in reverse order of setup.
  • request.addfinalizer is an older alternative; prefer yield and with for readability.
  • Keep teardown code tolerant so cleanup problems do not hide real test results.

Next: conftest.py and Sharing Fixtures