Test independence means each test runs alone without relying on others. This helps find problems quickly and keeps tests simple.
Test independence in PyTest
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
PyTest
def test_example(): # Arrange # Act # Assert assert something == expected
Each test function should set up its own data or use fixtures.
Do not depend on other tests to run first or change data.
Examples
PyTest
def test_addition(): result = 2 + 3 assert result == 5
PyTest
def test_list_append(): items = [] items.append('apple') assert items == ['apple']
Sample Program
This example shows two tests using a shared list. The fixture clears the list before each test to keep them independent.
PyTest
import pytest shared_list = [] @pytest.fixture(autouse=True) def clear_list(): shared_list.clear() def test_add_item(): shared_list.append('item1') assert shared_list == ['item1'] def test_list_starts_empty(): assert shared_list == []
Important Notes
Use fixtures to set up and tear down data for each test.
Avoid sharing state between tests unless it is reset each time.
Independent tests make debugging easier and test results more reliable.
Summary
Each test should run alone without depending on others.
Use setup and cleanup to keep tests independent.
Independent tests help find bugs faster and keep tests stable.
Practice
1. Why is test independence important in pytest?
easy
Solution
Step 1: Understand test independence concept
Test independence means each test runs alone without relying on others.Step 2: Identify why independence matters
This prevents tests from failing due to side effects or order, making results reliable.Final Answer:
It ensures tests do not affect each other and run reliably alone. -> Option CQuick Check:
Test independence = tests run alone [OK]
Hint: Tests should run alone without relying on others [OK]
Common Mistakes:
- Thinking tests must share data to be efficient
- Believing tests run only if previous tests pass
- Assuming test order controls correctness
2. Which pytest feature helps keep tests independent by running setup code before each test?
easy
Solution
Step 1: Identify setup features in pytest
Pytest runs setup code before each test usingsetup_methodorsetup_function.Step 2: Understand their role in test independence
Setup prepares fresh state for each test, avoiding shared state and keeping tests independent.Final Answer:
Usingsetup_methodorsetup_function-> Option AQuick Check:
Setup before each test =setup_method/setup_function[OK]
Hint: Setup code before each test keeps tests independent [OK]
Common Mistakes:
- Confusing parameterize with setup
- Using yield_fixture to share state incorrectly
- Skipping tests does not setup state
3. Given the code below, what will be the output when running both tests?
counter = 0
def test_first():
global counter
counter += 1
assert counter == 1
def test_second():
global counter
counter += 1
assert counter == 1medium
Solution
Step 1: Analyze test_first behavior
Initially, counter=0. test_first increments to 1 and asserts counter == 1, so it passes.Step 2: Analyze test_second behavior
counter is now 1 from previous test. test_second increments to 2 and asserts counter == 1, which fails.Final Answer:
First test passes, second test fails -> Option AQuick Check:
Shared state causes second test failure [OK]
Hint: Shared global state breaks test independence [OK]
Common Mistakes:
- Assuming counter resets automatically
- Thinking both tests run with fresh state
- Ignoring global variable effects
4. Identify the problem in this pytest code that breaks test independence:
shared_list = []
def test_add_one():
shared_list.append(1)
assert len(shared_list) == 1
def test_add_two():
shared_list.append(2)
assert len(shared_list) == 1medium
Solution
Step 1: Understand shared_list usage
shared_list is defined outside tests and not reset, so it keeps growing with each test.Step 2: Identify why independence breaks
Because shared_list is not cleared, test_add_two sees length 2, but asserts length 1, causing failure.Final Answer:
shared_list is not cleared between tests causing length to grow -> Option DQuick Check:
Shared mutable state without reset breaks independence [OK]
Hint: Reset shared data between tests to keep independence [OK]
Common Mistakes:
- Assuming pytest resets global variables automatically
- Changing assertions instead of fixing state
- Confusing parallel runs with shared state issues
5. You want to ensure two pytest tests that modify a database table run independently. Which approach best maintains test independence?
hard
Solution
Step 1: Understand database state isolation
To keep tests independent, each test should not affect others' database state.Step 2: Choose best isolation method
Using a fixture that creates a transaction and rolls back after each test resets database state, ensuring independence.Final Answer:
Use a fixture to create and rollback a transaction for each test -> Option BQuick Check:
Transaction rollback per test = independence [OK]
Hint: Rollback DB changes after each test to isolate state [OK]
Common Mistakes:
- Relying on test order for correctness
- Sharing global DB connection without isolation
- Skipping tests instead of fixing independence
