blob: 28743f03ae2036d4d8109206ae53ed6dfed72ca4 [file] [log] [blame]
Vinay Sajip42211422012-05-26 20:36:12 +01001"""
2Test harness for the venv module.
Vinay Sajip7ded1f02012-05-26 03:45:29 +01003
Vinay Sajip42211422012-05-26 20:36:12 +01004Copyright (C) 2011-2012 Vinay Sajip.
Vinay Sajip28952442012-06-25 00:47:46 +01005Licensed to the PSF under a contributor agreement.
Vinay Sajip7ded1f02012-05-26 03:45:29 +01006"""
7
Nick Coghlan1b1b1782013-11-30 15:56:58 +10008import ensurepip
Vinay Sajip7ded1f02012-05-26 03:45:29 +01009import os
10import os.path
Victor Stinner87d6e132016-03-14 18:21:58 +010011import re
Miss Islington (bot)63eefc32019-09-11 08:55:57 -070012import shutil
Vinay Sajip1e53f8d2014-04-15 11:18:10 +010013import struct
Vinay Sajip3874e542012-07-03 16:56:40 +010014import subprocess
Vinay Sajip7ded1f02012-05-26 03:45:29 +010015import sys
16import tempfile
Serhiy Storchaka5e0df742017-11-10 12:09:39 +020017from test.support import (captured_stdout, captured_stderr, requires_zlib,
xdegaye5437ccc2019-05-30 23:42:29 +020018 can_symlink, EnvironmentVarGuard, rmtree,
Victor Stinnere8056182020-06-18 18:56:43 +020019 import_module,
20 skip_if_broken_multiprocessing_synchronize)
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020021import threading
Vinay Sajip7ded1f02012-05-26 03:45:29 +010022import unittest
23import venv
Nick Coghlanae2ee962013-12-23 23:07:07 +100024
Victor Stinnerb3477882016-03-25 12:27:02 +010025try:
26 import ctypes
27except ImportError:
28 ctypes = None
29
Steve Dower8bba81f2019-03-21 10:04:21 -070030# Platforms that set sys._base_executable can create venvs from within
31# another venv, so no need to skip tests that require venv.create().
32requireVenvCreate = unittest.skipUnless(
Steve Dower323e7432019-06-29 14:28:59 -070033 sys.prefix == sys.base_prefix
34 or sys._base_executable != sys.executable,
Steve Dower8bba81f2019-03-21 10:04:21 -070035 'cannot run venv.create from within a venv on this platform')
Nick Coghlan8fbdb092013-11-23 00:30:34 +100036
Steve Dowerf14c28f2018-09-20 13:38:34 -070037def check_output(cmd, encoding=None):
38 p = subprocess.Popen(cmd,
39 stdout=subprocess.PIPE,
40 stderr=subprocess.PIPE,
41 encoding=encoding)
42 out, err = p.communicate()
43 if p.returncode:
44 raise subprocess.CalledProcessError(
Pablo Galindob9392502018-11-07 22:21:17 +000045 p.returncode, cmd, out, err)
Steve Dowerf14c28f2018-09-20 13:38:34 -070046 return out, err
47
Vinay Sajip7ded1f02012-05-26 03:45:29 +010048class BaseTest(unittest.TestCase):
49 """Base class for venv tests."""
Victor Stinnerbdc337b2016-03-25 12:30:40 +010050 maxDiff = 80 * 50
Vinay Sajip7ded1f02012-05-26 03:45:29 +010051
52 def setUp(self):
Ned Deily045bd532012-07-13 15:48:04 -070053 self.env_dir = os.path.realpath(tempfile.mkdtemp())
Vinay Sajip7ded1f02012-05-26 03:45:29 +010054 if os.name == 'nt':
55 self.bindir = 'Scripts'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010056 self.lib = ('Lib',)
57 self.include = 'Include'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010058 else:
59 self.bindir = 'bin'
Serhiy Storchaka885bdc42016-02-11 13:10:36 +020060 self.lib = ('lib', 'python%d.%d' % sys.version_info[:2])
Vinay Sajip7ded1f02012-05-26 03:45:29 +010061 self.include = 'include'
Steve Dower323e7432019-06-29 14:28:59 -070062 executable = sys._base_executable
Vinay Sajip382a7c02012-05-28 16:34:47 +010063 self.exe = os.path.split(executable)[-1]
Steve Dower323e7432019-06-29 14:28:59 -070064 if (sys.platform == 'win32'
65 and os.path.lexists(executable)
66 and not os.path.exists(executable)):
67 self.cannot_link_exe = True
68 else:
69 self.cannot_link_exe = False
Vinay Sajip7ded1f02012-05-26 03:45:29 +010070
71 def tearDown(self):
Victor Stinner866c4e22014-10-10 14:23:00 +020072 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010073
74 def run_with_capture(self, func, *args, **kwargs):
75 with captured_stdout() as output:
76 with captured_stderr() as error:
77 func(*args, **kwargs)
78 return output.getvalue(), error.getvalue()
79
80 def get_env_file(self, *args):
81 return os.path.join(self.env_dir, *args)
82
83 def get_text_file_contents(self, *args):
84 with open(self.get_env_file(*args), 'r') as f:
85 result = f.read()
86 return result
87
88class BasicTest(BaseTest):
89 """Test venv module functionality."""
90
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010091 def isdir(self, *args):
92 fn = self.get_env_file(*args)
93 self.assertTrue(os.path.isdir(fn))
94
Vinay Sajip7ded1f02012-05-26 03:45:29 +010095 def test_defaults(self):
96 """
97 Test the create function with default arguments.
98 """
Victor Stinner866c4e22014-10-10 14:23:00 +020099 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100100 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100101 self.isdir(self.bindir)
102 self.isdir(self.include)
103 self.isdir(*self.lib)
Vinay Sajip1e53f8d2014-04-15 11:18:10 +0100104 # Issue 21197
105 p = self.get_env_file('lib64')
106 conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
107 (sys.platform != 'darwin'))
108 if conditions:
109 self.assertTrue(os.path.islink(p))
110 else:
111 self.assertFalse(os.path.exists(p))
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100112 data = self.get_text_file_contents('pyvenv.cfg')
Steve Dower323e7432019-06-29 14:28:59 -0700113 executable = sys._base_executable
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100114 path = os.path.dirname(executable)
115 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100116 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +0100117 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100118 bd = self.get_env_file(self.bindir)
119 print('Contents of %r:' % bd)
120 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +0100121 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100122
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100123 def test_prompt(self):
124 env_name = os.path.split(self.env_dir)[1]
125
Cheryl Sabella839b9252019-03-12 20:15:47 -0400126 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100127 builder = venv.EnvBuilder()
Cheryl Sabella839b9252019-03-12 20:15:47 -0400128 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100129 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500130 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400131 self.assertEqual(context.prompt, '(%s) ' % env_name)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500132 self.assertNotIn("prompt = ", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100133
Cheryl Sabella839b9252019-03-12 20:15:47 -0400134 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100135 builder = venv.EnvBuilder(prompt='My prompt')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400136 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100137 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500138 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400139 self.assertEqual(context.prompt, '(My prompt) ')
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500140 self.assertIn("prompt = 'My prompt'\n", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100141
Steve Dower8bba81f2019-03-21 10:04:21 -0700142 @requireVenvCreate
Vinay Sajip3874e542012-07-03 16:56:40 +0100143 def test_prefixes(self):
144 """
145 Test that the prefix values are as expected.
146 """
Vinay Sajip3874e542012-07-03 16:56:40 +0100147 # check a venv's prefixes
Victor Stinner866c4e22014-10-10 14:23:00 +0200148 rmtree(self.env_dir)
Vinay Sajip3874e542012-07-03 16:56:40 +0100149 self.run_with_capture(venv.create, self.env_dir)
150 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
151 cmd = [envpy, '-c', None]
152 for prefix, expected in (
153 ('prefix', self.env_dir),
Steve Dower323e7432019-06-29 14:28:59 -0700154 ('exec_prefix', self.env_dir),
155 ('base_prefix', sys.base_prefix),
156 ('base_exec_prefix', sys.base_exec_prefix)):
Vinay Sajip3874e542012-07-03 16:56:40 +0100157 cmd[2] = 'import sys; print(sys.%s)' % prefix
Steve Dowerf14c28f2018-09-20 13:38:34 -0700158 out, err = check_output(cmd)
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200159 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100160
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100161 if sys.platform == 'win32':
162 ENV_SUBDIRS = (
163 ('Scripts',),
164 ('Include',),
165 ('Lib',),
166 ('Lib', 'site-packages'),
167 )
168 else:
169 ENV_SUBDIRS = (
170 ('bin',),
171 ('include',),
172 ('lib',),
173 ('lib', 'python%d.%d' % sys.version_info[:2]),
174 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
175 )
176
177 def create_contents(self, paths, filename):
178 """
179 Create some files in the environment which are unrelated
180 to the virtual environment.
181 """
182 for subdirs in paths:
183 d = os.path.join(self.env_dir, *subdirs)
184 os.mkdir(d)
185 fn = os.path.join(d, filename)
186 with open(fn, 'wb') as f:
187 f.write(b'Still here?')
188
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100189 def test_overwrite_existing(self):
190 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100191 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100192 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100193 self.create_contents(self.ENV_SUBDIRS, 'foo')
194 venv.create(self.env_dir)
195 for subdirs in self.ENV_SUBDIRS:
196 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
197 self.assertTrue(os.path.exists(fn))
198 with open(fn, 'rb') as f:
199 self.assertEqual(f.read(), b'Still here?')
200
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100201 builder = venv.EnvBuilder(clear=True)
202 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100203 for subdirs in self.ENV_SUBDIRS:
204 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
205 self.assertFalse(os.path.exists(fn))
206
207 def clear_directory(self, path):
208 for fn in os.listdir(path):
209 fn = os.path.join(path, fn)
210 if os.path.islink(fn) or os.path.isfile(fn):
211 os.remove(fn)
212 elif os.path.isdir(fn):
Victor Stinner866c4e22014-10-10 14:23:00 +0200213 rmtree(fn)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100214
215 def test_unoverwritable_fails(self):
216 #create a file clashing with directories in the env dir
217 for paths in self.ENV_SUBDIRS[:3]:
218 fn = os.path.join(self.env_dir, *paths)
219 with open(fn, 'wb') as f:
220 f.write(b'')
221 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
222 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100223
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100224 def test_upgrade(self):
225 """
226 Test upgrading an existing environment directory.
227 """
Vinay Sajipb9b965f2014-06-03 16:47:51 +0100228 # See Issue #21643: the loop needs to run twice to ensure
229 # that everything works on the upgrade (the first run just creates
230 # the venv).
231 for upgrade in (False, True):
232 builder = venv.EnvBuilder(upgrade=upgrade)
233 self.run_with_capture(builder.create, self.env_dir)
234 self.isdir(self.bindir)
235 self.isdir(self.include)
236 self.isdir(*self.lib)
237 fn = self.get_env_file(self.bindir, self.exe)
238 if not os.path.exists(fn):
239 # diagnostics for Windows buildbot failures
240 bd = self.get_env_file(self.bindir)
241 print('Contents of %r:' % bd)
242 print(' %r' % os.listdir(bd))
243 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100244
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100245 def test_isolation(self):
246 """
247 Test isolation from system site-packages
248 """
249 for ssp, s in ((True, 'true'), (False, 'false')):
250 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
251 builder.create(self.env_dir)
252 data = self.get_text_file_contents('pyvenv.cfg')
253 self.assertIn('include-system-site-packages = %s\n' % s, data)
254
255 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
256 def test_symlinking(self):
257 """
258 Test symlinking works as expected
259 """
260 for usl in (False, True):
261 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100262 builder.create(self.env_dir)
263 fn = self.get_env_file(self.bindir, self.exe)
264 # Don't test when False, because e.g. 'python' is always
265 # symlinked to 'python3.3' in the env, even when symlinking in
266 # general isn't wanted.
267 if usl:
Steve Dower323e7432019-06-29 14:28:59 -0700268 if self.cannot_link_exe:
269 # Symlinking is skipped when our executable is already a
270 # special app symlink
271 self.assertFalse(os.path.islink(fn))
272 else:
273 self.assertTrue(os.path.islink(fn))
Vinay Sajip90db6612012-07-17 17:33:46 +0100274
275 # If a venv is created from a source build and that venv is used to
276 # run the test, the pyvenv.cfg in the venv created in the test will
277 # point to the venv being used to run the test, and we lose the link
278 # to the source build - so Python can't initialise properly.
Steve Dower8bba81f2019-03-21 10:04:21 -0700279 @requireVenvCreate
Vinay Sajip90db6612012-07-17 17:33:46 +0100280 def test_executable(self):
281 """
282 Test that the sys.executable value is as expected.
283 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200284 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100285 self.run_with_capture(venv.create, self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700286 envpy = os.path.join(os.path.realpath(self.env_dir),
287 self.bindir, self.exe)
288 out, err = check_output([envpy, '-c',
289 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200290 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100291
292 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
293 def test_executable_symlinks(self):
294 """
295 Test that the sys.executable value is as expected.
296 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200297 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100298 builder = venv.EnvBuilder(clear=True, symlinks=True)
299 builder.create(self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700300 envpy = os.path.join(os.path.realpath(self.env_dir),
301 self.bindir, self.exe)
302 out, err = check_output([envpy, '-c',
303 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200304 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100305
Steve Dower62409172018-02-19 17:25:24 -0800306 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
307 def test_unicode_in_batch_file(self):
308 """
Steve Dowerf14c28f2018-09-20 13:38:34 -0700309 Test handling of Unicode paths
Steve Dower62409172018-02-19 17:25:24 -0800310 """
311 rmtree(self.env_dir)
312 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
313 builder = venv.EnvBuilder(clear=True)
314 builder.create(env_dir)
315 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
316 envpy = os.path.join(env_dir, self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700317 out, err = check_output(
318 [activate, '&', self.exe, '-c', 'print(0)'],
319 encoding='oem',
320 )
Steve Dower62409172018-02-19 17:25:24 -0800321 self.assertEqual(out.strip(), '0')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000322
Steve Dower8bba81f2019-03-21 10:04:21 -0700323 @requireVenvCreate
Steve Dower4e02f8f82019-01-25 14:59:12 -0800324 def test_multiprocessing(self):
325 """
326 Test that the multiprocessing is able to spawn.
327 """
Victor Stinnere8056182020-06-18 18:56:43 +0200328 # bpo-36342: Instantiation of a Pool object imports the
xdegaye5437ccc2019-05-30 23:42:29 +0200329 # multiprocessing.synchronize module. Skip the test if this module
330 # cannot be imported.
Victor Stinnere8056182020-06-18 18:56:43 +0200331 skip_if_broken_multiprocessing_synchronize()
332
Steve Dower4e02f8f82019-01-25 14:59:12 -0800333 rmtree(self.env_dir)
334 self.run_with_capture(venv.create, self.env_dir)
335 envpy = os.path.join(os.path.realpath(self.env_dir),
336 self.bindir, self.exe)
337 out, err = check_output([envpy, '-c',
Victor Stinnerbc6469f2019-06-04 19:03:13 +0200338 'from multiprocessing import Pool; '
339 'pool = Pool(1); '
340 'print(pool.apply_async("Python".lower).get(3)); '
341 'pool.terminate()'])
Steve Dower4e02f8f82019-01-25 14:59:12 -0800342 self.assertEqual(out.strip(), "python".encode())
343
Miss Islington (bot)63eefc32019-09-11 08:55:57 -0700344 @unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
345 def test_deactivate_with_strict_bash_opts(self):
346 bash = shutil.which("bash")
347 if bash is None:
348 self.skipTest("bash required for this test")
349 rmtree(self.env_dir)
350 builder = venv.EnvBuilder(clear=True)
351 builder.create(self.env_dir)
352 activate = os.path.join(self.env_dir, self.bindir, "activate")
353 test_script = os.path.join(self.env_dir, "test_strict.sh")
354 with open(test_script, "w") as f:
355 f.write("set -euo pipefail\n"
356 f"source {activate}\n"
357 "deactivate\n")
358 out, err = check_output([bash, test_script])
359 self.assertEqual(out, "".encode())
360 self.assertEqual(err, "".encode())
361
362
Miss Islington (bot)c959fa92020-03-22 11:56:26 -0700363 @unittest.skipUnless(sys.platform == 'darwin', 'only relevant on macOS')
364 def test_macos_env(self):
365 rmtree(self.env_dir)
366 builder = venv.EnvBuilder()
367 builder.create(self.env_dir)
368
369 envpy = os.path.join(os.path.realpath(self.env_dir),
370 self.bindir, self.exe)
371 out, err = check_output([envpy, '-c',
372 'import os; print("__PYVENV_LAUNCHER__" in os.environ)'])
373 self.assertEqual(out.strip(), 'False'.encode())
374
Steve Dower8bba81f2019-03-21 10:04:21 -0700375@requireVenvCreate
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000376class EnsurePipTest(BaseTest):
377 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000378 def assert_pip_not_installed(self):
379 envpy = os.path.join(os.path.realpath(self.env_dir),
380 self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700381 out, err = check_output([envpy, '-c',
382 'try:\n import pip\nexcept ImportError:\n print("OK")'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000383 # We force everything to text, so unittest gives the detailed diff
384 # if we get unexpected results
385 err = err.decode("latin-1") # Force to text, prevent decoding errors
386 self.assertEqual(err, "")
387 out = out.decode("latin-1") # Force to text, prevent decoding errors
388 self.assertEqual(out.strip(), "OK")
389
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000390
391 def test_no_pip_by_default(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200392 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000393 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000394 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000395
396 def test_explicit_no_pip(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200397 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000398 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000399 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000400
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100401 def test_devnull(self):
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000402 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000403 # appear empty. However http://bugs.python.org/issue20541 means
404 # that doesn't currently work properly on Windows. Once that is
405 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000406 with open(os.devnull, "rb") as f:
407 self.assertEqual(f.read(), b"")
408
Steve Dower9eb3d542019-08-21 15:52:42 -0700409 self.assertTrue(os.path.exists(os.devnull))
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100410
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000411 def do_test_with_pip(self, system_site_packages):
Victor Stinner866c4e22014-10-10 14:23:00 +0200412 rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000413 with EnvironmentVarGuard() as envvars:
414 # pip's cross-version compatibility may trigger deprecation
415 # warnings in current versions of Python. Ensure related
416 # environment settings don't cause venv to fail.
417 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000418 # ensurepip is different enough from a normal pip invocation
419 # that we want to ensure it ignores the normal pip environment
420 # variable settings. We set PIP_NO_INSTALL here specifically
421 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000422 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000423 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000424 # Also check that we ignore the pip configuration file
425 # See http://bugs.python.org/issue20053
426 with tempfile.TemporaryDirectory() as home_dir:
427 envvars["HOME"] = home_dir
428 bad_config = "[global]\nno-install=1"
429 # Write to both config file names on all platforms to reduce
430 # cross-platform variation in test code behaviour
431 win_location = ("pip", "pip.ini")
432 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000433 # Skips win_location due to http://bugs.python.org/issue20541
434 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000435 dirpath = os.path.join(home_dir, dirname)
436 os.mkdir(dirpath)
437 fpath = os.path.join(dirpath, fname)
438 with open(fpath, 'w') as f:
439 f.write(bad_config)
440
441 # Actually run the create command with all that unhelpful
442 # config in place to ensure we ignore it
443 try:
444 self.run_with_capture(venv.create, self.env_dir,
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000445 system_site_packages=system_site_packages,
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000446 with_pip=True)
447 except subprocess.CalledProcessError as exc:
448 # The output this produces can be a little hard to read,
449 # but at least it has all the details
450 details = exc.output.decode(errors="replace")
451 msg = "{}\n\n**Subprocess Output**\n{}"
452 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000453 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000454 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Victor Stinner895862a2017-11-20 09:47:03 -0800455 # Ignore DeprecationWarning since pip code is not part of Python
Steve Dowerf14c28f2018-09-20 13:38:34 -0700456 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
457 '-m', 'pip', '--version'])
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000458 # We force everything to text, so unittest gives the detailed diff
459 # if we get unexpected results
460 err = err.decode("latin-1") # Force to text, prevent decoding errors
461 self.assertEqual(err, "")
462 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000463 expected_version = "pip {}".format(ensurepip.version())
464 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000465 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000466 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000467
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000468 # http://bugs.python.org/issue19728
469 # Check the private uninstall command provided for the Windows
470 # installers works (at least in a virtual environment)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000471 with EnvironmentVarGuard() as envvars:
Steve Dowerf14c28f2018-09-20 13:38:34 -0700472 out, err = check_output([envpy,
473 '-W', 'ignore::DeprecationWarning', '-I',
474 '-m', 'ensurepip._uninstall'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000475 # We force everything to text, so unittest gives the detailed diff
476 # if we get unexpected results
477 err = err.decode("latin-1") # Force to text, prevent decoding errors
Victor Stinner87d6e132016-03-14 18:21:58 +0100478 # Ignore the warning:
479 # "The directory '$HOME/.cache/pip/http' or its parent directory
480 # is not owned by the current user and the cache has been disabled.
481 # Please check the permissions and owner of that directory. If
482 # executing pip with sudo, you may want sudo's -H flag."
483 # where $HOME is replaced by the HOME environment variable.
Miss Islington (bot)c5033902019-07-26 09:24:43 -0700484 err = re.sub("^(WARNING: )?The directory .* or its parent directory "
Ned Deilye63cc2f2020-06-15 17:42:22 -0400485 "is not owned or is not writable by the current user.*$", "",
Miss Islington (bot)c5033902019-07-26 09:24:43 -0700486 err, flags=re.MULTILINE)
Victor Stinner87d6e132016-03-14 18:21:58 +0100487 self.assertEqual(err.rstrip(), "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000488 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000489 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000490 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000491 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000492 self.assertIn("Successfully uninstalled pip", out)
493 self.assertIn("Successfully uninstalled setuptools", out)
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000494 # Check pip is now gone from the virtual environment. This only
495 # applies in the system_site_packages=False case, because in the
496 # other case, pip may still be available in the system site-packages
497 if not system_site_packages:
498 self.assert_pip_not_installed()
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000499
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000500 # Issue #26610: pip/pep425tags.py requires ctypes
501 @unittest.skipUnless(ctypes, 'pip requires ctypes')
Serhiy Storchaka5e0df742017-11-10 12:09:39 +0200502 @requires_zlib
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000503 def test_with_pip(self):
504 self.do_test_with_pip(False)
505 self.do_test_with_pip(True)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000506
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100507if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500508 unittest.main()