In pytest, why is it important to avoid test interdependence?
Think about what happens if one test fails and others rely on it.
Tests that depend on each other can cause cascading failures, making it hard to find the real problem. Independent tests help isolate issues.
What will be the output status of the second test when running pytest on this code?
shared_list = [] def test_add_item(): shared_list.append(1) assert len(shared_list) == 1 def test_check_item(): assert shared_list == [1]
Consider the order pytest runs tests and the shared state.
Because test_add_item runs first and adds 1 to shared_list, test_check_item sees [1] and passes. But this creates interdependence on test order.
Which assertion best avoids test interdependence by ensuring each test starts with a clean state?
import pytest @pytest.fixture(autouse=True) def clear_list(): global shared_list shared_list = [] shared_list = [] def test_one(): shared_list.append(5) # Assertion here def test_two(): # Assertion here
Think about what the fixture does before each test.
The fixture resets shared_list to empty before each test. test_one adds 5, so it expects [5]. test_two expects empty list because fixture cleared it.
Given these pytest tests, why might test_b fail if run alone?
shared_counter = 0 def test_a(): global shared_counter shared_counter += 1 assert shared_counter == 1 def test_b(): assert shared_counter == 1
Think about the initial value of shared_counter and test order.
test_b expects shared_counter to be 1, but if run alone, shared_counter is 0. This shows test_b depends on test_a's side effect.
Which pytest feature is best to ensure tests do not share state and remain independent?
Think about how pytest can reset or provide fresh data for each test.
Fixtures with function scope run before each test, giving a clean state and avoiding interdependence. Global variables and fixed order cause dependencies.