blob: 7130dc6f83091068b1e5eb05e98d5379fbd4d4c6 [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)
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020019import threading
Vinay Sajip7ded1f02012-05-26 03:45:29 +010020import unittest
21import venv
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 Dower323e7432019-06-29 14:28:59 -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 Dower323e7432019-06-29 14:28:59 -070060 executable = sys._base_executable
Vinay Sajip382a7c02012-05-28 16:34:47 +010061 self.exe = os.path.split(executable)[-1]
Steve Dower323e7432019-06-29 14:28:59 -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 Dower323e7432019-06-29 14:28:59 -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
Steve Dower8bba81f2019-03-21 10:04:21 -0700140 @requireVenvCreate
Vinay Sajip3874e542012-07-03 16:56:40 +0100141 def test_prefixes(self):
142 """
143 Test that the prefix values are as expected.
144 """
Vinay Sajip3874e542012-07-03 16:56:40 +0100145 # check a venv's prefixes
Victor Stinner866c4e22014-10-10 14:23:00 +0200146 rmtree(self.env_dir)
Vinay Sajip3874e542012-07-03 16:56:40 +0100147 self.run_with_capture(venv.create, self.env_dir)
148 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
149 cmd = [envpy, '-c', None]
150 for prefix, expected in (
151 ('prefix', self.env_dir),
Steve Dower323e7432019-06-29 14:28:59 -0700152 ('exec_prefix', self.env_dir),
153 ('base_prefix', sys.base_prefix),
154 ('base_exec_prefix', sys.base_exec_prefix)):
Vinay Sajip3874e542012-07-03 16:56:40 +0100155 cmd[2] = 'import sys; print(sys.%s)' % prefix
Steve Dowerf14c28f2018-09-20 13:38:34 -0700156 out, err = check_output(cmd)
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200157 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100158
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100159 if sys.platform == 'win32':
160 ENV_SUBDIRS = (
161 ('Scripts',),
162 ('Include',),
163 ('Lib',),
164 ('Lib', 'site-packages'),
165 )
166 else:
167 ENV_SUBDIRS = (
168 ('bin',),
169 ('include',),
170 ('lib',),
171 ('lib', 'python%d.%d' % sys.version_info[:2]),
172 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
173 )
174
175 def create_contents(self, paths, filename):
176 """
177 Create some files in the environment which are unrelated
178 to the virtual environment.
179 """
180 for subdirs in paths:
181 d = os.path.join(self.env_dir, *subdirs)
182 os.mkdir(d)
183 fn = os.path.join(d, filename)
184 with open(fn, 'wb') as f:
185 f.write(b'Still here?')
186
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100187 def test_overwrite_existing(self):
188 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100189 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100190 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100191 self.create_contents(self.ENV_SUBDIRS, 'foo')
192 venv.create(self.env_dir)
193 for subdirs in self.ENV_SUBDIRS:
194 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
195 self.assertTrue(os.path.exists(fn))
196 with open(fn, 'rb') as f:
197 self.assertEqual(f.read(), b'Still here?')
198
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100199 builder = venv.EnvBuilder(clear=True)
200 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100201 for subdirs in self.ENV_SUBDIRS:
202 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
203 self.assertFalse(os.path.exists(fn))
204
205 def clear_directory(self, path):
206 for fn in os.listdir(path):
207 fn = os.path.join(path, fn)
208 if os.path.islink(fn) or os.path.isfile(fn):
209 os.remove(fn)
210 elif os.path.isdir(fn):
Victor Stinner866c4e22014-10-10 14:23:00 +0200211 rmtree(fn)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100212
213 def test_unoverwritable_fails(self):
214 #create a file clashing with directories in the env dir
215 for paths in self.ENV_SUBDIRS[:3]:
216 fn = os.path.join(self.env_dir, *paths)
217 with open(fn, 'wb') as f:
218 f.write(b'')
219 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
220 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100221
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100222 def test_upgrade(self):
223 """
224 Test upgrading an existing environment directory.
225 """
Vinay Sajipb9b965f2014-06-03 16:47:51 +0100226 # See Issue #21643: the loop needs to run twice to ensure
227 # that everything works on the upgrade (the first run just creates
228 # the venv).
229 for upgrade in (False, True):
230 builder = venv.EnvBuilder(upgrade=upgrade)
231 self.run_with_capture(builder.create, self.env_dir)
232 self.isdir(self.bindir)
233 self.isdir(self.include)
234 self.isdir(*self.lib)
235 fn = self.get_env_file(self.bindir, self.exe)
236 if not os.path.exists(fn):
237 # diagnostics for Windows buildbot failures
238 bd = self.get_env_file(self.bindir)
239 print('Contents of %r:' % bd)
240 print(' %r' % os.listdir(bd))
241 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100242
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100243 def test_isolation(self):
244 """
245 Test isolation from system site-packages
246 """
247 for ssp, s in ((True, 'true'), (False, 'false')):
248 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
249 builder.create(self.env_dir)
250 data = self.get_text_file_contents('pyvenv.cfg')
251 self.assertIn('include-system-site-packages = %s\n' % s, data)
252
253 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
254 def test_symlinking(self):
255 """
256 Test symlinking works as expected
257 """
258 for usl in (False, True):
259 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100260 builder.create(self.env_dir)
261 fn = self.get_env_file(self.bindir, self.exe)
262 # Don't test when False, because e.g. 'python' is always
263 # symlinked to 'python3.3' in the env, even when symlinking in
264 # general isn't wanted.
265 if usl:
Steve Dower323e7432019-06-29 14:28:59 -0700266 if self.cannot_link_exe:
267 # Symlinking is skipped when our executable is already a
268 # special app symlink
269 self.assertFalse(os.path.islink(fn))
270 else:
271 self.assertTrue(os.path.islink(fn))
Vinay Sajip90db6612012-07-17 17:33:46 +0100272
273 # If a venv is created from a source build and that venv is used to
274 # run the test, the pyvenv.cfg in the venv created in the test will
275 # point to the venv being used to run the test, and we lose the link
276 # to the source build - so Python can't initialise properly.
Steve Dower8bba81f2019-03-21 10:04:21 -0700277 @requireVenvCreate
Vinay Sajip90db6612012-07-17 17:33:46 +0100278 def test_executable(self):
279 """
280 Test that the sys.executable value is as expected.
281 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200282 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100283 self.run_with_capture(venv.create, self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700284 envpy = os.path.join(os.path.realpath(self.env_dir),
285 self.bindir, self.exe)
286 out, err = check_output([envpy, '-c',
287 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200288 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100289
290 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
291 def test_executable_symlinks(self):
292 """
293 Test that the sys.executable value is as expected.
294 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200295 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100296 builder = venv.EnvBuilder(clear=True, symlinks=True)
297 builder.create(self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700298 envpy = os.path.join(os.path.realpath(self.env_dir),
299 self.bindir, self.exe)
300 out, err = check_output([envpy, '-c',
301 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200302 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100303
Steve Dower62409172018-02-19 17:25:24 -0800304 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
305 def test_unicode_in_batch_file(self):
306 """
Steve Dowerf14c28f2018-09-20 13:38:34 -0700307 Test handling of Unicode paths
Steve Dower62409172018-02-19 17:25:24 -0800308 """
309 rmtree(self.env_dir)
310 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
311 builder = venv.EnvBuilder(clear=True)
312 builder.create(env_dir)
313 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
314 envpy = os.path.join(env_dir, self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700315 out, err = check_output(
316 [activate, '&', self.exe, '-c', 'print(0)'],
317 encoding='oem',
318 )
Steve Dower62409172018-02-19 17:25:24 -0800319 self.assertEqual(out.strip(), '0')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000320
Steve Dower8bba81f2019-03-21 10:04:21 -0700321 @requireVenvCreate
Steve Dower4e02f8f82019-01-25 14:59:12 -0800322 def test_multiprocessing(self):
323 """
324 Test that the multiprocessing is able to spawn.
325 """
xdegaye5437ccc2019-05-30 23:42:29 +0200326 # Issue bpo-36342: Instanciation of a Pool object imports the
327 # multiprocessing.synchronize module. Skip the test if this module
328 # cannot be imported.
329 import_module('multiprocessing.synchronize')
Steve Dower4e02f8f82019-01-25 14:59:12 -0800330 rmtree(self.env_dir)
331 self.run_with_capture(venv.create, self.env_dir)
332 envpy = os.path.join(os.path.realpath(self.env_dir),
333 self.bindir, self.exe)
334 out, err = check_output([envpy, '-c',
Victor Stinnerbc6469f2019-06-04 19:03:13 +0200335 'from multiprocessing import Pool; '
336 'pool = Pool(1); '
337 'print(pool.apply_async("Python".lower).get(3)); '
338 'pool.terminate()'])
Steve Dower4e02f8f82019-01-25 14:59:12 -0800339 self.assertEqual(out.strip(), "python".encode())
340
Steve Dower8bba81f2019-03-21 10:04:21 -0700341@requireVenvCreate
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000342class EnsurePipTest(BaseTest):
343 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000344 def assert_pip_not_installed(self):
345 envpy = os.path.join(os.path.realpath(self.env_dir),
346 self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700347 out, err = check_output([envpy, '-c',
348 'try:\n import pip\nexcept ImportError:\n print("OK")'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000349 # We force everything to text, so unittest gives the detailed diff
350 # if we get unexpected results
351 err = err.decode("latin-1") # Force to text, prevent decoding errors
352 self.assertEqual(err, "")
353 out = out.decode("latin-1") # Force to text, prevent decoding errors
354 self.assertEqual(out.strip(), "OK")
355
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000356
357 def test_no_pip_by_default(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200358 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000359 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000360 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000361
362 def test_explicit_no_pip(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200363 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000364 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000365 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000366
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100367 def test_devnull(self):
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000368 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000369 # appear empty. However http://bugs.python.org/issue20541 means
370 # that doesn't currently work properly on Windows. Once that is
371 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000372 with open(os.devnull, "rb") as f:
373 self.assertEqual(f.read(), b"")
374
Steve Dower9eb3d542019-08-21 15:52:42 -0700375 self.assertTrue(os.path.exists(os.devnull))
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100376
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000377 def do_test_with_pip(self, system_site_packages):
Victor Stinner866c4e22014-10-10 14:23:00 +0200378 rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000379 with EnvironmentVarGuard() as envvars:
380 # pip's cross-version compatibility may trigger deprecation
381 # warnings in current versions of Python. Ensure related
382 # environment settings don't cause venv to fail.
383 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000384 # ensurepip is different enough from a normal pip invocation
385 # that we want to ensure it ignores the normal pip environment
386 # variable settings. We set PIP_NO_INSTALL here specifically
387 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000388 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000389 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000390 # Also check that we ignore the pip configuration file
391 # See http://bugs.python.org/issue20053
392 with tempfile.TemporaryDirectory() as home_dir:
393 envvars["HOME"] = home_dir
394 bad_config = "[global]\nno-install=1"
395 # Write to both config file names on all platforms to reduce
396 # cross-platform variation in test code behaviour
397 win_location = ("pip", "pip.ini")
398 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000399 # Skips win_location due to http://bugs.python.org/issue20541
400 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000401 dirpath = os.path.join(home_dir, dirname)
402 os.mkdir(dirpath)
403 fpath = os.path.join(dirpath, fname)
404 with open(fpath, 'w') as f:
405 f.write(bad_config)
406
407 # Actually run the create command with all that unhelpful
408 # config in place to ensure we ignore it
409 try:
410 self.run_with_capture(venv.create, self.env_dir,
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000411 system_site_packages=system_site_packages,
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000412 with_pip=True)
413 except subprocess.CalledProcessError as exc:
414 # The output this produces can be a little hard to read,
415 # but at least it has all the details
416 details = exc.output.decode(errors="replace")
417 msg = "{}\n\n**Subprocess Output**\n{}"
418 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000419 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000420 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Victor Stinner895862a2017-11-20 09:47:03 -0800421 # Ignore DeprecationWarning since pip code is not part of Python
Steve Dowerf14c28f2018-09-20 13:38:34 -0700422 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
423 '-m', 'pip', '--version'])
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000424 # We force everything to text, so unittest gives the detailed diff
425 # if we get unexpected results
426 err = err.decode("latin-1") # Force to text, prevent decoding errors
427 self.assertEqual(err, "")
428 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000429 expected_version = "pip {}".format(ensurepip.version())
430 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000431 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000432 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000433
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000434 # http://bugs.python.org/issue19728
435 # Check the private uninstall command provided for the Windows
436 # installers works (at least in a virtual environment)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000437 with EnvironmentVarGuard() as envvars:
Steve Dowerf14c28f2018-09-20 13:38:34 -0700438 out, err = check_output([envpy,
439 '-W', 'ignore::DeprecationWarning', '-I',
440 '-m', 'ensurepip._uninstall'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000441 # We force everything to text, so unittest gives the detailed diff
442 # if we get unexpected results
443 err = err.decode("latin-1") # Force to text, prevent decoding errors
Victor Stinner87d6e132016-03-14 18:21:58 +0100444 # Ignore the warning:
445 # "The directory '$HOME/.cache/pip/http' or its parent directory
446 # is not owned by the current user and the cache has been disabled.
447 # Please check the permissions and owner of that directory. If
448 # executing pip with sudo, you may want sudo's -H flag."
449 # where $HOME is replaced by the HOME environment variable.
Miss Islington (bot)c5033902019-07-26 09:24:43 -0700450 err = re.sub("^(WARNING: )?The directory .* or its parent directory "
451 "is not owned by the current user .*$", "",
452 err, flags=re.MULTILINE)
Victor Stinner87d6e132016-03-14 18:21:58 +0100453 self.assertEqual(err.rstrip(), "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000454 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000455 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000456 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000457 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000458 self.assertIn("Successfully uninstalled pip", out)
459 self.assertIn("Successfully uninstalled setuptools", out)
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000460 # Check pip is now gone from the virtual environment. This only
461 # applies in the system_site_packages=False case, because in the
462 # other case, pip may still be available in the system site-packages
463 if not system_site_packages:
464 self.assert_pip_not_installed()
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000465
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000466 # Issue #26610: pip/pep425tags.py requires ctypes
467 @unittest.skipUnless(ctypes, 'pip requires ctypes')
Serhiy Storchaka5e0df742017-11-10 12:09:39 +0200468 @requires_zlib
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000469 def test_with_pip(self):
470 self.do_test_with_pip(False)
471 self.do_test_with_pip(True)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000472
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100473if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500474 unittest.main()