diff --git a/Lib/importlib/_bootstrap_external.py b/Lib/importlib/_bootstrap_external.py index 46ddceed07b0d4..72b3b108be4432 100644 --- a/Lib/importlib/_bootstrap_external.py +++ b/Lib/importlib/_bootstrap_external.py @@ -1470,6 +1470,9 @@ def invalidate_caches(): # https://bugs.python.org/issue45703 _NamespacePath._epoch += 1 + from importlib.metadata import MetadataPathFinder + MetadataPathFinder().invalidate_caches() + @staticmethod def _path_hooks(path): """Search sys.path_hooks for a finder for 'path'.""" diff --git a/Lib/test/test_importlib/resources/test_files.py b/Lib/test/test_importlib/resources/test_files.py index 26c8b04e44c3b9..dfc678f38ca3ad 100644 --- a/Lib/test/test_importlib/resources/test_files.py +++ b/Lib/test/test_importlib/resources/test_files.py @@ -3,6 +3,7 @@ import unittest import warnings import importlib +import inspect import contextlib from importlib import resources @@ -90,6 +91,12 @@ def test_module_resources(self): class ImplicitContextFilesTests(SiteDir, unittest.TestCase): + + def tearDown(self): + # clean up inspect state to avoid ref leaks (#116731) + inspect._filesbymodname.clear() + inspect.modulesbyfile.clear() + def test_implicit_files(self): """ Without any parameter, files() will infer the location as the caller. diff --git a/Lib/test/test_importlib/test_main.py b/Lib/test/test_importlib/test_main.py index 0a769b89841234..306636063211dc 100644 --- a/Lib/test/test_importlib/test_main.py +++ b/Lib/test/test_importlib/test_main.py @@ -2,6 +2,7 @@ import pickle import unittest import warnings +import importlib import importlib.metadata import contextlib from test.support import os_helper @@ -37,6 +38,9 @@ def suppress_known_deprecation(): class BasicTests(fixtures.DistInfoPkg, unittest.TestCase): version_pattern = r'\d+\.\d+(\.\d)?' + def tearDown(self): + importlib.invalidate_caches() + def test_retrieves_version_of_self(self): dist = Distribution.from_name('distinfo-pkg') assert isinstance(dist.version, str) diff --git a/Lib/test/test_importlib/test_metadata_api.py b/Lib/test/test_importlib/test_metadata_api.py index 33c6e85ee94753..e2936303aca81f 100644 --- a/Lib/test/test_importlib/test_metadata_api.py +++ b/Lib/test/test_importlib/test_metadata_api.py @@ -37,6 +37,9 @@ class APITests( ): version_pattern = r'\d+\.\d+(\.\d)?' + def tearDown(self): + importlib.invalidate_caches() + def test_retrieves_version_of_self(self): pkg_version = version('egginfo-pkg') assert isinstance(pkg_version, str) diff --git a/Misc/NEWS.d/next/Tests/2024-03-13-16-59-56.gh-issue-116731.s2xTyz.rst b/Misc/NEWS.d/next/Tests/2024-03-13-16-59-56.gh-issue-116731.s2xTyz.rst new file mode 100644 index 00000000000000..99152c138b3dc6 --- /dev/null +++ b/Misc/NEWS.d/next/Tests/2024-03-13-16-59-56.gh-issue-116731.s2xTyz.rst @@ -0,0 +1,2 @@ +Fixed nuisance refleaks warnings in tests for importlib.metadata and +importlib.resources.