0
0
PyTesttesting~10 mins

Test independence in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test suite demonstrates test independence by ensuring each test runs separately without relying on shared state. It verifies that modifying data in one test does not affect others.

Test Code - pytest
PyTest
import pytest

@pytest.fixture
 def sample_list():
     return [1, 2, 3]

def test_append_item(sample_list):
    sample_list.append(4)
    assert sample_list == [1, 2, 3, 4]

def test_original_list_unchanged(sample_list):
    assert sample_list == [1, 2, 3]
Execution Trace - 3 Steps
StepActionSystem StateAssertionResult
1Test runner starts and collects testsNo tests executed yet-PASS
2Runs test_append_item with fresh sample_list fixturesample_list = [1, 2, 3]Check sample_list after append is [1, 2, 3, 4]PASS
3Runs test_original_list_unchanged with fresh sample_list fixturesample_list = [1, 2, 3]Check sample_list is still [1, 2, 3]PASS
Failure Scenario
Failing Condition: If sample_list fixture is shared and modified by test_append_item, test_original_list_unchanged will fail
Execution Trace Quiz - 3 Questions
Test your understanding
Why does test_original_list_unchanged pass after test_append_item modifies the list?
ABecause pytest fixtures provide a fresh list for each test
BBecause the list is reset manually in the second test
CBecause the tests run in parallel and do not affect each other
DBecause the list is immutable
Key Result
Always design tests so they do not depend on each other's data or state. Use fixtures or setup methods that provide fresh data for each test to ensure reliability and easier debugging.