Skip to content

Keep higher-scoped fixtures alive across re-runs of failed subtests - #357

Open
teddytennant wants to merge 1 commit into
pytest-dev:masterfrom
teddytennant:fix-subtest-premature-teardown
Open

Keep higher-scoped fixtures alive across re-runs of failed subtests#357
teddytennant wants to merge 1 commit into
pytest-dev:masterfrom
teddytennant:fix-subtest-premature-teardown

Conversation

@teddytennant

Copy link
Copy Markdown
Contributor

Follow-up to #351, the second of the two leaks I mentioned there. Independent of #356, though both touch the same condition in pytest_runtest_teardown, so whichever lands second wants a one line rebase. Happy to do it.

A call phase that fails through subtests only leaves the call report itself passing, so every entry in _test_failed_statuses is false. pytest_runtest_teardown reads that as a finished test and lets the module, class and session finalizers run, while _should_not_rerun does count the failed subtests and re-runs the test anyway. The higher-scoped fixtures are torn down and set up again on every attempt:

@pytest.fixture(scope="module", autouse=True)
def module_fixture():
    print("module setup")
    yield
    print("module teardown")

attempts = []

def test_subtests(subtests):
    attempts.append(1)
    with subtests.test("fails twice"):
        assert len(attempts) > 2

With --reruns 3 that prints three setups and three teardowns. The same test failing normally, without subtests, prints one of each.

The fix counts the failed subtests in the teardown check, the same way the re-run decision already does. _get_num_failed_subtests takes a nodeid now instead of a report, since the teardown hook has no report to hand it.

Tests cover class, module and session scope and the cross-module case. One is a guard rather than a reproduction: subtests that never pass exhaust the re-runs and still tear the module fixture down exactly once.

@teddytennant
teddytennant force-pushed the fix-subtest-premature-teardown branch from a3b028e to 5e87576 Compare August 27, 2026 12:45
A call phase that only has failed subtests leaves the call report itself
passing, so the failure statuses pytest_runtest_teardown looks at are
all false. The hook then treats the test as finished and lets the
module, class and session finalizers run, while the protocol goes on to
re-run the test. The higher-scoped fixtures are torn down and set up
again on every attempt.

Count the failed subtests in that check, the same way the re-run
decision already does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant