Test Overview
This test demonstrates how to use a shared expensive resource in pytest using a fixture with module scope. It verifies that the resource is created once and reused across multiple tests.
Jump into concepts and practice - no test required
This test demonstrates how to use a shared expensive resource in pytest using a fixture with module scope. It verifies that the resource is created once and reused across multiple tests.
import pytest @pytest.fixture(scope="module") def expensive_resource(): print("Setting up expensive resource") resource = {"data": [1, 2, 3]} yield resource print("Tearing down expensive resource") def test_resource_usage_1(expensive_resource): assert expensive_resource["data"] == [1, 2, 3] def test_resource_usage_2(expensive_resource): assert sum(expensive_resource["data"]) == 6
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and discovers tests | pytest ready to run tests test_resource_usage_1 and test_resource_usage_2 | — | PASS |
| 2 | Setup fixture 'expensive_resource' before first test | Prints 'Setting up expensive resource', resource dictionary created | — | PASS |
| 3 | Run test_resource_usage_1 using shared resource | Test accesses resource data [1, 2, 3] | Assert resource data equals [1, 2, 3] | PASS |
| 4 | Run test_resource_usage_2 using same shared resource | Test accesses resource data [1, 2, 3] | Assert sum of resource data equals 6 | PASS |
| 5 | Teardown fixture 'expensive_resource' after all tests in module | Prints 'Tearing down expensive resource' | — | PASS |
scope='module' when dealing with expensive resources?scope='module' run once per module, not per test function.session scope runs the fixture setup once for the entire test session.@pytest.fixture(scope='session'), which is correct for this purpose.@pytest.fixture(scope='module')
def resource():
print('Setup resource')
yield
print('Cleanup resource')
def test_one(resource):
print('Test one running')
def test_two(resource):
print('Test two running')scope='module', setup runs once before any tests in the module, and cleanup runs after all tests finish.@pytest.fixture(scope='class')
def setup_resource():
resource = open('file.txt')
yield resource
resource.close()
def test_example(setup_resource):
assert setup_resource.readable()session scope to cover all tests.yield allows cleanup code after tests; calling conn.reset() before conn.close() resets the connection properly.