Junior — Middle
Have you worked with the scope mechanism fixture in testing frameworks?
sobes.tech AI
Answer from AI
In the pytest testing framework in Python, the fixture scope mechanism determines how long a fixture lives and when it is created and destroyed. The main scope levels are:
- function (default): the fixture is created for each test separately.
- class: the fixture is created once for the entire test class.
- module: the fixture is created once for the entire module (test file).
- session: the fixture is created once for the entire test session.
Example:
import pytest
@pytest.fixture(scope="module")
def db_connection():
conn = create_connection()
yield conn
conn.close()
def test_query1(db_connection):
assert db_connection.query("SELECT 1") == 1
def test_query2(db_connection):
assert db_connection.query("SELECT 2") == 2
Here, db_connection is created once per module and used in multiple tests, which saves resources and time.