Sobes.tech
Senior

What is a fixture in pytest? How do you implement teardown?

sobes.tech AI

Answer from AI

In pytest, a fixture is a function that provides prepared data or environment for tests. It helps avoid code duplication and manage setup and cleanup of resources.

To implement teardown (cleanup after a test) in a fixture, a construct with the yield statement is used:

import pytest

@pytest.fixture
def resource():
    # setup
    res = acquire_resource()
    yield res
    # teardown
    release_resource(res)

When a test uses this fixture, the code before yield runs before the test, and the code after yield runs after the test completes, even if the test fails.

You can also use request.addfinalizer to register a cleanup function, but yield is considered a more convenient and readable way.