We use fixture teardown to clean up after a test runs. This keeps tests independent and avoids leftover data or settings.
0
0
Fixture teardown (yield) in PyTest
Introduction
When you open a file in a test and need to close it afterward.
When you connect to a database and want to disconnect after the test.
When you create temporary data or settings that should be removed after testing.
When you start a server or service for a test and need to stop it afterward.
Syntax
PyTest
import pytest @pytest.fixture def resource(): # setup code setup_value = 'resource ready' yield setup_value # teardown code print('Cleaning up resource')
The code before yield runs before the test (setup).
The code after yield runs after the test (teardown).
Examples
This fixture prints 'Setup' before the test and 'Teardown' after the test.
PyTest
import pytest @pytest.fixture def sample_fixture(): print('Setup') yield 'data' print('Teardown')
This fixture opens a file before the test and closes it after the test.
PyTest
import pytest @pytest.fixture def open_file(): f = open('test.txt', 'w') yield f f.close()
Sample Program
This test uses a fixture that sets up a resource, yields it to the test, and then tears it down after the test finishes.
PyTest
import pytest @pytest.fixture def resource(): print('Setup resource') yield 'resource ready' print('Teardown resource') def test_example(resource): print(f'Test uses {resource}') assert resource == 'resource ready'
OutputSuccess
Important Notes
Always put the cleanup code after yield to ensure it runs after the test.
Teardown code runs even if the test fails or raises an error.
Using yield in fixtures helps keep setup and teardown code together for clarity.
Summary
Fixture teardown with yield runs cleanup code after a test finishes.
Setup code goes before yield, teardown code goes after.
This keeps tests clean and independent by removing temporary resources.