Middle+
What is a fixture in pytest?
sobes.tech AI
Answer from AI
A fixture in pytest is a function that prepares and provides the necessary resources or state for tests before execution and can perform cleanup afterward. Fixtures help avoid code duplication and simplify environment setup for tests.
Example of a fixture that creates a temporary file for testing:
import pytest
@pytest.fixture
def temp_file(tmp_path):
file = tmp_path / "test.txt"
file.write_text("hello")
return file
def test_read_file(temp_file):
content = temp_file.read_text()
assert content == "hello"
Here, the temp_file fixture creates a file with content that is then used in the test.