0
0
PyTesttesting~15 mins

Avoiding test interdependence in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify independent test execution in pytest
Preconditions (2)
Step 1: Create two test functions: test_add and test_subtract
Step 2: In test_add, call add(2, 3) and verify the result is 5
Step 3: In test_subtract, call subtract(5, 3) and verify the result is 2
Step 4: Run tests individually and together to ensure no test depends on another
✅ Expected Result: Both tests pass independently with no shared state or order dependency
Automation Requirements - pytest
Assertions Needed:
assert add(2, 3) == 5
assert subtract(5, 3) == 2
Best Practices:
Use fresh state for each test
Avoid sharing variables or state between tests
Do not rely on test execution order
Use fixtures with scope='function' if setup is needed
Automated Solution
PyTest
import pytest

# Simple calculator functions
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

# Test functions

def test_add():
    result = add(2, 3)
    assert result == 5

def test_subtract():
    result = subtract(5, 3)
    assert result == 2

This test script defines two simple functions: add and subtract. Each test function calls one of these and asserts the expected result.

Each test is independent: they do not share variables or state. This means you can run test_add or test_subtract alone or together in any order, and they will pass.

This avoids test interdependence, which is important because tests that depend on each other can cause confusing failures and make debugging hard.

Common Mistakes - 3 Pitfalls
Sharing variables between tests
Relying on test execution order
Using global state without reset
Bonus Challenge

Now add data-driven testing with 3 different input pairs for add and subtract functions

Show Hint