Imagine you have multiple tests for a calculator app. Why should each test be independent from others?
Think about how one broken test might affect others if they depend on each other.
Test independence means tests do not rely on each other's results or data. This helps isolate failures and makes debugging easier.
Consider these two pytest tests that share a global variable. What will be the test results?
counter = 0 def test_increment(): global counter counter += 1 assert counter == 1 def test_increment_again(): global counter counter += 1 assert counter == 1
Think about the value of counter when each test runs.
The first test sets counter to 1 and passes. The second test runs after and increments counter to 2, so the assertion counter == 1 fails.
These pytest tests sometimes fail randomly. What is the main cause?
shared_list = [] def test_add_item(): shared_list.append(1) assert 1 in shared_list def test_clear_list(): shared_list.clear() assert shared_list == []
Look at the variable shared_list and how it is used.
Both tests modify the same global list. If test_add_item runs before test_clear_list, the list is cleared. But if order changes, tests may fail unpredictably.
Which pytest feature helps to create independent tests by providing fresh data for each test?
Think about how pytest can prepare data or state before each test runs.
Fixtures with function scope run before each test, giving a clean environment and avoiding shared state.
You want to verify that a test does not affect global state. Which assertion is best?
global_state = {'count': 0}
def test_modify_state():
global_state['count'] += 1
# Which assertion below best ensures test independence?Think about what value count should have if tests are independent.
If tests are independent, the global count should reset to 0 before each test. Checking it equals 0 ensures no leftover changes.