Junior — Middle
Could you explain what is meant by a fixture in the pytest library?
sobes.tech AI
Answer from AI
In pytest, a fixture is a special function that prepares the test environment and provides tests with necessary data or objects. Fixtures help avoid code duplication and enable reuse of setup.
For example, a fixture can create a database connection, start a server, or generate test data, and then automatically clean up resources after the test.
Example of a fixture:
import pytest
@pytest.fixture
def sample_list():
return [1, 2, 3]
def test_sum(sample_list):
assert sum(sample_list) == 6
Here, sample_list is a fixture that is passed to the test as a parameter.