Middle
What is a fixture in pytest?
sobes.tech AI
Answer from AI
In pytest, a fixture is a function that prepares and provides the necessary resources or data for tests. It helps avoid code duplication and manage the state of the test environment.
An example of a fixture that creates a temporary file:
import pytest
@pytest.fixture
def temp_file(tmp_path):
file = tmp_path / "test.txt"
file.write_text("hello")
return file
def test_read(temp_file):
content = temp_file.read_text()
assert content == "hello"
Fixtures can have different scopes (function, module, session), which allows flexible management of resource lifetimes.