Senior
What are fixtures in Pytest?
sobes.tech AI
Answer from AI
In Pytest, fixtures are special functions that allow you to prepare and provide the necessary data or state for tests. They are used to set up the environment before a test runs and to clean up afterward. Fixtures help avoid code duplication and make tests more readable and maintainable.
Fixtures are declared using the @pytest.fixture decorator and can return any objects — for example, a database connection, prepared data, mock objects, etc. Tests access fixtures through function parameters.
Example of a fixture:
import pytest
@pytest.fixture
def sample_data():
return [1, 2, 3, 4, 5]
def test_sum(sample_data):
assert sum(sample_data) == 15
Here, sample_data is a fixture that provides the test with a list of numbers.