blob: 0b2c7a0258df1614f2373d31707baed8ed0a2caf [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
Nick Coghlan8fbdb092013-11-23 00:30:34 +100027skipInVenv = unittest.skipIf(sys.prefix != sys.base_prefix,
28 'Test not appropriate in a venv')
29
Steve Dowerf14c28f2018-09-20 13:38:34 -070030def check_output(cmd, encoding=None):
31 p = subprocess.Popen(cmd,
32 stdout=subprocess.PIPE,
33 stderr=subprocess.PIPE,
34 encoding=encoding)
35 out, err = p.communicate()
36 if p.returncode:
37 raise subprocess.CalledProcessError(
Pablo Galindob9392502018-11-07 22:21:17 +000038 p.returncode, cmd, out, err)
Steve Dowerf14c28f2018-09-20 13:38:34 -070039 return out, err
40
Vinay Sajip7ded1f02012-05-26 03:45:29 +010041class BaseTest(unittest.TestCase):
42 """Base class for venv tests."""
Victor Stinnerbdc337b2016-03-25 12:30:40 +010043 maxDiff = 80 * 50
Vinay Sajip7ded1f02012-05-26 03:45:29 +010044
45 def setUp(self):
Ned Deily045bd532012-07-13 15:48:04 -070046 self.env_dir = os.path.realpath(tempfile.mkdtemp())
Vinay Sajip7ded1f02012-05-26 03:45:29 +010047 if os.name == 'nt':
48 self.bindir = 'Scripts'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010049 self.lib = ('Lib',)
50 self.include = 'Include'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010051 else:
52 self.bindir = 'bin'
Serhiy Storchaka885bdc42016-02-11 13:10:36 +020053 self.lib = ('lib', 'python%d.%d' % sys.version_info[:2])
Vinay Sajip7ded1f02012-05-26 03:45:29 +010054 self.include = 'include'
Steve Dowera8474d02019-02-03 23:19:38 -080055 executable = getattr(sys, '_base_executable', sys.executable)
Vinay Sajip382a7c02012-05-28 16:34:47 +010056 self.exe = os.path.split(executable)[-1]
Vinay Sajip7ded1f02012-05-26 03:45:29 +010057
58 def tearDown(self):
Victor Stinner866c4e22014-10-10 14:23:00 +020059 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010060
61 def run_with_capture(self, func, *args, **kwargs):
62 with captured_stdout() as output:
63 with captured_stderr() as error:
64 func(*args, **kwargs)
65 return output.getvalue(), error.getvalue()
66
67 def get_env_file(self, *args):
68 return os.path.join(self.env_dir, *args)
69
70 def get_text_file_contents(self, *args):
71 with open(self.get_env_file(*args), 'r') as f:
72 result = f.read()
73 return result
74
75class BasicTest(BaseTest):
76 """Test venv module functionality."""
77
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010078 def isdir(self, *args):
79 fn = self.get_env_file(*args)
80 self.assertTrue(os.path.isdir(fn))
81
Vinay Sajip7ded1f02012-05-26 03:45:29 +010082 def test_defaults(self):
83 """
84 Test the create function with default arguments.
85 """
Victor Stinner866c4e22014-10-10 14:23:00 +020086 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010087 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010088 self.isdir(self.bindir)
89 self.isdir(self.include)
90 self.isdir(*self.lib)
Vinay Sajip1e53f8d2014-04-15 11:18:10 +010091 # Issue 21197
92 p = self.get_env_file('lib64')
93 conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
94 (sys.platform != 'darwin'))
95 if conditions:
96 self.assertTrue(os.path.islink(p))
97 else:
98 self.assertFalse(os.path.exists(p))
Vinay Sajip7ded1f02012-05-26 03:45:29 +010099 data = self.get_text_file_contents('pyvenv.cfg')
Steve Dowera8474d02019-02-03 23:19:38 -0800100 executable = getattr(sys, '_base_executable', sys.executable)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100101 path = os.path.dirname(executable)
102 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100103 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +0100104 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100105 bd = self.get_env_file(self.bindir)
106 print('Contents of %r:' % bd)
107 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +0100108 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100109
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100110 def test_prompt(self):
111 env_name = os.path.split(self.env_dir)[1]
112
Cheryl Sabella839b9252019-03-12 20:15:47 -0400113 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100114 builder = venv.EnvBuilder()
Cheryl Sabella839b9252019-03-12 20:15:47 -0400115 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100116 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500117 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400118 self.assertEqual(context.prompt, '(%s) ' % env_name)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500119 self.assertNotIn("prompt = ", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100120
Cheryl Sabella839b9252019-03-12 20:15:47 -0400121 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100122 builder = venv.EnvBuilder(prompt='My prompt')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400123 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100124 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500125 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400126 self.assertEqual(context.prompt, '(My prompt) ')
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500127 self.assertIn("prompt = 'My prompt'\n", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100128
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000129 @skipInVenv
Vinay Sajip3874e542012-07-03 16:56:40 +0100130 def test_prefixes(self):
131 """
132 Test that the prefix values are as expected.
133 """
134 #check our prefixes
135 self.assertEqual(sys.base_prefix, sys.prefix)
136 self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
137
138 # check a venv's prefixes
Victor Stinner866c4e22014-10-10 14:23:00 +0200139 rmtree(self.env_dir)
Vinay Sajip3874e542012-07-03 16:56:40 +0100140 self.run_with_capture(venv.create, self.env_dir)
141 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
142 cmd = [envpy, '-c', None]
143 for prefix, expected in (
144 ('prefix', self.env_dir),
145 ('prefix', self.env_dir),
146 ('base_prefix', sys.prefix),
147 ('base_exec_prefix', sys.exec_prefix)):
148 cmd[2] = 'import sys; print(sys.%s)' % prefix
Steve Dowerf14c28f2018-09-20 13:38:34 -0700149 out, err = check_output(cmd)
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200150 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100151
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100152 if sys.platform == 'win32':
153 ENV_SUBDIRS = (
154 ('Scripts',),
155 ('Include',),
156 ('Lib',),
157 ('Lib', 'site-packages'),
158 )
159 else:
160 ENV_SUBDIRS = (
161 ('bin',),
162 ('include',),
163 ('lib',),
164 ('lib', 'python%d.%d' % sys.version_info[:2]),
165 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
166 )
167
168 def create_contents(self, paths, filename):
169 """
170 Create some files in the environment which are unrelated
171 to the virtual environment.
172 """
173 for subdirs in paths:
174 d = os.path.join(self.env_dir, *subdirs)
175 os.mkdir(d)
176 fn = os.path.join(d, filename)
177 with open(fn, 'wb') as f:
178 f.write(b'Still here?')
179
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100180 def test_overwrite_existing(self):
181 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100182 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100183 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100184 self.create_contents(self.ENV_SUBDIRS, 'foo')
185 venv.create(self.env_dir)
186 for subdirs in self.ENV_SUBDIRS:
187 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
188 self.assertTrue(os.path.exists(fn))
189 with open(fn, 'rb') as f:
190 self.assertEqual(f.read(), b'Still here?')
191
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100192 builder = venv.EnvBuilder(clear=True)
193 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100194 for subdirs in self.ENV_SUBDIRS:
195 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
196 self.assertFalse(os.path.exists(fn))
197
198 def clear_directory(self, path):
199 for fn in os.listdir(path):
200 fn = os.path.join(path, fn)
201 if os.path.islink(fn) or os.path.isfile(fn):
202 os.remove(fn)
203 elif os.path.isdir(fn):
Victor Stinner866c4e22014-10-10 14:23:00 +0200204 rmtree(fn)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100205
206 def test_unoverwritable_fails(self):
207 #create a file clashing with directories in the env dir
208 for paths in self.ENV_SUBDIRS[:3]:
209 fn = os.path.join(self.env_dir, *paths)
210 with open(fn, 'wb') as f:
211 f.write(b'')
212 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
213 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100214
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100215 def test_upgrade(self):
216 """
217 Test upgrading an existing environment directory.
218 """
Vinay Sajipb9b965f2014-06-03 16:47:51 +0100219 # See Issue #21643: the loop needs to run twice to ensure
220 # that everything works on the upgrade (the first run just creates
221 # the venv).
222 for upgrade in (False, True):
223 builder = venv.EnvBuilder(upgrade=upgrade)
224 self.run_with_capture(builder.create, self.env_dir)
225 self.isdir(self.bindir)
226 self.isdir(self.include)
227 self.isdir(*self.lib)
228 fn = self.get_env_file(self.bindir, self.exe)
229 if not os.path.exists(fn):
230 # diagnostics for Windows buildbot failures
231 bd = self.get_env_file(self.bindir)
232 print('Contents of %r:' % bd)
233 print(' %r' % os.listdir(bd))
234 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100235
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100236 def test_isolation(self):
237 """
238 Test isolation from system site-packages
239 """
240 for ssp, s in ((True, 'true'), (False, 'false')):
241 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
242 builder.create(self.env_dir)
243 data = self.get_text_file_contents('pyvenv.cfg')
244 self.assertIn('include-system-site-packages = %s\n' % s, data)
245
246 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
247 def test_symlinking(self):
248 """
249 Test symlinking works as expected
250 """
251 for usl in (False, True):
252 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100253 builder.create(self.env_dir)
254 fn = self.get_env_file(self.bindir, self.exe)
255 # Don't test when False, because e.g. 'python' is always
256 # symlinked to 'python3.3' in the env, even when symlinking in
257 # general isn't wanted.
258 if usl:
259 self.assertTrue(os.path.islink(fn))
260
261 # If a venv is created from a source build and that venv is used to
262 # run the test, the pyvenv.cfg in the venv created in the test will
263 # point to the venv being used to run the test, and we lose the link
264 # to the source build - so Python can't initialise properly.
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000265 @skipInVenv
Vinay Sajip90db6612012-07-17 17:33:46 +0100266 def test_executable(self):
267 """
268 Test that the sys.executable value is as expected.
269 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200270 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100271 self.run_with_capture(venv.create, self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700272 envpy = os.path.join(os.path.realpath(self.env_dir),
273 self.bindir, self.exe)
274 out, err = check_output([envpy, '-c',
275 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200276 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100277
278 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
279 def test_executable_symlinks(self):
280 """
281 Test that the sys.executable value is as expected.
282 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200283 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100284 builder = venv.EnvBuilder(clear=True, symlinks=True)
285 builder.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 Sajip7ded1f02012-05-26 03:45:29 +0100291
Steve Dower62409172018-02-19 17:25:24 -0800292 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
293 def test_unicode_in_batch_file(self):
294 """
Steve Dowerf14c28f2018-09-20 13:38:34 -0700295 Test handling of Unicode paths
Steve Dower62409172018-02-19 17:25:24 -0800296 """
297 rmtree(self.env_dir)
298 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
299 builder = venv.EnvBuilder(clear=True)
300 builder.create(env_dir)
301 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
302 envpy = os.path.join(env_dir, self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700303 out, err = check_output(
304 [activate, '&', self.exe, '-c', 'print(0)'],
305 encoding='oem',
306 )
Steve Dower62409172018-02-19 17:25:24 -0800307 self.assertEqual(out.strip(), '0')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000308
Steve Dower4e02f8f82019-01-25 14:59:12 -0800309 def test_multiprocessing(self):
310 """
311 Test that the multiprocessing is able to spawn.
312 """
313 rmtree(self.env_dir)
314 self.run_with_capture(venv.create, self.env_dir)
315 envpy = os.path.join(os.path.realpath(self.env_dir),
316 self.bindir, self.exe)
317 out, err = check_output([envpy, '-c',
318 'from multiprocessing import Pool; ' +
319 'print(Pool(1).apply_async("Python".lower).get(3))'])
320 self.assertEqual(out.strip(), "python".encode())
321
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000322@skipInVenv
323class EnsurePipTest(BaseTest):
324 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000325 def assert_pip_not_installed(self):
326 envpy = os.path.join(os.path.realpath(self.env_dir),
327 self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700328 out, err = check_output([envpy, '-c',
329 'try:\n import pip\nexcept ImportError:\n print("OK")'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000330 # We force everything to text, so unittest gives the detailed diff
331 # if we get unexpected results
332 err = err.decode("latin-1") # Force to text, prevent decoding errors
333 self.assertEqual(err, "")
334 out = out.decode("latin-1") # Force to text, prevent decoding errors
335 self.assertEqual(out.strip(), "OK")
336
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000337
338 def test_no_pip_by_default(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200339 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000340 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000341 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000342
343 def test_explicit_no_pip(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, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000346 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000347
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100348 def test_devnull(self):
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000349 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000350 # appear empty. However http://bugs.python.org/issue20541 means
351 # that doesn't currently work properly on Windows. Once that is
352 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000353 with open(os.devnull, "rb") as f:
354 self.assertEqual(f.read(), b"")
355
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100356 # Issue #20541: os.path.exists('nul') is False on Windows
357 if os.devnull.lower() == 'nul':
358 self.assertFalse(os.path.exists(os.devnull))
359 else:
360 self.assertTrue(os.path.exists(os.devnull))
361
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000362 def do_test_with_pip(self, system_site_packages):
Victor Stinner866c4e22014-10-10 14:23:00 +0200363 rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000364 with EnvironmentVarGuard() as envvars:
365 # pip's cross-version compatibility may trigger deprecation
366 # warnings in current versions of Python. Ensure related
367 # environment settings don't cause venv to fail.
368 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000369 # ensurepip is different enough from a normal pip invocation
370 # that we want to ensure it ignores the normal pip environment
371 # variable settings. We set PIP_NO_INSTALL here specifically
372 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000373 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000374 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000375 # Also check that we ignore the pip configuration file
376 # See http://bugs.python.org/issue20053
377 with tempfile.TemporaryDirectory() as home_dir:
378 envvars["HOME"] = home_dir
379 bad_config = "[global]\nno-install=1"
380 # Write to both config file names on all platforms to reduce
381 # cross-platform variation in test code behaviour
382 win_location = ("pip", "pip.ini")
383 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000384 # Skips win_location due to http://bugs.python.org/issue20541
385 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000386 dirpath = os.path.join(home_dir, dirname)
387 os.mkdir(dirpath)
388 fpath = os.path.join(dirpath, fname)
389 with open(fpath, 'w') as f:
390 f.write(bad_config)
391
392 # Actually run the create command with all that unhelpful
393 # config in place to ensure we ignore it
394 try:
395 self.run_with_capture(venv.create, self.env_dir,
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000396 system_site_packages=system_site_packages,
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000397 with_pip=True)
398 except subprocess.CalledProcessError as exc:
399 # The output this produces can be a little hard to read,
400 # but at least it has all the details
401 details = exc.output.decode(errors="replace")
402 msg = "{}\n\n**Subprocess Output**\n{}"
403 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000404 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000405 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Victor Stinner895862a2017-11-20 09:47:03 -0800406 # Ignore DeprecationWarning since pip code is not part of Python
Steve Dowerf14c28f2018-09-20 13:38:34 -0700407 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
408 '-m', 'pip', '--version'])
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000409 # We force everything to text, so unittest gives the detailed diff
410 # if we get unexpected results
411 err = err.decode("latin-1") # Force to text, prevent decoding errors
412 self.assertEqual(err, "")
413 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000414 expected_version = "pip {}".format(ensurepip.version())
415 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000416 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000417 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000418
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000419 # http://bugs.python.org/issue19728
420 # Check the private uninstall command provided for the Windows
421 # installers works (at least in a virtual environment)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000422 with EnvironmentVarGuard() as envvars:
Steve Dowerf14c28f2018-09-20 13:38:34 -0700423 out, err = check_output([envpy,
424 '-W', 'ignore::DeprecationWarning', '-I',
425 '-m', 'ensurepip._uninstall'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000426 # We force everything to text, so unittest gives the detailed diff
427 # if we get unexpected results
428 err = err.decode("latin-1") # Force to text, prevent decoding errors
Victor Stinner87d6e132016-03-14 18:21:58 +0100429 # Ignore the warning:
430 # "The directory '$HOME/.cache/pip/http' or its parent directory
431 # is not owned by the current user and the cache has been disabled.
432 # Please check the permissions and owner of that directory. If
433 # executing pip with sudo, you may want sudo's -H flag."
434 # where $HOME is replaced by the HOME environment variable.
435 err = re.sub("^The directory .* or its parent directory is not owned "
436 "by the current user .*$", "", err, flags=re.MULTILINE)
437 self.assertEqual(err.rstrip(), "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000438 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000439 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000440 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000441 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000442 self.assertIn("Successfully uninstalled pip", out)
443 self.assertIn("Successfully uninstalled setuptools", out)
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000444 # Check pip is now gone from the virtual environment. This only
445 # applies in the system_site_packages=False case, because in the
446 # other case, pip may still be available in the system site-packages
447 if not system_site_packages:
448 self.assert_pip_not_installed()
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000449
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000450 # Issue #26610: pip/pep425tags.py requires ctypes
451 @unittest.skipUnless(ctypes, 'pip requires ctypes')
Serhiy Storchaka5e0df742017-11-10 12:09:39 +0200452 @requires_zlib
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000453 def test_with_pip(self):
454 self.do_test_with_pip(False)
455 self.do_test_with_pip(True)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000456
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100457if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500458 unittest.main()