blob: 741ac109bbc8c5ac79912960b179a7ad2b565248 [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
Daniel Abrahamsson5209e582019-09-11 16:58:56 +020012import shutil
Vinay Sajip1e53f8d2014-04-15 11:18:10 +010013import struct
Vinay Sajip3874e542012-07-03 16:56:40 +010014import subprocess
Vinay Sajip7ded1f02012-05-26 03:45:29 +010015import sys
16import tempfile
Serhiy Storchaka5e0df742017-11-10 12:09:39 +020017from test.support import (captured_stdout, captured_stderr, requires_zlib,
xdegaye5437ccc2019-05-30 23:42:29 +020018 can_symlink, EnvironmentVarGuard, rmtree,
19 import_module)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010020import unittest
21import venv
Cooper Lees4acdbf12019-06-17 11:18:14 -070022from unittest.mock import patch
Nick Coghlanae2ee962013-12-23 23:07:07 +100023
Victor Stinnerb3477882016-03-25 12:27:02 +010024try:
25 import ctypes
26except ImportError:
27 ctypes = None
28
Steve Dower8bba81f2019-03-21 10:04:21 -070029# Platforms that set sys._base_executable can create venvs from within
30# another venv, so no need to skip tests that require venv.create().
31requireVenvCreate = unittest.skipUnless(
Steve Dower9048c492019-06-29 10:34:11 -070032 sys.prefix == sys.base_prefix
33 or sys._base_executable != sys.executable,
Steve Dower8bba81f2019-03-21 10:04:21 -070034 'cannot run venv.create from within a venv on this platform')
Nick Coghlan8fbdb092013-11-23 00:30:34 +100035
Steve Dowerf14c28f2018-09-20 13:38:34 -070036def check_output(cmd, encoding=None):
37 p = subprocess.Popen(cmd,
38 stdout=subprocess.PIPE,
39 stderr=subprocess.PIPE,
40 encoding=encoding)
41 out, err = p.communicate()
42 if p.returncode:
43 raise subprocess.CalledProcessError(
Pablo Galindob9392502018-11-07 22:21:17 +000044 p.returncode, cmd, out, err)
Steve Dowerf14c28f2018-09-20 13:38:34 -070045 return out, err
46
Vinay Sajip7ded1f02012-05-26 03:45:29 +010047class BaseTest(unittest.TestCase):
48 """Base class for venv tests."""
Victor Stinnerbdc337b2016-03-25 12:30:40 +010049 maxDiff = 80 * 50
Vinay Sajip7ded1f02012-05-26 03:45:29 +010050
51 def setUp(self):
Ned Deily045bd532012-07-13 15:48:04 -070052 self.env_dir = os.path.realpath(tempfile.mkdtemp())
Vinay Sajip7ded1f02012-05-26 03:45:29 +010053 if os.name == 'nt':
54 self.bindir = 'Scripts'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010055 self.lib = ('Lib',)
56 self.include = 'Include'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010057 else:
58 self.bindir = 'bin'
Serhiy Storchaka885bdc42016-02-11 13:10:36 +020059 self.lib = ('lib', 'python%d.%d' % sys.version_info[:2])
Vinay Sajip7ded1f02012-05-26 03:45:29 +010060 self.include = 'include'
Steve Dower9048c492019-06-29 10:34:11 -070061 executable = sys._base_executable
Vinay Sajip382a7c02012-05-28 16:34:47 +010062 self.exe = os.path.split(executable)[-1]
Steve Dower9048c492019-06-29 10:34:11 -070063 if (sys.platform == 'win32'
64 and os.path.lexists(executable)
65 and not os.path.exists(executable)):
66 self.cannot_link_exe = True
67 else:
68 self.cannot_link_exe = False
Vinay Sajip7ded1f02012-05-26 03:45:29 +010069
70 def tearDown(self):
Victor Stinner866c4e22014-10-10 14:23:00 +020071 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010072
73 def run_with_capture(self, func, *args, **kwargs):
74 with captured_stdout() as output:
75 with captured_stderr() as error:
76 func(*args, **kwargs)
77 return output.getvalue(), error.getvalue()
78
79 def get_env_file(self, *args):
80 return os.path.join(self.env_dir, *args)
81
82 def get_text_file_contents(self, *args):
83 with open(self.get_env_file(*args), 'r') as f:
84 result = f.read()
85 return result
86
87class BasicTest(BaseTest):
88 """Test venv module functionality."""
89
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010090 def isdir(self, *args):
91 fn = self.get_env_file(*args)
92 self.assertTrue(os.path.isdir(fn))
93
Vinay Sajip7ded1f02012-05-26 03:45:29 +010094 def test_defaults(self):
95 """
96 Test the create function with default arguments.
97 """
Victor Stinner866c4e22014-10-10 14:23:00 +020098 rmtree(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010099 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100100 self.isdir(self.bindir)
101 self.isdir(self.include)
102 self.isdir(*self.lib)
Vinay Sajip1e53f8d2014-04-15 11:18:10 +0100103 # Issue 21197
104 p = self.get_env_file('lib64')
105 conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
106 (sys.platform != 'darwin'))
107 if conditions:
108 self.assertTrue(os.path.islink(p))
109 else:
110 self.assertFalse(os.path.exists(p))
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100111 data = self.get_text_file_contents('pyvenv.cfg')
Steve Dower9048c492019-06-29 10:34:11 -0700112 executable = sys._base_executable
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100113 path = os.path.dirname(executable)
114 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100115 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +0100116 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100117 bd = self.get_env_file(self.bindir)
118 print('Contents of %r:' % bd)
119 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +0100120 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100121
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100122 def test_prompt(self):
123 env_name = os.path.split(self.env_dir)[1]
124
Cheryl Sabella839b9252019-03-12 20:15:47 -0400125 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100126 builder = venv.EnvBuilder()
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, '(%s) ' % env_name)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500131 self.assertNotIn("prompt = ", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100132
Cheryl Sabella839b9252019-03-12 20:15:47 -0400133 rmtree(self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100134 builder = venv.EnvBuilder(prompt='My prompt')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400135 self.run_with_capture(builder.create, self.env_dir)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100136 context = builder.ensure_directories(self.env_dir)
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500137 data = self.get_text_file_contents('pyvenv.cfg')
Cheryl Sabella839b9252019-03-12 20:15:47 -0400138 self.assertEqual(context.prompt, '(My prompt) ')
Cheryl Sabellad5a70c62019-03-08 17:01:27 -0500139 self.assertIn("prompt = 'My prompt'\n", data)
Vinay Sajipfd0f84b2016-08-06 10:43:44 +0100140
Cooper Lees4acdbf12019-06-17 11:18:14 -0700141 def test_upgrade_dependencies(self):
142 builder = venv.EnvBuilder()
143 bin_path = 'Scripts' if sys.platform == 'win32' else 'bin'
Tzu-ping Chungd9aa2162019-11-28 04:25:23 +0800144 python_exe = 'python.exe' if sys.platform == 'win32' else 'python'
Cooper Lees4acdbf12019-06-17 11:18:14 -0700145 with tempfile.TemporaryDirectory() as fake_env_dir:
146
147 def pip_cmd_checker(cmd):
148 self.assertEqual(
149 cmd,
150 [
Tzu-ping Chungd9aa2162019-11-28 04:25:23 +0800151 os.path.join(fake_env_dir, bin_path, python_exe),
152 '-m',
153 'pip',
Cooper Lees4acdbf12019-06-17 11:18:14 -0700154 'install',
Tzu-ping Chungd9aa2162019-11-28 04:25:23 +0800155 '--upgrade',
Cooper Lees4acdbf12019-06-17 11:18:14 -0700156 'pip',
157 'setuptools'
158 ]
159 )
160
161 fake_context = builder.ensure_directories(fake_env_dir)
162 with patch('venv.subprocess.check_call', pip_cmd_checker):
163 builder.upgrade_dependencies(fake_context)
164
Steve Dower8bba81f2019-03-21 10:04:21 -0700165 @requireVenvCreate
Vinay Sajip3874e542012-07-03 16:56:40 +0100166 def test_prefixes(self):
167 """
168 Test that the prefix values are as expected.
169 """
Vinay Sajip3874e542012-07-03 16:56:40 +0100170 # check a venv's prefixes
Victor Stinner866c4e22014-10-10 14:23:00 +0200171 rmtree(self.env_dir)
Vinay Sajip3874e542012-07-03 16:56:40 +0100172 self.run_with_capture(venv.create, self.env_dir)
173 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
174 cmd = [envpy, '-c', None]
175 for prefix, expected in (
176 ('prefix', self.env_dir),
Steve Dower9048c492019-06-29 10:34:11 -0700177 ('exec_prefix', self.env_dir),
178 ('base_prefix', sys.base_prefix),
179 ('base_exec_prefix', sys.base_exec_prefix)):
Vinay Sajip3874e542012-07-03 16:56:40 +0100180 cmd[2] = 'import sys; print(sys.%s)' % prefix
Steve Dowerf14c28f2018-09-20 13:38:34 -0700181 out, err = check_output(cmd)
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200182 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100183
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100184 if sys.platform == 'win32':
185 ENV_SUBDIRS = (
186 ('Scripts',),
187 ('Include',),
188 ('Lib',),
189 ('Lib', 'site-packages'),
190 )
191 else:
192 ENV_SUBDIRS = (
193 ('bin',),
194 ('include',),
195 ('lib',),
196 ('lib', 'python%d.%d' % sys.version_info[:2]),
197 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
198 )
199
200 def create_contents(self, paths, filename):
201 """
202 Create some files in the environment which are unrelated
203 to the virtual environment.
204 """
205 for subdirs in paths:
206 d = os.path.join(self.env_dir, *subdirs)
207 os.mkdir(d)
208 fn = os.path.join(d, filename)
209 with open(fn, 'wb') as f:
210 f.write(b'Still here?')
211
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100212 def test_overwrite_existing(self):
213 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100214 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100215 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100216 self.create_contents(self.ENV_SUBDIRS, 'foo')
217 venv.create(self.env_dir)
218 for subdirs in self.ENV_SUBDIRS:
219 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
220 self.assertTrue(os.path.exists(fn))
221 with open(fn, 'rb') as f:
222 self.assertEqual(f.read(), b'Still here?')
223
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100224 builder = venv.EnvBuilder(clear=True)
225 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100226 for subdirs in self.ENV_SUBDIRS:
227 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
228 self.assertFalse(os.path.exists(fn))
229
230 def clear_directory(self, path):
231 for fn in os.listdir(path):
232 fn = os.path.join(path, fn)
233 if os.path.islink(fn) or os.path.isfile(fn):
234 os.remove(fn)
235 elif os.path.isdir(fn):
Victor Stinner866c4e22014-10-10 14:23:00 +0200236 rmtree(fn)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100237
238 def test_unoverwritable_fails(self):
239 #create a file clashing with directories in the env dir
240 for paths in self.ENV_SUBDIRS[:3]:
241 fn = os.path.join(self.env_dir, *paths)
242 with open(fn, 'wb') as f:
243 f.write(b'')
244 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
245 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100246
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100247 def test_upgrade(self):
248 """
249 Test upgrading an existing environment directory.
250 """
Vinay Sajipb9b965f2014-06-03 16:47:51 +0100251 # See Issue #21643: the loop needs to run twice to ensure
252 # that everything works on the upgrade (the first run just creates
253 # the venv).
254 for upgrade in (False, True):
255 builder = venv.EnvBuilder(upgrade=upgrade)
256 self.run_with_capture(builder.create, self.env_dir)
257 self.isdir(self.bindir)
258 self.isdir(self.include)
259 self.isdir(*self.lib)
260 fn = self.get_env_file(self.bindir, self.exe)
261 if not os.path.exists(fn):
262 # diagnostics for Windows buildbot failures
263 bd = self.get_env_file(self.bindir)
264 print('Contents of %r:' % bd)
265 print(' %r' % os.listdir(bd))
266 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100267
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100268 def test_isolation(self):
269 """
270 Test isolation from system site-packages
271 """
272 for ssp, s in ((True, 'true'), (False, 'false')):
273 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
274 builder.create(self.env_dir)
275 data = self.get_text_file_contents('pyvenv.cfg')
276 self.assertIn('include-system-site-packages = %s\n' % s, data)
277
278 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
279 def test_symlinking(self):
280 """
281 Test symlinking works as expected
282 """
283 for usl in (False, True):
284 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100285 builder.create(self.env_dir)
286 fn = self.get_env_file(self.bindir, self.exe)
287 # Don't test when False, because e.g. 'python' is always
288 # symlinked to 'python3.3' in the env, even when symlinking in
289 # general isn't wanted.
290 if usl:
Steve Dower9048c492019-06-29 10:34:11 -0700291 if self.cannot_link_exe:
292 # Symlinking is skipped when our executable is already a
293 # special app symlink
294 self.assertFalse(os.path.islink(fn))
295 else:
296 self.assertTrue(os.path.islink(fn))
Vinay Sajip90db6612012-07-17 17:33:46 +0100297
298 # If a venv is created from a source build and that venv is used to
299 # run the test, the pyvenv.cfg in the venv created in the test will
300 # point to the venv being used to run the test, and we lose the link
301 # to the source build - so Python can't initialise properly.
Steve Dower8bba81f2019-03-21 10:04:21 -0700302 @requireVenvCreate
Vinay Sajip90db6612012-07-17 17:33:46 +0100303 def test_executable(self):
304 """
305 Test that the sys.executable value is as expected.
306 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200307 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100308 self.run_with_capture(venv.create, self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700309 envpy = os.path.join(os.path.realpath(self.env_dir),
310 self.bindir, self.exe)
311 out, err = check_output([envpy, '-c',
312 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200313 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100314
315 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
316 def test_executable_symlinks(self):
317 """
318 Test that the sys.executable value is as expected.
319 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200320 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100321 builder = venv.EnvBuilder(clear=True, symlinks=True)
322 builder.create(self.env_dir)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700323 envpy = os.path.join(os.path.realpath(self.env_dir),
324 self.bindir, self.exe)
325 out, err = check_output([envpy, '-c',
326 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200327 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100328
Steve Dower62409172018-02-19 17:25:24 -0800329 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
330 def test_unicode_in_batch_file(self):
331 """
Steve Dowerf14c28f2018-09-20 13:38:34 -0700332 Test handling of Unicode paths
Steve Dower62409172018-02-19 17:25:24 -0800333 """
334 rmtree(self.env_dir)
335 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
336 builder = venv.EnvBuilder(clear=True)
337 builder.create(env_dir)
338 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
339 envpy = os.path.join(env_dir, self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700340 out, err = check_output(
341 [activate, '&', self.exe, '-c', 'print(0)'],
342 encoding='oem',
343 )
Steve Dower62409172018-02-19 17:25:24 -0800344 self.assertEqual(out.strip(), '0')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000345
Steve Dower8bba81f2019-03-21 10:04:21 -0700346 @requireVenvCreate
Steve Dower4e02f8f82019-01-25 14:59:12 -0800347 def test_multiprocessing(self):
348 """
349 Test that the multiprocessing is able to spawn.
350 """
Min ho Kimc4cacc82019-07-31 08:16:13 +1000351 # Issue bpo-36342: Instantiation of a Pool object imports the
xdegaye5437ccc2019-05-30 23:42:29 +0200352 # multiprocessing.synchronize module. Skip the test if this module
353 # cannot be imported.
354 import_module('multiprocessing.synchronize')
Steve Dower4e02f8f82019-01-25 14:59:12 -0800355 rmtree(self.env_dir)
356 self.run_with_capture(venv.create, self.env_dir)
357 envpy = os.path.join(os.path.realpath(self.env_dir),
358 self.bindir, self.exe)
359 out, err = check_output([envpy, '-c',
Victor Stinnerbc6469f2019-06-04 19:03:13 +0200360 'from multiprocessing import Pool; '
361 'pool = Pool(1); '
362 'print(pool.apply_async("Python".lower).get(3)); '
363 'pool.terminate()'])
Steve Dower4e02f8f82019-01-25 14:59:12 -0800364 self.assertEqual(out.strip(), "python".encode())
365
Daniel Abrahamsson5209e582019-09-11 16:58:56 +0200366 @unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
367 def test_deactivate_with_strict_bash_opts(self):
368 bash = shutil.which("bash")
369 if bash is None:
370 self.skipTest("bash required for this test")
371 rmtree(self.env_dir)
372 builder = venv.EnvBuilder(clear=True)
373 builder.create(self.env_dir)
374 activate = os.path.join(self.env_dir, self.bindir, "activate")
375 test_script = os.path.join(self.env_dir, "test_strict.sh")
376 with open(test_script, "w") as f:
377 f.write("set -euo pipefail\n"
378 f"source {activate}\n"
379 "deactivate\n")
380 out, err = check_output([bash, test_script])
381 self.assertEqual(out, "".encode())
382 self.assertEqual(err, "".encode())
383
384
Steve Dower8bba81f2019-03-21 10:04:21 -0700385@requireVenvCreate
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000386class EnsurePipTest(BaseTest):
387 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000388 def assert_pip_not_installed(self):
389 envpy = os.path.join(os.path.realpath(self.env_dir),
390 self.bindir, self.exe)
Steve Dowerf14c28f2018-09-20 13:38:34 -0700391 out, err = check_output([envpy, '-c',
392 'try:\n import pip\nexcept ImportError:\n print("OK")'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000393 # We force everything to text, so unittest gives the detailed diff
394 # if we get unexpected results
395 err = err.decode("latin-1") # Force to text, prevent decoding errors
396 self.assertEqual(err, "")
397 out = out.decode("latin-1") # Force to text, prevent decoding errors
398 self.assertEqual(out.strip(), "OK")
399
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000400
401 def test_no_pip_by_default(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200402 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000403 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000404 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000405
406 def test_explicit_no_pip(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200407 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000408 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000409 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000410
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100411 def test_devnull(self):
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000412 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000413 # appear empty. However http://bugs.python.org/issue20541 means
414 # that doesn't currently work properly on Windows. Once that is
415 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000416 with open(os.devnull, "rb") as f:
417 self.assertEqual(f.read(), b"")
418
Steve Dowerdf2d4a62019-08-21 15:27:33 -0700419 self.assertTrue(os.path.exists(os.devnull))
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100420
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000421 def do_test_with_pip(self, system_site_packages):
Victor Stinner866c4e22014-10-10 14:23:00 +0200422 rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000423 with EnvironmentVarGuard() as envvars:
424 # pip's cross-version compatibility may trigger deprecation
425 # warnings in current versions of Python. Ensure related
426 # environment settings don't cause venv to fail.
427 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000428 # ensurepip is different enough from a normal pip invocation
429 # that we want to ensure it ignores the normal pip environment
430 # variable settings. We set PIP_NO_INSTALL here specifically
431 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000432 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000433 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000434 # Also check that we ignore the pip configuration file
435 # See http://bugs.python.org/issue20053
436 with tempfile.TemporaryDirectory() as home_dir:
437 envvars["HOME"] = home_dir
438 bad_config = "[global]\nno-install=1"
439 # Write to both config file names on all platforms to reduce
440 # cross-platform variation in test code behaviour
441 win_location = ("pip", "pip.ini")
442 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000443 # Skips win_location due to http://bugs.python.org/issue20541
444 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000445 dirpath = os.path.join(home_dir, dirname)
446 os.mkdir(dirpath)
447 fpath = os.path.join(dirpath, fname)
448 with open(fpath, 'w') as f:
449 f.write(bad_config)
450
451 # Actually run the create command with all that unhelpful
452 # config in place to ensure we ignore it
453 try:
454 self.run_with_capture(venv.create, self.env_dir,
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000455 system_site_packages=system_site_packages,
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000456 with_pip=True)
457 except subprocess.CalledProcessError as exc:
458 # The output this produces can be a little hard to read,
459 # but at least it has all the details
460 details = exc.output.decode(errors="replace")
461 msg = "{}\n\n**Subprocess Output**\n{}"
462 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000463 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000464 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Victor Stinner895862a2017-11-20 09:47:03 -0800465 # Ignore DeprecationWarning since pip code is not part of Python
Steve Dowerf14c28f2018-09-20 13:38:34 -0700466 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
467 '-m', 'pip', '--version'])
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000468 # We force everything to text, so unittest gives the detailed diff
469 # if we get unexpected results
470 err = err.decode("latin-1") # Force to text, prevent decoding errors
471 self.assertEqual(err, "")
472 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000473 expected_version = "pip {}".format(ensurepip.version())
474 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000475 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000476 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000477
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000478 # http://bugs.python.org/issue19728
479 # Check the private uninstall command provided for the Windows
480 # installers works (at least in a virtual environment)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000481 with EnvironmentVarGuard() as envvars:
Steve Dowerf14c28f2018-09-20 13:38:34 -0700482 out, err = check_output([envpy,
483 '-W', 'ignore::DeprecationWarning', '-I',
484 '-m', 'ensurepip._uninstall'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000485 # We force everything to text, so unittest gives the detailed diff
486 # if we get unexpected results
487 err = err.decode("latin-1") # Force to text, prevent decoding errors
Victor Stinner87d6e132016-03-14 18:21:58 +0100488 # Ignore the warning:
489 # "The directory '$HOME/.cache/pip/http' or its parent directory
490 # is not owned by the current user and the cache has been disabled.
491 # Please check the permissions and owner of that directory. If
492 # executing pip with sudo, you may want sudo's -H flag."
493 # where $HOME is replaced by the HOME environment variable.
Steve Dowerb1eb20e2019-07-26 09:06:04 -0700494 err = re.sub("^(WARNING: )?The directory .* or its parent directory "
495 "is not owned by the current user .*$", "",
496 err, flags=re.MULTILINE)
Victor Stinner87d6e132016-03-14 18:21:58 +0100497 self.assertEqual(err.rstrip(), "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000498 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000499 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000500 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000501 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000502 self.assertIn("Successfully uninstalled pip", out)
503 self.assertIn("Successfully uninstalled setuptools", out)
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000504 # Check pip is now gone from the virtual environment. This only
505 # applies in the system_site_packages=False case, because in the
506 # other case, pip may still be available in the system site-packages
507 if not system_site_packages:
508 self.assert_pip_not_installed()
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000509
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000510 # Issue #26610: pip/pep425tags.py requires ctypes
511 @unittest.skipUnless(ctypes, 'pip requires ctypes')
Serhiy Storchaka5e0df742017-11-10 12:09:39 +0200512 @requires_zlib
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000513 def test_with_pip(self):
514 self.do_test_with_pip(False)
515 self.do_test_with_pip(True)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000516
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100517if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500518 unittest.main()