Verify that tests run independently without relying on each other's state
Preconditions (2)
✅ Expected Result: Each test passes independently, no test depends on the result or state of another test
Jump into concepts and practice - no test required
import pytest class Calculator: def __init__(self): self.value = 0 def add(self, x): self.value += x return self.value def reset(self): self.value = 0 @pytest.fixture def calculator(): return Calculator() def test_addition(calculator): result = calculator.add(5) assert result == 5 def test_reset(calculator): calculator.add(10) calculator.reset() assert calculator.value == 0 def test_addition_again(calculator): result = calculator.add(3) assert result == 3
The Calculator class simulates a simple calculator with add and reset methods.
The calculator fixture creates a new Calculator instance for each test, ensuring fresh state.
test_addition adds 5 and checks the result is 5.
test_reset adds 10, resets, and checks the value is 0.
test_addition_again adds 3 and checks the result is 3, verifying no leftover state from previous tests.
This setup ensures tests are independent and do not affect each other.
Now add data-driven testing with 3 different addition inputs using pytest parametrize
setup_method or setup_function.setup_method or setup_function -> Option Asetup_method/setup_function [OK]counter = 0
def test_first():
global counter
counter += 1
assert counter == 1
def test_second():
global counter
counter += 1
assert counter == 1shared_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) == 1