Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Pytest & fixturesMiddleVery commonPractical

What is a pytest fixture, and how does its `scope` argument control how often it runs?

Answer

A pytest fixture is a function decorated with `@pytest.fixture` that provides setup (and, after a `yield`, teardown) for tests that declare it as a parameter by name; pytest resolves and injects it automatically without an explicit call. The `scope` argument (`function`, the default, `class`, `module`, `package`, or `session`) controls how many times the fixture actually runs versus how many tests share the same instance: a `session`-scoped fixture runs once for the entire test run and is shared by every test that requests it, which is essential for expensive setup like a database connection, while `function` scope reruns fresh setup and teardown for every single test to guarantee isolation.

Strong answer includes

  • a decorated function providing setup, optionally teardown after yield, injected by parameter name
  • scope controls how many tests share one instance of the fixture
  • session scope for expensive shared setup, function scope for full isolation

Practical example

Python example
@pytest.fixture(scope="session")
def db_connection():
    conn = connect()
    yield conn
    conn.close()

opens one database connection for the whole test suite instead of reconnecting before every single test.

#pytest#testing

Sources

pytest documentationpytest · Fixture scope, parametrization, markers and plugin architectureunittest — Unit testing frameworkPython Software Foundation · Baseline test-case, mock and assertion semantics shared across Python test tooling