0
0
PyTesttesting~15 mins

Test independence in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify that tests run independently without relying on each other's state
Preconditions (2)
Step 1: Run test_addition which adds two numbers and checks the result
Step 2: Run test_reset which resets the calculator state
Step 3: Run test_addition again to verify it does not depend on previous test state
✅ Expected Result: Each test passes independently, no test depends on the result or state of another test
Automation Requirements - pytest
Assertions Needed:
Assert addition result is correct
Assert calculator state is reset properly
Assert tests do not share state causing failures
Best Practices:
Use fixtures to provide fresh state for each test
Avoid sharing mutable state between tests
Keep tests isolated and independent
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
{'mistake': 'Sharing a single Calculator instance across tests as a global variable', 'why_bad': "Tests can affect each other's state causing flaky or false failures", 'correct_approach': 'Use pytest fixtures to provide a fresh Calculator instance for each test'}
Modifying global or class-level variables inside tests
Relying on test execution order to pass tests
Bonus Challenge

Now add data-driven testing with 3 different addition inputs using pytest parametrize

Show Hint