0
0
PyTesttesting~10 mins

Shared expensive resource patterns in PyTest - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - pytest
PyTest
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
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test runner starts and discovers testspytest ready to run tests test_resource_usage_1 and test_resource_usage_2-PASS
2Setup fixture 'expensive_resource' before first testPrints 'Setting up expensive resource', resource dictionary created-PASS
3Run test_resource_usage_1 using shared resourceTest accesses resource data [1, 2, 3]Assert resource data equals [1, 2, 3]PASS
4Run test_resource_usage_2 using same shared resourceTest accesses resource data [1, 2, 3]Assert sum of resource data equals 6PASS
5Teardown fixture 'expensive_resource' after all tests in modulePrints 'Tearing down expensive resource'-PASS
Failure Scenario
Failing Condition: Fixture setup fails or resource data is incorrect
Execution Trace Quiz - 3 Questions
Test your understanding
When is the 'expensive_resource' fixture set up in this test pattern?
ABefore each test function
BOnce before all tests in the module
CAfter each test function
DOnly if a test fails
Key Result
Using a fixture with module scope allows sharing an expensive resource setup once for multiple tests, improving test speed and resource management.