gh-139823: Check if zlib is available in ensurepip (GH-139954)

This commit is contained in:
Stan Ulbrych
2025-10-13 15:01:06 +01:00
committed by GitHub
parent 52996aaa78
commit 1a82568568
3 changed files with 26 additions and 0 deletions

View File

@@ -130,6 +130,15 @@ def _bootstrap(*, root=None, upgrade=False, user=False,
Note that calling this function will alter both sys.path and os.environ.
"""
try:
import zlib
except ImportError:
raise ModuleNotFoundError(
"ensurepip requires the standard library module 'zlib' "
"to install pip."
) from None
if altinstall and default_pip:
raise ValueError("Cannot use altinstall and default_pip together")

View File

@@ -60,6 +60,11 @@ class EnsurepipMixin:
self.run_pip.return_value = 0
self.addCleanup(run_pip_patch.stop)
# Allow testing on zlib-less platforms by avoiding the check for zlib in _bootstrap()
zlib_patch = unittest.mock.patch.dict('sys.modules', {'zlib': unittest.mock.MagicMock()})
zlib_patch.start()
self.addCleanup(zlib_patch.stop)
# Avoid side effects on the actual os module
real_devnull = os.devnull
os_patch = unittest.mock.patch("ensurepip.os")
@@ -185,6 +190,16 @@ class TestBootstrap(EnsurepipMixin, unittest.TestCase):
ensurepip.bootstrap()
self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull)
def test_missing_zlib(self):
with unittest.mock.patch.dict('sys.modules', {'zlib': None}):
with self.assertRaises(ModuleNotFoundError) as cm:
ensurepip.bootstrap()
error_msg = str(cm.exception)
self.assertIn("ensurepip requires the standard library module 'zlib'", error_msg)
self.assertFalse(self.run_pip.called)
@contextlib.contextmanager
def fake_pip(version=ensurepip.version()):
if version is None:

View File

@@ -0,0 +1,2 @@
:mod:`ensurepip` now fails with a nicer error message when the :mod:`zlib`
module is not available.