0
0
PyTesttesting~15 mins

Shared expensive resource patterns in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify shared expensive resource is initialized once and reused
Preconditions (2)
Step 1: Run the test suite with three test functions that use the shared database connection fixture
Step 2: Each test function should perform a simple query using the shared connection
Step 3: Observe the initialization logs or counters to confirm the connection is created only once
✅ Expected Result: The database connection is initialized only once before any tests run and reused by all test functions, ensuring faster test execution and resource efficiency
Automation Requirements - pytest
Assertions Needed:
Assert that the expensive resource (database connection) is created only once
Assert that each test function can use the shared resource successfully
Best Practices:
Use pytest fixtures with scope='session' to share expensive resources
Use explicit teardown to close the resource after all tests
Avoid global variables; use fixture parameters
Use logging or counters to verify single initialization
Automated Solution
PyTest
import pytest

class ExpensiveDBConnection:
    def __init__(self):
        self.connected = False
        self.init_count = 0

    def connect(self):
        if not self.connected:
            # Simulate expensive connection setup
            self.init_count += 1
            self.connected = True

    def query(self, sql):
        if not self.connected:
            raise Exception("Not connected")
        return f"Result for: {sql}"

    def close(self):
        self.connected = False

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


def test_query_one(db_connection):
    result = db_connection.query("SELECT 1")
    assert result == "Result for: SELECT 1"


def test_query_two(db_connection):
    result = db_connection.query("SELECT 2")
    assert result == "Result for: SELECT 2"


def test_single_initialization(db_connection):
    # The init_count should be 1 because connection is shared
    assert db_connection.init_count == 1

The ExpensiveDBConnection class simulates a costly resource with a connection count.

The db_connection fixture uses scope='session' to ensure it runs once per test session, sharing the resource.

Each test uses the fixture to run queries, verifying the resource works.

The test_single_initialization asserts the connection was initialized only once, confirming the shared pattern.

Teardown closes the connection after all tests.

Common Mistakes - 3 Pitfalls
{'mistake': 'Using fixture with default function scope causing resource to initialize before each test', 'why_bad': 'This defeats the purpose of sharing an expensive resource and slows down tests.', 'correct_approach': "Set fixture scope to 'session' or 'module' to share the resource across tests."}
Not properly closing or cleaning up the resource after tests
Using global variables to track resource state
Bonus Challenge

Now add data-driven testing with 3 different SQL queries using the shared database connection fixture

Show Hint