0
0
PyTesttesting~10 mins

Handling shared resources in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks that a shared resource (a simple counter) is correctly reset before each test to avoid interference between tests.

Test Code - pytest
PyTest
import pytest

shared_counter = {'count': 0}

@pytest.fixture(autouse=True)
def reset_counter():
    shared_counter['count'] = 0


def test_increment_once():
    shared_counter['count'] += 1
    assert shared_counter['count'] == 1

def test_increment_twice():
    shared_counter['count'] += 2
    assert shared_counter['count'] == 2
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test runner starts and loads the test moduleshared_counter dictionary initialized with count = 0-PASS
2Before test_increment_once runs, reset_counter fixture sets shared_counter['count'] to 0shared_counter['count'] is 0-PASS
3test_increment_once increments shared_counter['count'] by 1shared_counter['count'] is 1assert shared_counter['count'] == 1PASS
4Before test_increment_twice runs, reset_counter fixture sets shared_counter['count'] to 0 againshared_counter['count'] reset to 0-PASS
5test_increment_twice increments shared_counter['count'] by 2shared_counter['count'] is 2assert shared_counter['count'] == 2PASS
Failure Scenario
Failing Condition: If the reset_counter fixture is missing or not autoused, shared_counter is not reset between tests
Execution Trace Quiz - 3 Questions
Test your understanding
What does the reset_counter fixture do before each test?
ADeletes the shared_counter dictionary
BSets shared_counter['count'] to 0
CIncrements shared_counter['count'] by 1
DDoes nothing
Key Result
Always reset or isolate shared resources before each test to ensure tests do not affect each other and results stay reliable.