Course contentsShow
← Python
Lesson 753 of 1,06012. Testing and DebuggingFree lesson

Optimizing Test Execution with Fixture Scoping

Control the lifecycle of your fixtures by applying function, class, module, or session scopes to balance test isolation and execution performance.

In this lesson, you will learn how to balance test isolation and performance by controlling how often your pytest fixtures are created and destroyed using scoping.

The Problem with Default Scopes

By default, pytest fixtures have a function scope, meaning a new instance is created for every single test function that requests it. While this ensures perfect isolation, it becomes a bottleneck if your fixture performs expensive operations, such as connecting to a database, initializing a heavy machine learning model, or loading a massive dataset into memory.

Controlling the Lifecycle

You can optimize your test suite by changing the scope parameter in the @pytest.fixture decorator. Pytest provides four levels:

  1. function (default): Created once per test function.
  2. class: Created once per test class.
  3. module: Created once per module (file).
  4. session: Created once per test session.

By moving an expensive setup to a session scope, you pay the "cost" of creation only once, and all subsequent tests share the same instance.

Practical Example

Consider a database connection that takes two seconds to establish. If you have 50 tests, using the default scope results in 100 seconds of setup time. By changing the scope, you reduce this to just two seconds:

import pytest

@pytest.fixture(scope="session")
def db_connection():
    # This setup logic runs exactly once for the entire session
    connection = connect_to_expensive_db()
    yield connection
    connection.close()

def test_user_query(db_connection):
    assert db_connection.get_user(1) == "Alice"

def test_product_query(db_connection):
    assert db_connection.get_product(50) == "Laptop"

Finding the Balance

When you broaden the scope, you lose some isolation. If test_user_query modifies the state of the database, test_product_query will inherit that modified state. Always ensure that when you increase the scope for performance, your tests are either read-only or include a cleanup step (like a teardown) to reset the state. If tests interfere with one another, revert the scope to ensure reliability.

Key Takeaway: Use the scope parameter in your fixtures to cache expensive resources, choosing the broadest scope possible that doesn't compromise test independence.