Skip to content

fix: don't credit collection-time calls to the first test - #646

Open
agustin18 wants to merge 1 commit into
boxed:mainfrom
agustin18:fix/stats-collection-finish
Open

agustin18 wants to merge 1 commit into
boxed:mainfrom
agustin18:fix/stats-collection-finish

Conversation

@agustin18

Copy link
Copy Markdown

state()._stats is only cleared in pytest_runtest_teardown, so the calls made while pytest imports the test and source modules survive until the first test finishes and get credited to it. In the repro from #641 that credits _table to test_double, and _table's mutants are then reported as survived even though test_lookup would kill them.

This adds pytest_collection_finish to StatsCollector and clears the buffer there, so only calls made while a test runs are attributed to it.

Scope. This is the first part the issue asks for. A function that only runs at import now has no tests, so its mutants show as no tests instead of a false survived. Making them killable requires importing the module with MUTANT_UNDER_TEST already set, which is a separate change and is not attempted here.

Test. The new test drives the collector directly rather than running a nested pytest session: it records a hit, fires pytest_collection_finish, then asserts the first test only picks up the hit recorded during its own run. It fails on main with AttributeError: 'StatsCollector' object has no attribute 'pytest_collection_finish'.

Notes:

  • HammettRunner.run_stats has the same shape in post_test_callback, but hammett exposes no collection hook, so that path is unchanged.
  • tests/e2e/test_e2e_my_lib.py::test_my_lib_result_snapshot fails in my environment on unmodified main too; everything else passes (470 passed, 3 skipped, --ignore=tests/e2e).

Refs #641.

Trampolined functions called while pytest imports test and source modules
were left in state()._stats and credited to whichever test ran first. A
function only called at import time therefore looked covered, so its
mutants were reported as survived instead of no tests.

Clear the buffer in pytest_collection_finish, which runs after collection
and before the first test.
@agustin18

agustin18 commented Nov 19, 2026 •

Copy link
Copy Markdown
Author

Ran the repro from the report in this environment, on unmodified main and on this branch:

main this branch
lib.x__table__mutmut_1..6 survived no tests
tests_by_mangled_function_name lib.x__table: ["tests/test_lib.py::test_double"] lib.x_double only

The false survivors are gone and the stats file no longer credits _table to a test that never touches it. The mutants are still not killable, because the module is imported before MUTANT_UNDER_TEST is set; that is the second part of the issue and is not addressed here.

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