blob: 6822d567e42b58883b68cbeca7629ed46217b2ef [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,
Victor Stinner866c4e22014-10-10 14:23:00 +020017 can_symlink, EnvironmentVarGuard, rmtree)
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020018import threading
Vinay Sajip7ded1f02012-05-26 03:45:29 +010019import unittest
20import venv
Nick Coghlanae2ee962013-12-23 23:07:07 +100021
Victor Stinnerb3477882016-03-25 12:27:02 +010022try:
23 import ctypes
24except ImportError:
25 ctypes = None
26
Steve Dower8bba81f2019-03-21 10:04:21 -070027# Platforms that set sys._base_executable can create venvs from within
28# another venv, so no need to skip tests that require venv.create().
29requireVenvCreate = unittest.skipUnless(
30 hasattr(sys, '_base_executable')
31 or sys.prefix == sys.base_prefix,
32 'cannot run venv.create from within a venv on this platform')
Nick Coghlan8fbdb092013-11-23 00:30:34 +100033
Steve Dowerf14c28f2018-09-20 13:38:34 -070034def check_output(cmd, encoding=None):
35 p = subprocess.Popen(cmd,
36 stdout=subprocess.PIPE,
37 stderr=subprocess.PIPE,
38 encoding=encoding)
39 out, err = p.communicate()
40 if p.returncode:
41 raise subprocess.CalledProcessError(
Pablo Galindob9392502018-11-07 22:21:17 +000042 p.returncode, cmd, out, err)
Steve Dowerf14c28f2018-09-20 13:38:34 -070043 return out, err
44
Vinay Sajip7ded1f02012-05-26 03:45:29 +010045class BaseTest(unittest.TestCase):
46 """Base class for venv tests."""
Victor Stinnerbdc337b2016-03-25 12:30:40 +010047 maxDiff = 80 * 50
Vinay Sajip7ded1f02012-05-26 03:45:29 +010048
49 def setUp(self):
Ned Deily045bd532012-07-13 15:48:04 -070050 self.env_dir = os.path.realpath(tempfile.mkdtemp())
Vinay Sajip7ded1f02012-05-26 03:45:29 +010051 if os.name == 'nt':
52 self.bindir = 'Scripts'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010053 self.lib = ('Lib',)
54 self.include = 'Include'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010055 else:
56 self.bindir = 'bin'
Serhiy Storchaka885bdc42016-02-11 13:10:36 +020057 self.lib = ('lib', 'python%d.%d' % sys.version_info[:2])
Vinay Sajip7ded1f02012-05-26 03:45:29 +010058 self.include = 'include'
Steve Dowera8474d02019-02-03 23:19:38 -080059 executable = getattr(sys, '_base_executable', sys.executable)
Vinay Sajip382a7c02012-05-28 16:34:47 +010060 self.exe = os.path.split(executable)[-1]
Vinay Sajip7ded1f02012-05-26 03:45:29 +010061
62 def tearDown(self):
Victor Stinner866c4e22014-10-10 14:23:00 +020063 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010064
65 def run_with_capture(self, func, *args, **kwargs):
66 with captured_stdout() as output:
67 with captured_stderr() as error:
68 func(*args, **kwargs)
69 return output.getvalue(), error.getvalue()
70
71 def get_env_file(self, *args):
72 return os.path.join(self.env_dir, *args)
73
74 def get_text_file_contents(self, *args):
75 with open(self.get_env_file(*args), 'r') as f:
76 result = f.read()
77 return result
78
79class BasicTest(BaseTest):
80 """Test venv module functionality."""
81
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010082 def isdir(self, *args):
83 fn = self.get_env_file(*args)
84 self.assertTrue(os.path.isdir(fn))
85
Vinay Sajip7ded1f02012-05-26 03:45:29 +010086 def test_defaults(self):
87 """
88 Test the create function with default arguments.
89 """
Victor Stinner866c4e22014-10-10 14:23:00 +020090 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010091 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010092 self.isdir(self.bindir)
93 self.isdir(self.include)
94 self.isdir(*self.lib)
Vinay Sajip1e53f8d2014-04-15 11:18:10 +010095 # Issue 21197
96 p = self.get_env_file('lib64')
97 conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
98 (sys.platform != 'darwin'))
99 if conditions:
100 self.assertTrue(os.path.islink(p))
101 else:
102 self.assertFalse(os.path.exists(p))
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100103 data = self.get_text_file_contents('pyvenv.cfg')
Steve Dowera8474d02019-02-03 23:19:38 -0800104 executable = getattr(sys, '_base_executable', sys.executable)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100105 path = os.path.dirname(executable)
106 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100107 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +0100108 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100109 bd = self.get_env_file(self.bindir)
110 print('Contents of %r:' % bd)
111 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +0100112 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100113
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100114 def test_prompt(self):
115 env_name = os.path.split(self.env_dir)[1]
116
Cheryl Sabella839b9252019-03-12 20:15:47 -0400117 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100118 builder = venv.EnvBuilder()
Cheryl Sabella839b9252019-03-12 20:15:47 -0400119 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100120 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500121 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400122 self.assertEqual(context.prompt, '(%s) ' % env_name)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500123 self.assertNotIn("prompt = ", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100124
Cheryl Sabella839b9252019-03-12 20:15:47 -0400125 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100126 builder = venv.EnvBuilder(prompt='My prompt')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400127 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100128 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500129 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400130 self.assertEqual(context.prompt, '(My prompt) ')
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500131 self.assertIn("prompt = 'My prompt'\n", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100132
Steve Dower8bba81f2019-03-21 10:04:21 -0700133 @requireVenvCreate
Vinay Sajip3874e542012-07-03 16:56:40 +0100134 def test_prefixes(self):
135 """
136 Test that the prefix values are as expected.
137 """
138 #check our prefixes
139 self.assertEqual(sys.base_prefix, sys.prefix)
140 self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
141
142 # check a venv's prefixes
Victor Stinner866c4e22014-10-10 14:23:00 +0200143 rmtree(self.env_dir)
Vinay Sajip3874e542012-07-03 16:56:40 +0100144 self.run_with_capture(venv.create, self.env_dir)
145 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
146 cmd = [envpy, '-c', None]
147 for prefix, expected in (
148 ('prefix', self.env_dir),
149 ('prefix', self.env_dir),
150 ('base_prefix', sys.prefix),
151 ('base_exec_prefix', sys.exec_prefix)):
152 cmd[2] = 'import sys; print(sys.%s)' % prefix
Steve Dowerf14c28f2018-09-20 13:38:34 -0700153 out, err = check_output(cmd)
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200154 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100155
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100156 if sys.platform == 'win32':
157 ENV_SUBDIRS = (
158 ('Scripts',),
159 ('Include',),
160 ('Lib',),
161 ('Lib', 'site-packages'),
162 )
163 else:
164 ENV_SUBDIRS = (
165 ('bin',),
166 ('include',),
167 ('lib',),
168 ('lib', 'python%d.%d' % sys.version_info[:2]),
169 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
170 )
171
172 def create_contents(self, paths, filename):
173 """
174 Create some files in the environment which are unrelated
175 to the virtual environment.
176 """
177 for subdirs in paths:
178 d = os.path.join(self.env_dir, *subdirs)
179 os.mkdir(d)
180 fn = os.path.join(d, filename)
181 with open(fn, 'wb') as f:
182 f.write(b'Still here?')
183
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100184 def test_overwrite_existing(self):
185 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100186 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100187 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100188 self.create_contents(self.ENV_SUBDIRS, 'foo')
189 venv.create(self.env_dir)
190 for subdirs in self.ENV_SUBDIRS:
191 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
192 self.assertTrue(os.path.exists(fn))
193 with open(fn, 'rb') as f:
194 self.assertEqual(f.read(), b'Still here?')
195
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100196 builder = venv.EnvBuilder(clear=True)
197 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100198 for subdirs in self.ENV_SUBDIRS:
199 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
200 self.assertFalse(os.path.exists(fn))
201
202 def clear_directory(self, path):
203 for fn in os.listdir(path):
204 fn = os.path.join(path, fn)
205 if os.path.islink(fn) or os.path.isfile(fn):
206 os.remove(fn)
207 elif os.path.isdir(fn):
Victor Stinner866c4e22014-10-10 14:23:00 +0200208 rmtree(fn)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100209
210 def test_unoverwritable_fails(self):
211 #create a file clashing with directories in the env dir
212 for paths in self.ENV_SUBDIRS[:3]:
213 fn = os.path.join(self.env_dir, *paths)
214 with open(fn, 'wb') as f:
215 f.write(b'')
216 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
217 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100218
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100219 def test_upgrade(self):
220 """
221 Test upgrading an existing environment directory.
222 """
Vinay Sajipb9b965f2014-06-03 16:47:51 +0100223 # See Issue #21643: the loop needs to run twice to ensure
224 # that everything works on the upgrade (the first run just creates
225 # the venv).
226 for upgrade in (False, True):
227 builder = venv.EnvBuilder(upgrade=upgrade)
228 self.run_with_capture(builder.create, self.env_dir)
229 self.isdir(self.bindir)
230 self.isdir(self.include)
231 self.isdir(*self.lib)
232 fn = self.get_env_file(self.bindir, self.exe)
233 if not os.path.exists(fn):
234 # diagnostics for Windows buildbot failures
235 bd = self.get_env_file(self.bindir)
236 print('Contents of %r:' % bd)
237 print(' %r' % os.listdir(bd))
238 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100239
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100240 def test_isolation(self):
241 """
242 Test isolation from system site-packages
243 """
244 for ssp, s in ((True, 'true'), (False, 'false')):
245 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
246 builder.create(self.env_dir)
247 data = self.get_text_file_contents('pyvenv.cfg')
248 self.assertIn('include-system-site-packages = %s\n' % s, data)
249
250 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
251 def test_symlinking(self):
252 """
253 Test symlinking works as expected
254 """
255 for usl in (False, True):
256 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100257 builder.create(self.env_dir)
258 fn = self.get_env_file(self.bindir, self.exe)
259 # Don't test when False, because e.g. 'python' is always
260 # symlinked to 'python3.3' in the env, even when symlinking in
261 # general isn't wanted.
262 if usl:
263 self.assertTrue(os.path.islink(fn))
264
265 # If a venv is created from a source build and that venv is used to
266 # run the test, the pyvenv.cfg in the venv created in the test will
267 # point to the venv being used to run the test, and we lose the link
268 # to the source build - so Python can't initialise properly.
Steve Dower8bba81f2019-03-21 10:04:21 -0700269 @requireVenvCreate
Vinay Sajip90db6612012-07-17 17:33:46 +0100270 def test_executable(self):
271 """
272 Test that the sys.executable value is as expected.
273 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200274 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100275 self.run_with_capture(venv.create, self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700276 envpy = os.path.join(os.path.realpath(self.env_dir),
277 self.bindir, self.exe)
278 out, err = check_output([envpy, '-c',
279 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200280 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100281
282 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
283 def test_executable_symlinks(self):
284 """
285 Test that the sys.executable value is as expected.
286 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200287 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100288 builder = venv.EnvBuilder(clear=True, symlinks=True)
289 builder.create(self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700290 envpy = os.path.join(os.path.realpath(self.env_dir),
291 self.bindir, self.exe)
292 out, err = check_output([envpy, '-c',
293 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200294 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100295
Steve Dower62409172018-02-19 17:25:24 -0800296 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
297 def test_unicode_in_batch_file(self):
298 """
Steve Dowerf14c28f2018-09-20 13:38:34 -0700299 Test handling of Unicode paths
Steve Dower62409172018-02-19 17:25:24 -0800300 """
301 rmtree(self.env_dir)
302 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
303 builder = venv.EnvBuilder(clear=True)
304 builder.create(env_dir)
305 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
306 envpy = os.path.join(env_dir, self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700307 out, err = check_output(
308 [activate, '&', self.exe, '-c', 'print(0)'],
309 encoding='oem',
310 )
Steve Dower62409172018-02-19 17:25:24 -0800311 self.assertEqual(out.strip(), '0')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000312
Steve Dower8bba81f2019-03-21 10:04:21 -0700313 @requireVenvCreate
Steve Dower4e02f8f82019-01-25 14:59:12 -0800314 def test_multiprocessing(self):
315 """
316 Test that the multiprocessing is able to spawn.
317 """
318 rmtree(self.env_dir)
319 self.run_with_capture(venv.create, self.env_dir)
320 envpy = os.path.join(os.path.realpath(self.env_dir),
321 self.bindir, self.exe)
322 out, err = check_output([envpy, '-c',
323 'from multiprocessing import Pool; ' +
324 'print(Pool(1).apply_async("Python".lower).get(3))'])
325 self.assertEqual(out.strip(), "python".encode())
326
Steve Dower8bba81f2019-03-21 10:04:21 -0700327@requireVenvCreate
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000328class EnsurePipTest(BaseTest):
329 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000330 def assert_pip_not_installed(self):
331 envpy = os.path.join(os.path.realpath(self.env_dir),
332 self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700333 out, err = check_output([envpy, '-c',
334 'try:\n import pip\nexcept ImportError:\n print("OK")'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000335 # We force everything to text, so unittest gives the detailed diff
336 # if we get unexpected results
337 err = err.decode("latin-1") # Force to text, prevent decoding errors
338 self.assertEqual(err, "")
339 out = out.decode("latin-1") # Force to text, prevent decoding errors
340 self.assertEqual(out.strip(), "OK")
341
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000342
343 def test_no_pip_by_default(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200344 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000345 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000346 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000347
348 def test_explicit_no_pip(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200349 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000350 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000351 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000352
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100353 def test_devnull(self):
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000354 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000355 # appear empty. However http://bugs.python.org/issue20541 means
356 # that doesn't currently work properly on Windows. Once that is
357 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000358 with open(os.devnull, "rb") as f:
359 self.assertEqual(f.read(), b"")
360
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100361 # Issue #20541: os.path.exists('nul') is False on Windows
362 if os.devnull.lower() == 'nul':
363 self.assertFalse(os.path.exists(os.devnull))
364 else:
365 self.assertTrue(os.path.exists(os.devnull))
366
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000367 def do_test_with_pip(self, system_site_packages):
Victor Stinner866c4e22014-10-10 14:23:00 +0200368 rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000369 with EnvironmentVarGuard() as envvars:
370 # pip's cross-version compatibility may trigger deprecation
371 # warnings in current versions of Python. Ensure related
372 # environment settings don't cause venv to fail.
373 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000374 # ensurepip is different enough from a normal pip invocation
375 # that we want to ensure it ignores the normal pip environment
376 # variable settings. We set PIP_NO_INSTALL here specifically
377 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000378 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000379 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000380 # Also check that we ignore the pip configuration file
381 # See http://bugs.python.org/issue20053
382 with tempfile.TemporaryDirectory() as home_dir:
383 envvars["HOME"] = home_dir
384 bad_config = "[global]\nno-install=1"
385 # Write to both config file names on all platforms to reduce
386 # cross-platform variation in test code behaviour
387 win_location = ("pip", "pip.ini")
388 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000389 # Skips win_location due to http://bugs.python.org/issue20541
390 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000391 dirpath = os.path.join(home_dir, dirname)
392 os.mkdir(dirpath)
393 fpath = os.path.join(dirpath, fname)
394 with open(fpath, 'w') as f:
395 f.write(bad_config)
396
397 # Actually run the create command with all that unhelpful
398 # config in place to ensure we ignore it
399 try:
400 self.run_with_capture(venv.create, self.env_dir,
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000401 system_site_packages=system_site_packages,
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000402 with_pip=True)
403 except subprocess.CalledProcessError as exc:
404 # The output this produces can be a little hard to read,
405 # but at least it has all the details
406 details = exc.output.decode(errors="replace")
407 msg = "{}\n\n**Subprocess Output**\n{}"
408 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000409 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000410 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Victor Stinner895862a2017-11-20 09:47:03 -0800411 # Ignore DeprecationWarning since pip code is not part of Python
Steve Dowerf14c28f2018-09-20 13:38:34 -0700412 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
413 '-m', 'pip', '--version'])
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000414 # We force everything to text, so unittest gives the detailed diff
415 # if we get unexpected results
416 err = err.decode("latin-1") # Force to text, prevent decoding errors
417 self.assertEqual(err, "")
418 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000419 expected_version = "pip {}".format(ensurepip.version())
420 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000421 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000422 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000423
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000424 # http://bugs.python.org/issue19728
425 # Check the private uninstall command provided for the Windows
426 # installers works (at least in a virtual environment)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000427 with EnvironmentVarGuard() as envvars:
Steve Dowerf14c28f2018-09-20 13:38:34 -0700428 out, err = check_output([envpy,
429 '-W', 'ignore::DeprecationWarning', '-I',
430 '-m', 'ensurepip._uninstall'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000431 # We force everything to text, so unittest gives the detailed diff
432 # if we get unexpected results
433 err = err.decode("latin-1") # Force to text, prevent decoding errors
Victor Stinner87d6e132016-03-14 18:21:58 +0100434 # Ignore the warning:
435 # "The directory '$HOME/.cache/pip/http' or its parent directory
436 # is not owned by the current user and the cache has been disabled.
437 # Please check the permissions and owner of that directory. If
438 # executing pip with sudo, you may want sudo's -H flag."
439 # where $HOME is replaced by the HOME environment variable.
440 err = re.sub("^The directory .* or its parent directory is not owned "
441 "by the current user .*$", "", err, flags=re.MULTILINE)
442 self.assertEqual(err.rstrip(), "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000443 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000444 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000445 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000446 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000447 self.assertIn("Successfully uninstalled pip", out)
448 self.assertIn("Successfully uninstalled setuptools", out)
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000449 # Check pip is now gone from the virtual environment. This only
450 # applies in the system_site_packages=False case, because in the
451 # other case, pip may still be available in the system site-packages
452 if not system_site_packages:
453 self.assert_pip_not_installed()
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000454
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000455 # Issue #26610: pip/pep425tags.py requires ctypes
456 @unittest.skipUnless(ctypes, 'pip requires ctypes')
Serhiy Storchaka5e0df742017-11-10 12:09:39 +0200457 @requires_zlib
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000458 def test_with_pip(self):
459 self.do_test_with_pip(False)
460 self.do_test_with_pip(True)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000461
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100462if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500463 unittest.main()