0
0
PyTesttesting~5 mins

Shared expensive resource patterns in PyTest

Choose your learning style9 modes available
Introduction

Sometimes tests need to use a resource that takes a long time to set up. Sharing this resource helps tests run faster and saves effort.

When multiple tests need a database connection that takes time to create.
When tests require a web server to be running before they start.
When loading a large file or dataset that many tests will use.
When setting up hardware or external devices that are costly to initialize.
Syntax
PyTest
import pytest

@pytest.fixture(scope="module")
def expensive_resource():
    print("Setting up resource")
    resource = "Expensive setup"
    yield resource
    print("Tearing down resource")

Use scope="module" or scope="session" to share the resource across tests.

The yield keyword lets you run setup code before tests and cleanup code after.

Examples
This fixture creates a database connection once per test session and closes it after all tests finish.
PyTest
import pytest

@pytest.fixture(scope="session")
def db_connection():
    print("Connect to DB")
    conn = "DB Connection"
    yield conn
    print("Close DB Connection")
This fixture starts a web server once per module and stops it after all tests in that module run.
PyTest
import pytest

@pytest.fixture(scope="module")
def web_server():
    print("Start server")
    server = "Running server"
    yield server
    print("Stop server")
Sample Program

This example shows two tests sharing one expensive resource setup. The setup runs once before both tests, and cleanup runs after both finish.

PyTest
import pytest

@pytest.fixture(scope="module")
def expensive_resource():
    print("Setup expensive resource")
    resource = "Resource Ready"
    yield resource
    print("Cleanup expensive resource")

def test_one(expensive_resource):
    print(f"Test one uses {expensive_resource}")
    assert expensive_resource == "Resource Ready"

def test_two(expensive_resource):
    print(f"Test two uses {expensive_resource}")
    assert expensive_resource == "Resource Ready"
OutputSuccess
Important Notes

Sharing resources reduces test time but be careful to avoid tests changing shared data.

Use scope="function" if you want a fresh resource for each test.

Always clean up resources to avoid side effects on other tests.

Summary

Use pytest fixtures with scopes to share expensive resources.

Setup runs once per scope, saving time.

Cleanup runs after all tests using the resource finish.