blob: 24d3a69b1878b5f113c9fcd966edc8bb7e9a533d [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(
31 hasattr(sys, '_base_executable')
32 or sys.prefix == sys.base_prefix,
33 '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 Dowera8474d02019-02-03 23:19:38 -080060 executable = getattr(sys, '_base_executable', sys.executable)
Vinay Sajip382a7c02012-05-28 16:34:47 +010061 self.exe = os.path.split(executable)[-1]
Vinay Sajip7ded1f02012-05-26 03:45:29 +010062
63 def tearDown(self):
Victor Stinner866c4e22014-10-10 14:23:00 +020064 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010065
66 def run_with_capture(self, func, *args, **kwargs):
67 with captured_stdout() as output:
68 with captured_stderr() as error:
69 func(*args, **kwargs)
70 return output.getvalue(), error.getvalue()
71
72 def get_env_file(self, *args):
73 return os.path.join(self.env_dir, *args)
74
75 def get_text_file_contents(self, *args):
76 with open(self.get_env_file(*args), 'r') as f:
77 result = f.read()
78 return result
79
80class BasicTest(BaseTest):
81 """Test venv module functionality."""
82
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010083 def isdir(self, *args):
84 fn = self.get_env_file(*args)
85 self.assertTrue(os.path.isdir(fn))
86
Vinay Sajip7ded1f02012-05-26 03:45:29 +010087 def test_defaults(self):
88 """
89 Test the create function with default arguments.
90 """
Victor Stinner866c4e22014-10-10 14:23:00 +020091 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010092 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010093 self.isdir(self.bindir)
94 self.isdir(self.include)
95 self.isdir(*self.lib)
Vinay Sajip1e53f8d2014-04-15 11:18:10 +010096 # Issue 21197
97 p = self.get_env_file('lib64')
98 conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
99 (sys.platform != 'darwin'))
100 if conditions:
101 self.assertTrue(os.path.islink(p))
102 else:
103 self.assertFalse(os.path.exists(p))
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100104 data = self.get_text_file_contents('pyvenv.cfg')
Steve Dowera8474d02019-02-03 23:19:38 -0800105 executable = getattr(sys, '_base_executable', sys.executable)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100106 path = os.path.dirname(executable)
107 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100108 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +0100109 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100110 bd = self.get_env_file(self.bindir)
111 print('Contents of %r:' % bd)
112 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +0100113 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100114
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100115 def test_prompt(self):
116 env_name = os.path.split(self.env_dir)[1]
117
Cheryl Sabella839b9252019-03-12 20:15:47 -0400118 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100119 builder = venv.EnvBuilder()
Cheryl Sabella839b9252019-03-12 20:15:47 -0400120 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100121 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500122 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400123 self.assertEqual(context.prompt, '(%s) ' % env_name)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500124 self.assertNotIn("prompt = ", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100125
Cheryl Sabella839b9252019-03-12 20:15:47 -0400126 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100127 builder = venv.EnvBuilder(prompt='My prompt')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400128 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100129 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500130 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400131 self.assertEqual(context.prompt, '(My prompt) ')
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500132 self.assertIn("prompt = 'My prompt'\n", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100133
Steve Dower8bba81f2019-03-21 10:04:21 -0700134 @requireVenvCreate
Vinay Sajip3874e542012-07-03 16:56:40 +0100135 def test_prefixes(self):
136 """
137 Test that the prefix values are as expected.
138 """
139 #check our prefixes
140 self.assertEqual(sys.base_prefix, sys.prefix)
141 self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
142
143 # check a venv's prefixes
Victor Stinner866c4e22014-10-10 14:23:00 +0200144 rmtree(self.env_dir)
Vinay Sajip3874e542012-07-03 16:56:40 +0100145 self.run_with_capture(venv.create, self.env_dir)
146 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
147 cmd = [envpy, '-c', None]
148 for prefix, expected in (
149 ('prefix', self.env_dir),
150 ('prefix', self.env_dir),
151 ('base_prefix', sys.prefix),
152 ('base_exec_prefix', sys.exec_prefix)):
153 cmd[2] = 'import sys; print(sys.%s)' % prefix
Steve Dowerf14c28f2018-09-20 13:38:34 -0700154 out, err = check_output(cmd)
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200155 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100156
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100157 if sys.platform == 'win32':
158 ENV_SUBDIRS = (
159 ('Scripts',),
160 ('Include',),
161 ('Lib',),
162 ('Lib', 'site-packages'),
163 )
164 else:
165 ENV_SUBDIRS = (
166 ('bin',),
167 ('include',),
168 ('lib',),
169 ('lib', 'python%d.%d' % sys.version_info[:2]),
170 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
171 )
172
173 def create_contents(self, paths, filename):
174 """
175 Create some files in the environment which are unrelated
176 to the virtual environment.
177 """
178 for subdirs in paths:
179 d = os.path.join(self.env_dir, *subdirs)
180 os.mkdir(d)
181 fn = os.path.join(d, filename)
182 with open(fn, 'wb') as f:
183 f.write(b'Still here?')
184
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100185 def test_overwrite_existing(self):
186 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100187 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100188 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100189 self.create_contents(self.ENV_SUBDIRS, 'foo')
190 venv.create(self.env_dir)
191 for subdirs in self.ENV_SUBDIRS:
192 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
193 self.assertTrue(os.path.exists(fn))
194 with open(fn, 'rb') as f:
195 self.assertEqual(f.read(), b'Still here?')
196
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100197 builder = venv.EnvBuilder(clear=True)
198 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100199 for subdirs in self.ENV_SUBDIRS:
200 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
201 self.assertFalse(os.path.exists(fn))
202
203 def clear_directory(self, path):
204 for fn in os.listdir(path):
205 fn = os.path.join(path, fn)
206 if os.path.islink(fn) or os.path.isfile(fn):
207 os.remove(fn)
208 elif os.path.isdir(fn):
Victor Stinner866c4e22014-10-10 14:23:00 +0200209 rmtree(fn)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100210
211 def test_unoverwritable_fails(self):
212 #create a file clashing with directories in the env dir
213 for paths in self.ENV_SUBDIRS[:3]:
214 fn = os.path.join(self.env_dir, *paths)
215 with open(fn, 'wb') as f:
216 f.write(b'')
217 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
218 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100219
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100220 def test_upgrade(self):
221 """
222 Test upgrading an existing environment directory.
223 """
Vinay Sajipb9b965f2014-06-03 16:47:51 +0100224 # See Issue #21643: the loop needs to run twice to ensure
225 # that everything works on the upgrade (the first run just creates
226 # the venv).
227 for upgrade in (False, True):
228 builder = venv.EnvBuilder(upgrade=upgrade)
229 self.run_with_capture(builder.create, self.env_dir)
230 self.isdir(self.bindir)
231 self.isdir(self.include)
232 self.isdir(*self.lib)
233 fn = self.get_env_file(self.bindir, self.exe)
234 if not os.path.exists(fn):
235 # diagnostics for Windows buildbot failures
236 bd = self.get_env_file(self.bindir)
237 print('Contents of %r:' % bd)
238 print(' %r' % os.listdir(bd))
239 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100240
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100241 def test_isolation(self):
242 """
243 Test isolation from system site-packages
244 """
245 for ssp, s in ((True, 'true'), (False, 'false')):
246 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
247 builder.create(self.env_dir)
248 data = self.get_text_file_contents('pyvenv.cfg')
249 self.assertIn('include-system-site-packages = %s\n' % s, data)
250
251 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
252 def test_symlinking(self):
253 """
254 Test symlinking works as expected
255 """
256 for usl in (False, True):
257 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100258 builder.create(self.env_dir)
259 fn = self.get_env_file(self.bindir, self.exe)
260 # Don't test when False, because e.g. 'python' is always
261 # symlinked to 'python3.3' in the env, even when symlinking in
262 # general isn't wanted.
263 if usl:
264 self.assertTrue(os.path.islink(fn))
265
266 # If a venv is created from a source build and that venv is used to
267 # run the test, the pyvenv.cfg in the venv created in the test will
268 # point to the venv being used to run the test, and we lose the link
269 # to the source build - so Python can't initialise properly.
Steve Dower8bba81f2019-03-21 10:04:21 -0700270 @requireVenvCreate
Vinay Sajip90db6612012-07-17 17:33:46 +0100271 def test_executable(self):
272 """
273 Test that the sys.executable value is as expected.
274 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200275 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100276 self.run_with_capture(venv.create, self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700277 envpy = os.path.join(os.path.realpath(self.env_dir),
278 self.bindir, self.exe)
279 out, err = check_output([envpy, '-c',
280 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200281 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100282
283 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
284 def test_executable_symlinks(self):
285 """
286 Test that the sys.executable value is as expected.
287 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200288 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100289 builder = venv.EnvBuilder(clear=True, symlinks=True)
290 builder.create(self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700291 envpy = os.path.join(os.path.realpath(self.env_dir),
292 self.bindir, self.exe)
293 out, err = check_output([envpy, '-c',
294 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200295 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100296
Steve Dower62409172018-02-19 17:25:24 -0800297 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
298 def test_unicode_in_batch_file(self):
299 """
Steve Dowerf14c28f2018-09-20 13:38:34 -0700300 Test handling of Unicode paths
Steve Dower62409172018-02-19 17:25:24 -0800301 """
302 rmtree(self.env_dir)
303 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
304 builder = venv.EnvBuilder(clear=True)
305 builder.create(env_dir)
306 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
307 envpy = os.path.join(env_dir, self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700308 out, err = check_output(
309 [activate, '&', self.exe, '-c', 'print(0)'],
310 encoding='oem',
311 )
Steve Dower62409172018-02-19 17:25:24 -0800312 self.assertEqual(out.strip(), '0')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000313
Steve Dower8bba81f2019-03-21 10:04:21 -0700314 @requireVenvCreate
Steve Dower4e02f8f82019-01-25 14:59:12 -0800315 def test_multiprocessing(self):
316 """
317 Test that the multiprocessing is able to spawn.
318 """
xdegaye5437ccc2019-05-30 23:42:29 +0200319 # Issue bpo-36342: Instanciation of a Pool object imports the
320 # multiprocessing.synchronize module. Skip the test if this module
321 # cannot be imported.
322 import_module('multiprocessing.synchronize')
Steve Dower4e02f8f82019-01-25 14:59:12 -0800323 rmtree(self.env_dir)
324 self.run_with_capture(venv.create, self.env_dir)
325 envpy = os.path.join(os.path.realpath(self.env_dir),
326 self.bindir, self.exe)
327 out, err = check_output([envpy, '-c',
Victor Stinnerbc6469f2019-06-04 19:03:13 +0200328 'from multiprocessing import Pool; '
329 'pool = Pool(1); '
330 'print(pool.apply_async("Python".lower).get(3)); '
331 'pool.terminate()'])
Steve Dower4e02f8f82019-01-25 14:59:12 -0800332 self.assertEqual(out.strip(), "python".encode())
333
Steve Dower8bba81f2019-03-21 10:04:21 -0700334@requireVenvCreate
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000335class EnsurePipTest(BaseTest):
336 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000337 def assert_pip_not_installed(self):
338 envpy = os.path.join(os.path.realpath(self.env_dir),
339 self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700340 out, err = check_output([envpy, '-c',
341 'try:\n import pip\nexcept ImportError:\n print("OK")'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000342 # We force everything to text, so unittest gives the detailed diff
343 # if we get unexpected results
344 err = err.decode("latin-1") # Force to text, prevent decoding errors
345 self.assertEqual(err, "")
346 out = out.decode("latin-1") # Force to text, prevent decoding errors
347 self.assertEqual(out.strip(), "OK")
348
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000349
350 def test_no_pip_by_default(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200351 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000352 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000353 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000354
355 def test_explicit_no_pip(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200356 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000357 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000358 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000359
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100360 def test_devnull(self):
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000361 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000362 # appear empty. However http://bugs.python.org/issue20541 means
363 # that doesn't currently work properly on Windows. Once that is
364 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000365 with open(os.devnull, "rb") as f:
366 self.assertEqual(f.read(), b"")
367
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100368 # Issue #20541: os.path.exists('nul') is False on Windows
369 if os.devnull.lower() == 'nul':
370 self.assertFalse(os.path.exists(os.devnull))
371 else:
372 self.assertTrue(os.path.exists(os.devnull))
373
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000374 def do_test_with_pip(self, system_site_packages):
Victor Stinner866c4e22014-10-10 14:23:00 +0200375 rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000376 with EnvironmentVarGuard() as envvars:
377 # pip's cross-version compatibility may trigger deprecation
378 # warnings in current versions of Python. Ensure related
379 # environment settings don't cause venv to fail.
380 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000381 # ensurepip is different enough from a normal pip invocation
382 # that we want to ensure it ignores the normal pip environment
383 # variable settings. We set PIP_NO_INSTALL here specifically
384 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000385 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000386 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000387 # Also check that we ignore the pip configuration file
388 # See http://bugs.python.org/issue20053
389 with tempfile.TemporaryDirectory() as home_dir:
390 envvars["HOME"] = home_dir
391 bad_config = "[global]\nno-install=1"
392 # Write to both config file names on all platforms to reduce
393 # cross-platform variation in test code behaviour
394 win_location = ("pip", "pip.ini")
395 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000396 # Skips win_location due to http://bugs.python.org/issue20541
397 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000398 dirpath = os.path.join(home_dir, dirname)
399 os.mkdir(dirpath)
400 fpath = os.path.join(dirpath, fname)
401 with open(fpath, 'w') as f:
402 f.write(bad_config)
403
404 # Actually run the create command with all that unhelpful
405 # config in place to ensure we ignore it
406 try:
407 self.run_with_capture(venv.create, self.env_dir,
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000408 system_site_packages=system_site_packages,
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000409 with_pip=True)
410 except subprocess.CalledProcessError as exc:
411 # The output this produces can be a little hard to read,
412 # but at least it has all the details
413 details = exc.output.decode(errors="replace")
414 msg = "{}\n\n**Subprocess Output**\n{}"
415 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000416 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000417 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Victor Stinner895862a2017-11-20 09:47:03 -0800418 # Ignore DeprecationWarning since pip code is not part of Python
Steve Dowerf14c28f2018-09-20 13:38:34 -0700419 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
420 '-m', 'pip', '--version'])
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000421 # We force everything to text, so unittest gives the detailed diff
422 # if we get unexpected results
423 err = err.decode("latin-1") # Force to text, prevent decoding errors
424 self.assertEqual(err, "")
425 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000426 expected_version = "pip {}".format(ensurepip.version())
427 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000428 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000429 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000430
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000431 # http://bugs.python.org/issue19728
432 # Check the private uninstall command provided for the Windows
433 # installers works (at least in a virtual environment)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000434 with EnvironmentVarGuard() as envvars:
Steve Dowerf14c28f2018-09-20 13:38:34 -0700435 out, err = check_output([envpy,
436 '-W', 'ignore::DeprecationWarning', '-I',
437 '-m', 'ensurepip._uninstall'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000438 # We force everything to text, so unittest gives the detailed diff
439 # if we get unexpected results
440 err = err.decode("latin-1") # Force to text, prevent decoding errors
Victor Stinner87d6e132016-03-14 18:21:58 +0100441 # Ignore the warning:
442 # "The directory '$HOME/.cache/pip/http' or its parent directory
443 # is not owned by the current user and the cache has been disabled.
444 # Please check the permissions and owner of that directory. If
445 # executing pip with sudo, you may want sudo's -H flag."
446 # where $HOME is replaced by the HOME environment variable.
447 err = re.sub("^The directory .* or its parent directory is not owned "
448 "by the current user .*$", "", err, flags=re.MULTILINE)
449 self.assertEqual(err.rstrip(), "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000450 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000451 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000452 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000453 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000454 self.assertIn("Successfully uninstalled pip", out)
455 self.assertIn("Successfully uninstalled setuptools", out)
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000456 # Check pip is now gone from the virtual environment. This only
457 # applies in the system_site_packages=False case, because in the
458 # other case, pip may still be available in the system site-packages
459 if not system_site_packages:
460 self.assert_pip_not_installed()
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000461
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000462 # Issue #26610: pip/pep425tags.py requires ctypes
463 @unittest.skipUnless(ctypes, 'pip requires ctypes')
Serhiy Storchaka5e0df742017-11-10 12:09:39 +0200464 @requires_zlib
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000465 def test_with_pip(self):
466 self.do_test_with_pip(False)
467 self.do_test_with_pip(True)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000468
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100469if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500470 unittest.main()