Sobes.tech
Junior — Middle

Can you explain what the term 'scope' means in the context of fixtures?

sobes.tech AI

Answer from AI

In the context of fixtures (for example, in pytest), the term "scope" defines the visibility and lifetime of a fixture — that is, how often it is created and destroyed.

Main scope options:

  • function (default): the fixture is recreated for each test function.
  • class: the fixture is created once per test class.
  • module: the fixture is created once per module (test file).
  • session: the fixture is created once per test session.

For example, a fixture with scope='module' will be initialized once before all tests in the module run and destroyed after they finish. This is useful for expensive operations that can be reused.

Example:

import pytest

@pytest.fixture(scope='module')
def db_connection():
    conn = create_connection()
    yield conn
    conn.close()