Middle
Tell us about the scope of fixtures in pytest.
sobes.tech AI
Answer from AI
In pytest, fixtures can have different scopes that determine their lifespan and scope of action:
- function (default) — the fixture is recreated for each test function.
- class — the fixture is created once for the entire test class.
- module — the fixture is created once for the entire module (test file).
- package — the fixture is created once per package (directory with init.py).
- session — the fixture is created once for the entire test session.
For example, if you need to initialize a database once for the entire module, you can set the scope to module:
import pytest
@pytest.fixture(scope="module")
def db_connection():
conn = create_db_connection()
yield conn
conn.close()
This helps optimize test execution time and manage resources more efficiently.