Skip to content

Commit 1a82568

Browse files
gh-139823: Check if zlib is available in ensurepip (GH-139954)
1 parent 52996aa commit 1a82568

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

Lib/ensurepip/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,15 @@ def _bootstrap(*, root=None, upgrade=False, user=False,
130130
131131
Note that calling this function will alter both sys.path and os.environ.
132132
"""
133+
134+
try:
135+
import zlib
136+
except ImportError:
137+
raise ModuleNotFoundError(
138+
"ensurepip requires the standard library module 'zlib' "
139+
"to install pip."
140+
) from None
141+
133142
if altinstall and default_pip:
134143
raise ValueError("Cannot use altinstall and default_pip together")
135144

Lib/test/test_ensurepip.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,11 @@ def setUp(self):
6060
self.run_pip.return_value = 0
6161
self.addCleanup(run_pip_patch.stop)
6262

63+
# Allow testing on zlib-less platforms by avoiding the check for zlib in _bootstrap()
64+
zlib_patch = unittest.mock.patch.dict('sys.modules', {'zlib': unittest.mock.MagicMock()})
65+
zlib_patch.start()
66+
self.addCleanup(zlib_patch.stop)
67+
6368
# Avoid side effects on the actual os module
6469
real_devnull = os.devnull
6570
os_patch = unittest.mock.patch("ensurepip.os")
@@ -185,6 +190,16 @@ def test_pip_config_file_disabled(self):
185190
ensurepip.bootstrap()
186191
self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull)
187192

193+
def test_missing_zlib(self):
194+
with unittest.mock.patch.dict('sys.modules', {'zlib': None}):
195+
with self.assertRaises(ModuleNotFoundError) as cm:
196+
ensurepip.bootstrap()
197+
198+
error_msg = str(cm.exception)
199+
self.assertIn("ensurepip requires the standard library module 'zlib'", error_msg)
200+
201+
self.assertFalse(self.run_pip.called)
202+
188203
@contextlib.contextmanager
189204
def fake_pip(version=ensurepip.version()):
190205
if version is None:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:mod:`ensurepip` now fails with a nicer error message when the :mod:`zlib`
2+
module is not available.

0 commit comments

Comments
 (0)