Skip to content

gh-158377: Fix unittest.TestLoader.discover() leaking _top_level_dir on error - #158378

Open
christianaurichzm wants to merge 1 commit into
python:mainfrom
christianaurichzm:fix-unittest-discover-top-level-dir
Open

christianaurichzm wants to merge 1 commit into
python:mainfrom
christianaurichzm:fix-unittest-discover-top-level-dir

Conversation

@christianaurichzm

@christianaurichzm christianaurichzm commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #158377

TestLoader.discover() restores _top_level_dir at the end of the call (gh-59215), but only on the success path. If discovery raises, the loader keeps the top-level directory of the failed call, and a later discover() on the same loader without an explicit top_level_dir resolves against it. This moves the restore into a finally block. Most of the diff is reindentation, so it is easier to review with whitespace changes hidden.

This is reachable without touching the loader directly: unittest.main() uses the shared unittest.defaultTestLoader, so calling unittest.main(argv=[..., "discover", "-s", <typo>], exit=False) and then again with the right directory in the same process (for example from a notebook or REPL) fails on the second call too.

Two assertions in test_discover checked _top_level_dir after an ImportError from discover() and after the successful call that follows it, so they encoded the leaked value. They now expect None, the value of a fresh loader.

…l_dir on error

TestLoader.discover() restores _top_level_dir at the end of the call, but
only when discovery succeeds. If it raises, for example because the start
directory is not importable, the loader keeps the top-level directory of
the failed call, and a later discover() on the same loader without an
explicit top_level_dir resolves against it.

Restore _top_level_dir in a finally block. Two assertions in
test_discover checked the leaked value and now expect None.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

unittest.TestLoader.discover() leaves _top_level_dir set if discovery fails

1 participant