Sobes.tech
Junior — Middle

Can you explain the concept of scope in test fixtures?

sobes.tech AI

Answer from AI

The scope of fixtures in tests determines how long and where the fixture is available during the test execution.

In pytest, for example, fixtures can have the following scopes:

  • function (default): the fixture is created anew for each test method or function.
  • class: the fixture is created once for the entire test class and used by all methods within.
  • module: the fixture is created once for the entire test module (file).
  • session: the fixture is created once for the entire test session.

Example of a fixture with module scope:

import pytest

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

This means that the database connection will be created once for all tests in the module, saving time and resources.

The choice of scope depends on how often resources need to be created and destroyed, and on test isolation.