Conftest.restore_import_state should restore sys.meta_path as well as sys.path #1140
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The
restore_import_state
context manager (in conftest.py) is used to isolate tests with respect to any changes they may make insys.path
and any modules they may import.It turns out that
sys.meta_path
needs to be restored as well. If that's not done, there are a couple of insidious bugs (spurious test failures) that crop up.Issue(s) Resolved
Spurious test failures.
Description of Changes
Restore
sys.meta_path
.Some modules, when imported, add their own custom finders to sys.meta_path. If such a module is imported within a test that is protected by
restore_import_state
, it is in effect, "unimported" at the end of the test. If another test also imports that module, it can add its finder to meta_path again.(This can result in a
RuntimeError: Plugin "webpack-support" is already registered
, since, with a duplicate finder on meta_path, import.metadata.distributions() can list all distributions twice.)Demangle the finders on
sys.meta_path
It gets worse.
It turns out that when
importlib_metadata
is imported, it neuters the stdlib PathFinder (by deleting its find_distributions method). It then adds its own custom finder to handle distribution lookup instead.If
importlib_metadata
is imported within a test that is protected byrestore_import_state
, its custom finder gets removed from sys.meta_path at the end of the test. But the stdlib finder has been crippled at this point, so now attempts to list installed distributions fail.So here, we make a copy of the stdlib PathFinder before the test run and restore that at the end of the test.