Debian Codegraph @

Lib/test/test_ensurepip.py

raw
1 import contextlib
2 import os
3 import os.path
4 import sys
5 import tempfile
6 import test.support
7 import unittest
8 import unittest.mock
9 from pathlib import Path
10 from test.support import import_helper
11
12 import ensurepip
13 import ensurepip._uninstall
14
15
16 class TestPackages(unittest.TestCase):
17 def touch(self, directory, filename):
18 fullname = os.path.join(directory, filename)
19 open(fullname, "wb").close()
20
21 def test_version(self):
22 # Test version()
23 with tempfile.TemporaryDirectory() as tmpdir:
24 self.touch(tmpdir, "pip-1.2.3b1-py2.py3-none-any.whl")
25 with unittest.mock.patch.object(ensurepip, '_WHEEL_PKG_DIR', Path(tmpdir)):
26 self.assertEqual(ensurepip.version(), '1.2.3b1')
27
28 def test_version_no_dir(self):
29 # Test version() without a wheel package directory
30 with unittest.mock.patch.object(ensurepip, '_WHEEL_PKG_DIR', None):
31 # when the bundled pip wheel is used, we get _PIP_VERSION
32 self.assertEqual(ensurepip._PIP_VERSION, ensurepip.version())
33
34 def test_wheel_pkg_dir_none(self):
35 # gh-146310: empty or None WHEEL_PKG_DIR should not search CWD
36 for value in ('', None):
37 with unittest.mock.patch('sysconfig.get_config_var',
38 return_value=value) as get_config_var:
39 module = import_helper.import_fresh_module('ensurepip')
40 self.assertIsNone(module._WHEEL_PKG_DIR)
41 get_config_var.assert_called_once_with('WHEEL_PKG_DIR')
42
43 def test_selected_wheel_path_no_dir(self):
44 pip_filename = f'pip-{ensurepip._PIP_VERSION}-py3-none-any.whl'
45 with unittest.mock.patch.object(ensurepip, '_WHEEL_PKG_DIR', None):
46 with ensurepip._get_pip_whl_path_ctx() as bundled_wheel_path:
47 self.assertEqual(pip_filename, bundled_wheel_path.name)
48
49 def test_selected_wheel_path_with_dir(self):
50 # Test _get_pip_whl_path_ctx() with a wheel package directory
51 pip_filename = "pip-20.2.2-py2.py3-none-any.whl"
52
53 with tempfile.TemporaryDirectory() as tmpdir:
54 self.touch(tmpdir, pip_filename)
55 # not used, make sure that they're ignored
56 self.touch(tmpdir, "pip-1.2.3-py2.py3-none-any.whl")
57 self.touch(tmpdir, "wheel-0.34.2-py2.py3-none-any.whl")
58 self.touch(tmpdir, "pip-script.py")
59
60 with unittest.mock.patch.object(ensurepip, '_WHEEL_PKG_DIR', Path(tmpdir)):
61 with ensurepip._get_pip_whl_path_ctx() as bundled_wheel_path:
62 self.assertEqual(pip_filename, bundled_wheel_path.name)
63
64
65 class EnsurepipMixin:
66
67 def setUp(self):
68 run_pip_patch = unittest.mock.patch("ensurepip._run_pip")
69 self.run_pip = run_pip_patch.start()
70 self.run_pip.return_value = 0
71 self.addCleanup(run_pip_patch.stop)
72
73 # Avoid side effects on the actual os module
74 real_devnull = os.devnull
75 os_patch = unittest.mock.patch("ensurepip.os")
76 patched_os = os_patch.start()
77 # But expose os.listdir() used by _find_wheel_pkg_dir_pip()
78 patched_os.listdir = os.listdir
79 self.addCleanup(os_patch.stop)
80 patched_os.devnull = real_devnull
81 patched_os.path = os.path
82 self.os_environ = patched_os.environ = os.environ.copy()
83
84
85 class TestBootstrap(EnsurepipMixin, unittest.TestCase):
86
87 def test_basic_bootstrapping(self):
88 ensurepip.bootstrap()
89
90 self.run_pip.assert_called_once_with(
91 [
92 "install", "--no-cache-dir", "--no-index", "--find-links",
93 unittest.mock.ANY, "pip",
94 ],
95 unittest.mock.ANY,
96 )
97
98 additional_paths = self.run_pip.call_args[0][1]
99 self.assertEqual(len(additional_paths), 1)
100
101 def test_bootstrapping_with_root(self):
102 ensurepip.bootstrap(root="/foo/bar/")
103
104 self.run_pip.assert_called_once_with(
105 [
106 "install", "--no-cache-dir", "--no-index", "--find-links",
107 unittest.mock.ANY, "--root", "/foo/bar/",
108 "pip",
109 ],
110 unittest.mock.ANY,
111 )
112
113 def test_bootstrapping_with_user(self):
114 ensurepip.bootstrap(user=True)
115
116 self.run_pip.assert_called_once_with(
117 [
118 "install", "--no-cache-dir", "--no-index", "--find-links",
119 unittest.mock.ANY, "--user", "pip",
120 ],
121 unittest.mock.ANY,
122 )
123
124 def test_bootstrapping_with_upgrade(self):
125 ensurepip.bootstrap(upgrade=True)
126
127 self.run_pip.assert_called_once_with(
128 [
129 "install", "--no-cache-dir", "--no-index", "--find-links",
130 unittest.mock.ANY, "--upgrade", "pip",
131 ],
132 unittest.mock.ANY,
133 )
134
135 def test_bootstrapping_with_verbosity_1(self):
136 ensurepip.bootstrap(verbosity=1)
137
138 self.run_pip.assert_called_once_with(
139 [
140 "install", "--no-cache-dir", "--no-index", "--find-links",
141 unittest.mock.ANY, "-v", "pip",
142 ],
143 unittest.mock.ANY,
144 )
145
146 def test_bootstrapping_with_verbosity_2(self):
147 ensurepip.bootstrap(verbosity=2)
148
149 self.run_pip.assert_called_once_with(
150 [
151 "install", "--no-cache-dir", "--no-index", "--find-links",
152 unittest.mock.ANY, "-vv", "pip",
153 ],
154 unittest.mock.ANY,
155 )
156
157 def test_bootstrapping_with_verbosity_3(self):
158 ensurepip.bootstrap(verbosity=3)
159
160 self.run_pip.assert_called_once_with(
161 [
162 "install", "--no-cache-dir", "--no-index", "--find-links",
163 unittest.mock.ANY, "-vvv", "pip",
164 ],
165 unittest.mock.ANY,
166 )
167
168 def test_bootstrapping_with_regular_install(self):
169 ensurepip.bootstrap()
170 self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "install")
171
172 def test_bootstrapping_with_alt_install(self):
173 ensurepip.bootstrap(altinstall=True)
174 self.assertEqual(self.os_environ["ENSUREPIP_OPTIONS"], "altinstall")
175
176 def test_bootstrapping_with_default_pip(self):
177 ensurepip.bootstrap(default_pip=True)
178 self.assertNotIn("ENSUREPIP_OPTIONS", self.os_environ)
179
180 def test_altinstall_default_pip_conflict(self):
181 with self.assertRaises(ValueError):
182 ensurepip.bootstrap(altinstall=True, default_pip=True)
183 self.assertFalse(self.run_pip.called)
184
185 def test_pip_environment_variables_removed(self):
186 # ensurepip deliberately ignores all pip environment variables
187 # See http://bugs.python.org/issue19734 for details
188 self.os_environ["PIP_THIS_SHOULD_GO_AWAY"] = "test fodder"
189 ensurepip.bootstrap()
190 self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ)
191
192 def test_pip_config_file_disabled(self):
193 # ensurepip deliberately ignores the pip config file
194 # See http://bugs.python.org/issue20053 for details
195 ensurepip.bootstrap()
196 self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull)
197
198 @contextlib.contextmanager
199 def fake_pip(version=ensurepip.version()):
200 if version is None:
201 pip = None
202 else:
203 class FakePip():
204 __version__ = version
205 pip = FakePip()
206 sentinel = object()
207 orig_pip = sys.modules.get("pip", sentinel)
208 sys.modules["pip"] = pip
209 try:
210 yield pip
211 finally:
212 if orig_pip is sentinel:
213 del sys.modules["pip"]
214 else:
215 sys.modules["pip"] = orig_pip
216
217 class TestUninstall(EnsurepipMixin, unittest.TestCase):
218
219 def test_uninstall_skipped_when_not_installed(self):
220 with fake_pip(None):
221 ensurepip._uninstall_helper()
222 self.assertFalse(self.run_pip.called)
223
224 def test_uninstall_skipped_with_warning_for_wrong_version(self):
225 with fake_pip("not a valid version"):
226 with test.support.captured_stderr() as stderr:
227 ensurepip._uninstall_helper()
228 warning = stderr.getvalue().strip()
229 self.assertIn("only uninstall a matching version", warning)
230 self.assertFalse(self.run_pip.called)
231
232
233 def test_uninstall(self):
234 with fake_pip():
235 ensurepip._uninstall_helper()
236
237 self.run_pip.assert_called_once_with(
238 [
239 "uninstall", "-y", "--disable-pip-version-check", "pip",
240 ]
241 )
242
243 def test_uninstall_with_verbosity_1(self):
244 with fake_pip():
245 ensurepip._uninstall_helper(verbosity=1)
246
247 self.run_pip.assert_called_once_with(
248 [
249 "uninstall", "-y", "--disable-pip-version-check", "-v", "pip",
250 ]
251 )
252
253 def test_uninstall_with_verbosity_2(self):
254 with fake_pip():
255 ensurepip._uninstall_helper(verbosity=2)
256
257 self.run_pip.assert_called_once_with(
258 [
259 "uninstall", "-y", "--disable-pip-version-check", "-vv", "pip",
260 ]
261 )
262
263 def test_uninstall_with_verbosity_3(self):
264 with fake_pip():
265 ensurepip._uninstall_helper(verbosity=3)
266
267 self.run_pip.assert_called_once_with(
268 [
269 "uninstall", "-y", "--disable-pip-version-check", "-vvv",
270 "pip"
271 ]
272 )
273
274 def test_pip_environment_variables_removed(self):
275 # ensurepip deliberately ignores all pip environment variables
276 # See http://bugs.python.org/issue19734 for details
277 self.os_environ["PIP_THIS_SHOULD_GO_AWAY"] = "test fodder"
278 with fake_pip():
279 ensurepip._uninstall_helper()
280 self.assertNotIn("PIP_THIS_SHOULD_GO_AWAY", self.os_environ)
281
282 def test_pip_config_file_disabled(self):
283 # ensurepip deliberately ignores the pip config file
284 # See http://bugs.python.org/issue20053 for details
285 with fake_pip():
286 ensurepip._uninstall_helper()
287 self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull)
288
289
290 # Basic testing of the main functions and their argument parsing
291
292 EXPECTED_VERSION_OUTPUT = "pip " + ensurepip.version()
293
294 class TestBootstrappingMainFunction(EnsurepipMixin, unittest.TestCase):
295
296 def test_bootstrap_version(self):
297 with test.support.captured_stdout() as stdout:
298 with self.assertRaises(SystemExit):
299 ensurepip._main(["--version"])
300 result = stdout.getvalue().strip()
301 self.assertEqual(result, EXPECTED_VERSION_OUTPUT)
302 self.assertFalse(self.run_pip.called)
303
304 def test_basic_bootstrapping(self):
305 exit_code = ensurepip._main([])
306
307 self.run_pip.assert_called_once_with(
308 [
309 "install", "--no-cache-dir", "--no-index", "--find-links",
310 unittest.mock.ANY, "pip",
311 ],
312 unittest.mock.ANY,
313 )
314
315 additional_paths = self.run_pip.call_args[0][1]
316 self.assertEqual(len(additional_paths), 1)
317 self.assertEqual(exit_code, 0)
318
319 def test_bootstrapping_error_code(self):
320 self.run_pip.return_value = 2
321 exit_code = ensurepip._main([])
322 self.assertEqual(exit_code, 2)
323
324
325 class TestUninstallationMainFunction(EnsurepipMixin, unittest.TestCase):
326
327 def test_uninstall_version(self):
328 with test.support.captured_stdout() as stdout:
329 with self.assertRaises(SystemExit):
330 ensurepip._uninstall._main(["--version"])
331 result = stdout.getvalue().strip()
332 self.assertEqual(result, EXPECTED_VERSION_OUTPUT)
333 self.assertFalse(self.run_pip.called)
334
335 def test_basic_uninstall(self):
336 with fake_pip():
337 exit_code = ensurepip._uninstall._main([])
338
339 self.run_pip.assert_called_once_with(
340 [
341 "uninstall", "-y", "--disable-pip-version-check", "pip",
342 ]
343 )
344
345 self.assertEqual(exit_code, 0)
346
347 def test_uninstall_error_code(self):
348 with fake_pip():
349 self.run_pip.return_value = 2
350 exit_code = ensurepip._uninstall._main([])
351 self.assertEqual(exit_code, 2)
352
353
354 if __name__ == "__main__":
355 unittest.main()