What is a fixture in pytest? What is its scope? Can a fixture be called from another fixture? What is autouse? Can parameters be passed to a fixture?
sobes.tech AI
Answer from AI
In pytest, a fixture is a function that prepares the test environment or data needed for tests. It can create objects, set up state, perform preparatory actions, and release resources after the test.
The scope of a fixture determines how often it is invoked:
- function (default) — the fixture is called for each test.
- class — the fixture is called once per test class.
- module — once per module (test file).
- package — once per package.
- session — once per entire test session.
Yes, a fixture can be called from another fixture by simply specifying its name in the function parameters. This allows building dependency chains.
The autouse=True parameter in the @pytest.fixture decorator means that the fixture will automatically apply to all tests in its scope without explicitly mentioning it in the test parameters.
In pytest, you can pass parameters to a fixture via parameterization using @pytest.mark.parametrize or by using request.param within the fixture during parameterization. This enables running tests with different data sets.
Example of a fixture with parameterization and calling another fixture:
import pytest
@pytest.fixture(scope='module')
def db_connection():
conn = create_db_connection()
yield conn
conn.close()
@pytest.fixture(params=["user1", "user2"])
def user(db_connection, request):
return db_connection.get_user(request.param)
def test_user_access(user):
assert user.has_access()
Here, user depends on db_connection, and user itself is parameterized with different values.