blob: de93d9539c2cd619962b0dbc0b73162e2ac4e993 [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
Vinay Sajip1e53f8d2014-04-15 11:18:10 +010012import struct
Vinay Sajip3874e542012-07-03 16:56:40 +010013import subprocess
Vinay Sajip7ded1f02012-05-26 03:45:29 +010014import sys
15import tempfile
Serhiy Storchaka5e0df742017-11-10 12:09:39 +020016from test.support import (captured_stdout, captured_stderr, requires_zlib,
xdegaye5437ccc2019-05-30 23:42:29 +020017 can_symlink, EnvironmentVarGuard, rmtree,
18 import_module)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010019import unittest
20import venv
Cooper Lees4acdbf12019-06-17 11:18:14 -070021from unittest.mock import patch
Nick Coghlanae2ee962013-12-23 23:07:07 +100022
Victor Stinnerb3477882016-03-25 12:27:02 +010023try:
24 import ctypes
25except ImportError:
26 ctypes = None
27
Steve Dower8bba81f2019-03-21 10:04:21 -070028# Platforms that set sys._base_executable can create venvs from within
29# another venv, so no need to skip tests that require venv.create().
30requireVenvCreate = unittest.skipUnless(
Steve Dower9048c492019-06-29 10:34:11 -070031 sys.prefix == sys.base_prefix
32 or sys._base_executable != sys.executable,
Steve Dower8bba81f2019-03-21 10:04:21 -070033 'cannot run venv.create from within a venv on this platform')
Nick Coghlan8fbdb092013-11-23 00:30:34 +100034
Steve Dowerf14c28f2018-09-20 13:38:34 -070035def check_output(cmd, encoding=None):
36 p = subprocess.Popen(cmd,
37 stdout=subprocess.PIPE,
38 stderr=subprocess.PIPE,
39 encoding=encoding)
40 out, err = p.communicate()
41 if p.returncode:
42 raise subprocess.CalledProcessError(
Pablo Galindob9392502018-11-07 22:21:17 +000043 p.returncode, cmd, out, err)
Steve Dowerf14c28f2018-09-20 13:38:34 -070044 return out, err
45
Vinay Sajip7ded1f02012-05-26 03:45:29 +010046class BaseTest(unittest.TestCase):
47 """Base class for venv tests."""
Victor Stinnerbdc337b2016-03-25 12:30:40 +010048 maxDiff = 80 * 50
Vinay Sajip7ded1f02012-05-26 03:45:29 +010049
50 def setUp(self):
Ned Deily045bd532012-07-13 15:48:04 -070051 self.env_dir = os.path.realpath(tempfile.mkdtemp())
Vinay Sajip7ded1f02012-05-26 03:45:29 +010052 if os.name == 'nt':
53 self.bindir = 'Scripts'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010054 self.lib = ('Lib',)
55 self.include = 'Include'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010056 else:
57 self.bindir = 'bin'
Serhiy Storchaka885bdc42016-02-11 13:10:36 +020058 self.lib = ('lib', 'python%d.%d' % sys.version_info[:2])
Vinay Sajip7ded1f02012-05-26 03:45:29 +010059 self.include = 'include'
Steve Dower9048c492019-06-29 10:34:11 -070060 executable = sys._base_executable
Vinay Sajip382a7c02012-05-28 16:34:47 +010061 self.exe = os.path.split(executable)[-1]
Steve Dower9048c492019-06-29 10:34:11 -070062 if (sys.platform == 'win32'
63 and os.path.lexists(executable)
64 and not os.path.exists(executable)):
65 self.cannot_link_exe = True
66 else:
67 self.cannot_link_exe = False
Vinay Sajip7ded1f02012-05-26 03:45:29 +010068
69 def tearDown(self):
Victor Stinner866c4e22014-10-10 14:23:00 +020070 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010071
72 def run_with_capture(self, func, *args, **kwargs):
73 with captured_stdout() as output:
74 with captured_stderr() as error:
75 func(*args, **kwargs)
76 return output.getvalue(), error.getvalue()
77
78 def get_env_file(self, *args):
79 return os.path.join(self.env_dir, *args)
80
81 def get_text_file_contents(self, *args):
82 with open(self.get_env_file(*args), 'r') as f:
83 result = f.read()
84 return result
85
86class BasicTest(BaseTest):
87 """Test venv module functionality."""
88
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010089 def isdir(self, *args):
90 fn = self.get_env_file(*args)
91 self.assertTrue(os.path.isdir(fn))
92
Vinay Sajip7ded1f02012-05-26 03:45:29 +010093 def test_defaults(self):
94 """
95 Test the create function with default arguments.
96 """
Victor Stinner866c4e22014-10-10 14:23:00 +020097 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010098 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010099 self.isdir(self.bindir)
100 self.isdir(self.include)
101 self.isdir(*self.lib)
Vinay Sajip1e53f8d2014-04-15 11:18:10 +0100102 # Issue 21197
103 p = self.get_env_file('lib64')
104 conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
105 (sys.platform != 'darwin'))
106 if conditions:
107 self.assertTrue(os.path.islink(p))
108 else:
109 self.assertFalse(os.path.exists(p))
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100110 data = self.get_text_file_contents('pyvenv.cfg')
Steve Dower9048c492019-06-29 10:34:11 -0700111 executable = sys._base_executable
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100112 path = os.path.dirname(executable)
113 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100114 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +0100115 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100116 bd = self.get_env_file(self.bindir)
117 print('Contents of %r:' % bd)
118 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +0100119 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100120
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100121 def test_prompt(self):
122 env_name = os.path.split(self.env_dir)[1]
123
Cheryl Sabella839b9252019-03-12 20:15:47 -0400124 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100125 builder = venv.EnvBuilder()
Cheryl Sabella839b9252019-03-12 20:15:47 -0400126 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100127 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500128 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400129 self.assertEqual(context.prompt, '(%s) ' % env_name)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500130 self.assertNotIn("prompt = ", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100131
Cheryl Sabella839b9252019-03-12 20:15:47 -0400132 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100133 builder = venv.EnvBuilder(prompt='My prompt')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400134 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100135 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500136 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400137 self.assertEqual(context.prompt, '(My prompt) ')
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500138 self.assertIn("prompt = 'My prompt'\n", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100139
Cooper Lees4acdbf12019-06-17 11:18:14 -0700140 def test_upgrade_dependencies(self):
141 builder = venv.EnvBuilder()
142 bin_path = 'Scripts' if sys.platform == 'win32' else 'bin'
143 pip_exe = 'pip.exe' if sys.platform == 'win32' else 'pip'
144 with tempfile.TemporaryDirectory() as fake_env_dir:
145
146 def pip_cmd_checker(cmd):
147 self.assertEqual(
148 cmd,
149 [
150 os.path.join(fake_env_dir, bin_path, pip_exe),
151 'install',
152 '-U',
153 'pip',
154 'setuptools'
155 ]
156 )
157
158 fake_context = builder.ensure_directories(fake_env_dir)
159 with patch('venv.subprocess.check_call', pip_cmd_checker):
160 builder.upgrade_dependencies(fake_context)
161
Steve Dower8bba81f2019-03-21 10:04:21 -0700162 @requireVenvCreate
Vinay Sajip3874e542012-07-03 16:56:40 +0100163 def test_prefixes(self):
164 """
165 Test that the prefix values are as expected.
166 """
Vinay Sajip3874e542012-07-03 16:56:40 +0100167 # check a venv's prefixes
Victor Stinner866c4e22014-10-10 14:23:00 +0200168 rmtree(self.env_dir)
Vinay Sajip3874e542012-07-03 16:56:40 +0100169 self.run_with_capture(venv.create, self.env_dir)
170 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
171 cmd = [envpy, '-c', None]
172 for prefix, expected in (
173 ('prefix', self.env_dir),
Steve Dower9048c492019-06-29 10:34:11 -0700174 ('exec_prefix', self.env_dir),
175 ('base_prefix', sys.base_prefix),
176 ('base_exec_prefix', sys.base_exec_prefix)):
Vinay Sajip3874e542012-07-03 16:56:40 +0100177 cmd[2] = 'import sys; print(sys.%s)' % prefix
Steve Dowerf14c28f2018-09-20 13:38:34 -0700178 out, err = check_output(cmd)
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200179 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100180
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100181 if sys.platform == 'win32':
182 ENV_SUBDIRS = (
183 ('Scripts',),
184 ('Include',),
185 ('Lib',),
186 ('Lib', 'site-packages'),
187 )
188 else:
189 ENV_SUBDIRS = (
190 ('bin',),
191 ('include',),
192 ('lib',),
193 ('lib', 'python%d.%d' % sys.version_info[:2]),
194 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
195 )
196
197 def create_contents(self, paths, filename):
198 """
199 Create some files in the environment which are unrelated
200 to the virtual environment.
201 """
202 for subdirs in paths:
203 d = os.path.join(self.env_dir, *subdirs)
204 os.mkdir(d)
205 fn = os.path.join(d, filename)
206 with open(fn, 'wb') as f:
207 f.write(b'Still here?')
208
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100209 def test_overwrite_existing(self):
210 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100211 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100212 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100213 self.create_contents(self.ENV_SUBDIRS, 'foo')
214 venv.create(self.env_dir)
215 for subdirs in self.ENV_SUBDIRS:
216 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
217 self.assertTrue(os.path.exists(fn))
218 with open(fn, 'rb') as f:
219 self.assertEqual(f.read(), b'Still here?')
220
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100221 builder = venv.EnvBuilder(clear=True)
222 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100223 for subdirs in self.ENV_SUBDIRS:
224 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
225 self.assertFalse(os.path.exists(fn))
226
227 def clear_directory(self, path):
228 for fn in os.listdir(path):
229 fn = os.path.join(path, fn)
230 if os.path.islink(fn) or os.path.isfile(fn):
231 os.remove(fn)
232 elif os.path.isdir(fn):
Victor Stinner866c4e22014-10-10 14:23:00 +0200233 rmtree(fn)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100234
235 def test_unoverwritable_fails(self):
236 #create a file clashing with directories in the env dir
237 for paths in self.ENV_SUBDIRS[:3]:
238 fn = os.path.join(self.env_dir, *paths)
239 with open(fn, 'wb') as f:
240 f.write(b'')
241 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
242 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100243
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100244 def test_upgrade(self):
245 """
246 Test upgrading an existing environment directory.
247 """
Vinay Sajipb9b965f2014-06-03 16:47:51 +0100248 # See Issue #21643: the loop needs to run twice to ensure
249 # that everything works on the upgrade (the first run just creates
250 # the venv).
251 for upgrade in (False, True):
252 builder = venv.EnvBuilder(upgrade=upgrade)
253 self.run_with_capture(builder.create, self.env_dir)
254 self.isdir(self.bindir)
255 self.isdir(self.include)
256 self.isdir(*self.lib)
257 fn = self.get_env_file(self.bindir, self.exe)
258 if not os.path.exists(fn):
259 # diagnostics for Windows buildbot failures
260 bd = self.get_env_file(self.bindir)
261 print('Contents of %r:' % bd)
262 print(' %r' % os.listdir(bd))
263 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100264
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100265 def test_isolation(self):
266 """
267 Test isolation from system site-packages
268 """
269 for ssp, s in ((True, 'true'), (False, 'false')):
270 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
271 builder.create(self.env_dir)
272 data = self.get_text_file_contents('pyvenv.cfg')
273 self.assertIn('include-system-site-packages = %s\n' % s, data)
274
275 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
276 def test_symlinking(self):
277 """
278 Test symlinking works as expected
279 """
280 for usl in (False, True):
281 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100282 builder.create(self.env_dir)
283 fn = self.get_env_file(self.bindir, self.exe)
284 # Don't test when False, because e.g. 'python' is always
285 # symlinked to 'python3.3' in the env, even when symlinking in
286 # general isn't wanted.
287 if usl:
Steve Dower9048c492019-06-29 10:34:11 -0700288 if self.cannot_link_exe:
289 # Symlinking is skipped when our executable is already a
290 # special app symlink
291 self.assertFalse(os.path.islink(fn))
292 else:
293 self.assertTrue(os.path.islink(fn))
Vinay Sajip90db6612012-07-17 17:33:46 +0100294
295 # If a venv is created from a source build and that venv is used to
296 # run the test, the pyvenv.cfg in the venv created in the test will
297 # point to the venv being used to run the test, and we lose the link
298 # to the source build - so Python can't initialise properly.
Steve Dower8bba81f2019-03-21 10:04:21 -0700299 @requireVenvCreate
Vinay Sajip90db6612012-07-17 17:33:46 +0100300 def test_executable(self):
301 """
302 Test that the sys.executable value is as expected.
303 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200304 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100305 self.run_with_capture(venv.create, self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700306 envpy = os.path.join(os.path.realpath(self.env_dir),
307 self.bindir, self.exe)
308 out, err = check_output([envpy, '-c',
309 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200310 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100311
312 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
313 def test_executable_symlinks(self):
314 """
315 Test that the sys.executable value is as expected.
316 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200317 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100318 builder = venv.EnvBuilder(clear=True, symlinks=True)
319 builder.create(self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700320 envpy = os.path.join(os.path.realpath(self.env_dir),
321 self.bindir, self.exe)
322 out, err = check_output([envpy, '-c',
323 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200324 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100325
Steve Dower62409172018-02-19 17:25:24 -0800326 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
327 def test_unicode_in_batch_file(self):
328 """
Steve Dowerf14c28f2018-09-20 13:38:34 -0700329 Test handling of Unicode paths
Steve Dower62409172018-02-19 17:25:24 -0800330 """
331 rmtree(self.env_dir)
332 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
333 builder = venv.EnvBuilder(clear=True)
334 builder.create(env_dir)
335 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
336 envpy = os.path.join(env_dir, self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700337 out, err = check_output(
338 [activate, '&', self.exe, '-c', 'print(0)'],
339 encoding='oem',
340 )
Steve Dower62409172018-02-19 17:25:24 -0800341 self.assertEqual(out.strip(), '0')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000342
Steve Dower8bba81f2019-03-21 10:04:21 -0700343 @requireVenvCreate
Steve Dower4e02f8f82019-01-25 14:59:12 -0800344 def test_multiprocessing(self):
345 """
346 Test that the multiprocessing is able to spawn.
347 """
Min ho Kimc4cacc82019-07-31 08:16:13 +1000348 # Issue bpo-36342: Instantiation of a Pool object imports the
xdegaye5437ccc2019-05-30 23:42:29 +0200349 # multiprocessing.synchronize module. Skip the test if this module
350 # cannot be imported.
351 import_module('multiprocessing.synchronize')
Steve Dower4e02f8f82019-01-25 14:59:12 -0800352 rmtree(self.env_dir)
353 self.run_with_capture(venv.create, self.env_dir)
354 envpy = os.path.join(os.path.realpath(self.env_dir),
355 self.bindir, self.exe)
356 out, err = check_output([envpy, '-c',
Victor Stinnerbc6469f2019-06-04 19:03:13 +0200357 'from multiprocessing import Pool; '
358 'pool = Pool(1); '
359 'print(pool.apply_async("Python".lower).get(3)); '
360 'pool.terminate()'])
Steve Dower4e02f8f82019-01-25 14:59:12 -0800361 self.assertEqual(out.strip(), "python".encode())
362
Steve Dower8bba81f2019-03-21 10:04:21 -0700363@requireVenvCreate
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000364class EnsurePipTest(BaseTest):
365 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000366 def assert_pip_not_installed(self):
367 envpy = os.path.join(os.path.realpath(self.env_dir),
368 self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700369 out, err = check_output([envpy, '-c',
370 'try:\n import pip\nexcept ImportError:\n print("OK")'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000371 # We force everything to text, so unittest gives the detailed diff
372 # if we get unexpected results
373 err = err.decode("latin-1") # Force to text, prevent decoding errors
374 self.assertEqual(err, "")
375 out = out.decode("latin-1") # Force to text, prevent decoding errors
376 self.assertEqual(out.strip(), "OK")
377
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000378
379 def test_no_pip_by_default(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200380 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000381 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000382 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000383
384 def test_explicit_no_pip(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200385 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000386 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000387 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000388
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100389 def test_devnull(self):
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000390 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000391 # appear empty. However http://bugs.python.org/issue20541 means
392 # that doesn't currently work properly on Windows. Once that is
393 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000394 with open(os.devnull, "rb") as f:
395 self.assertEqual(f.read(), b"")
396
Steve Dowerdf2d4a62019-08-21 15:27:33 -0700397 self.assertTrue(os.path.exists(os.devnull))
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100398
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000399 def do_test_with_pip(self, system_site_packages):
Victor Stinner866c4e22014-10-10 14:23:00 +0200400 rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000401 with EnvironmentVarGuard() as envvars:
402 # pip's cross-version compatibility may trigger deprecation
403 # warnings in current versions of Python. Ensure related
404 # environment settings don't cause venv to fail.
405 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000406 # ensurepip is different enough from a normal pip invocation
407 # that we want to ensure it ignores the normal pip environment
408 # variable settings. We set PIP_NO_INSTALL here specifically
409 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000410 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000411 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000412 # Also check that we ignore the pip configuration file
413 # See http://bugs.python.org/issue20053
414 with tempfile.TemporaryDirectory() as home_dir:
415 envvars["HOME"] = home_dir
416 bad_config = "[global]\nno-install=1"
417 # Write to both config file names on all platforms to reduce
418 # cross-platform variation in test code behaviour
419 win_location = ("pip", "pip.ini")
420 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000421 # Skips win_location due to http://bugs.python.org/issue20541
422 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000423 dirpath = os.path.join(home_dir, dirname)
424 os.mkdir(dirpath)
425 fpath = os.path.join(dirpath, fname)
426 with open(fpath, 'w') as f:
427 f.write(bad_config)
428
429 # Actually run the create command with all that unhelpful
430 # config in place to ensure we ignore it
431 try:
432 self.run_with_capture(venv.create, self.env_dir,
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000433 system_site_packages=system_site_packages,
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000434 with_pip=True)
435 except subprocess.CalledProcessError as exc:
436 # The output this produces can be a little hard to read,
437 # but at least it has all the details
438 details = exc.output.decode(errors="replace")
439 msg = "{}\n\n**Subprocess Output**\n{}"
440 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000441 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000442 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Victor Stinner895862a2017-11-20 09:47:03 -0800443 # Ignore DeprecationWarning since pip code is not part of Python
Steve Dowerf14c28f2018-09-20 13:38:34 -0700444 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
445 '-m', 'pip', '--version'])
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000446 # We force everything to text, so unittest gives the detailed diff
447 # if we get unexpected results
448 err = err.decode("latin-1") # Force to text, prevent decoding errors
449 self.assertEqual(err, "")
450 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000451 expected_version = "pip {}".format(ensurepip.version())
452 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000453 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000454 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000455
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000456 # http://bugs.python.org/issue19728
457 # Check the private uninstall command provided for the Windows
458 # installers works (at least in a virtual environment)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000459 with EnvironmentVarGuard() as envvars:
Steve Dowerf14c28f2018-09-20 13:38:34 -0700460 out, err = check_output([envpy,
461 '-W', 'ignore::DeprecationWarning', '-I',
462 '-m', 'ensurepip._uninstall'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000463 # We force everything to text, so unittest gives the detailed diff
464 # if we get unexpected results
465 err = err.decode("latin-1") # Force to text, prevent decoding errors
Victor Stinner87d6e132016-03-14 18:21:58 +0100466 # Ignore the warning:
467 # "The directory '$HOME/.cache/pip/http' or its parent directory
468 # is not owned by the current user and the cache has been disabled.
469 # Please check the permissions and owner of that directory. If
470 # executing pip with sudo, you may want sudo's -H flag."
471 # where $HOME is replaced by the HOME environment variable.
Steve Dowerb1eb20e2019-07-26 09:06:04 -0700472 err = re.sub("^(WARNING: )?The directory .* or its parent directory "
473 "is not owned by the current user .*$", "",
474 err, flags=re.MULTILINE)
Victor Stinner87d6e132016-03-14 18:21:58 +0100475 self.assertEqual(err.rstrip(), "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000476 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000477 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000478 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000479 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000480 self.assertIn("Successfully uninstalled pip", out)
481 self.assertIn("Successfully uninstalled setuptools", out)
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000482 # Check pip is now gone from the virtual environment. This only
483 # applies in the system_site_packages=False case, because in the
484 # other case, pip may still be available in the system site-packages
485 if not system_site_packages:
486 self.assert_pip_not_installed()
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000487
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000488 # Issue #26610: pip/pep425tags.py requires ctypes
489 @unittest.skipUnless(ctypes, 'pip requires ctypes')
Serhiy Storchaka5e0df742017-11-10 12:09:39 +0200490 @requires_zlib
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000491 def test_with_pip(self):
492 self.do_test_with_pip(False)
493 self.do_test_with_pip(True)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000494
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100495if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500496 unittest.main()