Sobes.tech
Junior — Middle

Can you explain what Scope means in the context of PyTest and how it affects test execution?

sobes.tech AI

Answer from AI

In PyTest, the scope parameter defines the lifetime (lifecycle) of a fixture — that is, how long it will be created and used in tests.

Main scope values:

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

For example, if a fixture has scope="module", it is initialized once before all tests in the module run and destroyed after they complete. This saves time and resources, especially if the fixture creates, for example, a database connection or server.

Example of a fixture with scope:

import pytest

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

Thus, scope affects test performance and isolation, allowing control over how often resources are created and destroyed.

Can you explain what Scope means in the context of… - sobes.tech