blob: 19a5aab7a210b4ef47a774db09bbe691643fac47 [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
Miss Islington (bot)b0967fe2019-03-21 10:33:40 -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 Dowera73e7902018-09-20 14:39:21 -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(
Miss Islington (bot)b097f9f2018-11-07 14:39:21 -080042 p.returncode, cmd, out, err)
Steve Dowera73e7902018-09-20 14:39:21 -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 Dower44467e82019-02-04 07:20:19 -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 Dower44467e82019-02-04 07:20:19 -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
117 builder = venv.EnvBuilder()
118 context = builder.ensure_directories(self.env_dir)
119 self.assertEqual(context.prompt, '(%s) ' % env_name)
120
121 builder = venv.EnvBuilder(prompt='My prompt')
122 context = builder.ensure_directories(self.env_dir)
123 self.assertEqual(context.prompt, '(My prompt) ')
124
Miss Islington (bot)b0967fe2019-03-21 10:33:40 -0700125 @requireVenvCreate
Vinay Sajip3874e542012-07-03 16:56:40 +0100126 def test_prefixes(self):
127 """
128 Test that the prefix values are as expected.
129 """
130 #check our prefixes
131 self.assertEqual(sys.base_prefix, sys.prefix)
132 self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
133
134 # check a venv's prefixes
Victor Stinner866c4e22014-10-10 14:23:00 +0200135 rmtree(self.env_dir)
Vinay Sajip3874e542012-07-03 16:56:40 +0100136 self.run_with_capture(venv.create, self.env_dir)
137 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
138 cmd = [envpy, '-c', None]
139 for prefix, expected in (
140 ('prefix', self.env_dir),
141 ('prefix', self.env_dir),
142 ('base_prefix', sys.prefix),
143 ('base_exec_prefix', sys.exec_prefix)):
144 cmd[2] = 'import sys; print(sys.%s)' % prefix
Steve Dowera73e7902018-09-20 14:39:21 -0700145 out, err = check_output(cmd)
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200146 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100147
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100148 if sys.platform == 'win32':
149 ENV_SUBDIRS = (
150 ('Scripts',),
151 ('Include',),
152 ('Lib',),
153 ('Lib', 'site-packages'),
154 )
155 else:
156 ENV_SUBDIRS = (
157 ('bin',),
158 ('include',),
159 ('lib',),
160 ('lib', 'python%d.%d' % sys.version_info[:2]),
161 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
162 )
163
164 def create_contents(self, paths, filename):
165 """
166 Create some files in the environment which are unrelated
167 to the virtual environment.
168 """
169 for subdirs in paths:
170 d = os.path.join(self.env_dir, *subdirs)
171 os.mkdir(d)
172 fn = os.path.join(d, filename)
173 with open(fn, 'wb') as f:
174 f.write(b'Still here?')
175
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100176 def test_overwrite_existing(self):
177 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100178 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100179 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100180 self.create_contents(self.ENV_SUBDIRS, 'foo')
181 venv.create(self.env_dir)
182 for subdirs in self.ENV_SUBDIRS:
183 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
184 self.assertTrue(os.path.exists(fn))
185 with open(fn, 'rb') as f:
186 self.assertEqual(f.read(), b'Still here?')
187
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100188 builder = venv.EnvBuilder(clear=True)
189 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100190 for subdirs in self.ENV_SUBDIRS:
191 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
192 self.assertFalse(os.path.exists(fn))
193
194 def clear_directory(self, path):
195 for fn in os.listdir(path):
196 fn = os.path.join(path, fn)
197 if os.path.islink(fn) or os.path.isfile(fn):
198 os.remove(fn)
199 elif os.path.isdir(fn):
Victor Stinner866c4e22014-10-10 14:23:00 +0200200 rmtree(fn)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100201
202 def test_unoverwritable_fails(self):
203 #create a file clashing with directories in the env dir
204 for paths in self.ENV_SUBDIRS[:3]:
205 fn = os.path.join(self.env_dir, *paths)
206 with open(fn, 'wb') as f:
207 f.write(b'')
208 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
209 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100210
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100211 def test_upgrade(self):
212 """
213 Test upgrading an existing environment directory.
214 """
Vinay Sajipb9b965f2014-06-03 16:47:51 +0100215 # See Issue #21643: the loop needs to run twice to ensure
216 # that everything works on the upgrade (the first run just creates
217 # the venv).
218 for upgrade in (False, True):
219 builder = venv.EnvBuilder(upgrade=upgrade)
220 self.run_with_capture(builder.create, self.env_dir)
221 self.isdir(self.bindir)
222 self.isdir(self.include)
223 self.isdir(*self.lib)
224 fn = self.get_env_file(self.bindir, self.exe)
225 if not os.path.exists(fn):
226 # diagnostics for Windows buildbot failures
227 bd = self.get_env_file(self.bindir)
228 print('Contents of %r:' % bd)
229 print(' %r' % os.listdir(bd))
230 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100231
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100232 def test_isolation(self):
233 """
234 Test isolation from system site-packages
235 """
236 for ssp, s in ((True, 'true'), (False, 'false')):
237 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
238 builder.create(self.env_dir)
239 data = self.get_text_file_contents('pyvenv.cfg')
240 self.assertIn('include-system-site-packages = %s\n' % s, data)
241
242 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
243 def test_symlinking(self):
244 """
245 Test symlinking works as expected
246 """
247 for usl in (False, True):
248 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100249 builder.create(self.env_dir)
250 fn = self.get_env_file(self.bindir, self.exe)
251 # Don't test when False, because e.g. 'python' is always
252 # symlinked to 'python3.3' in the env, even when symlinking in
253 # general isn't wanted.
254 if usl:
255 self.assertTrue(os.path.islink(fn))
256
257 # If a venv is created from a source build and that venv is used to
258 # run the test, the pyvenv.cfg in the venv created in the test will
259 # point to the venv being used to run the test, and we lose the link
260 # to the source build - so Python can't initialise properly.
Miss Islington (bot)b0967fe2019-03-21 10:33:40 -0700261 @requireVenvCreate
Vinay Sajip90db6612012-07-17 17:33:46 +0100262 def test_executable(self):
263 """
264 Test that the sys.executable value is as expected.
265 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200266 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100267 self.run_with_capture(venv.create, self.env_dir)
Steve Dowera73e7902018-09-20 14:39:21 -0700268 envpy = os.path.join(os.path.realpath(self.env_dir),
269 self.bindir, self.exe)
270 out, err = check_output([envpy, '-c',
271 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200272 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100273
274 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
275 def test_executable_symlinks(self):
276 """
277 Test that the sys.executable value is as expected.
278 """
Victor Stinner866c4e22014-10-10 14:23:00 +0200279 rmtree(self.env_dir)
Vinay Sajip90db6612012-07-17 17:33:46 +0100280 builder = venv.EnvBuilder(clear=True, symlinks=True)
281 builder.create(self.env_dir)
Steve Dowera73e7902018-09-20 14:39:21 -0700282 envpy = os.path.join(os.path.realpath(self.env_dir),
283 self.bindir, self.exe)
284 out, err = check_output([envpy, '-c',
285 'import sys; print(sys.executable)'])
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200286 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100287
Miss Islington (bot)a3d6c1b2018-02-19 17:45:02 -0800288 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
289 def test_unicode_in_batch_file(self):
290 """
Steve Dowera73e7902018-09-20 14:39:21 -0700291 Test handling of Unicode paths
Miss Islington (bot)a3d6c1b2018-02-19 17:45:02 -0800292 """
293 rmtree(self.env_dir)
294 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
295 builder = venv.EnvBuilder(clear=True)
296 builder.create(env_dir)
297 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
298 envpy = os.path.join(env_dir, self.bindir, self.exe)
Steve Dowera73e7902018-09-20 14:39:21 -0700299 out, err = check_output(
300 [activate, '&', self.exe, '-c', 'print(0)'],
301 encoding='oem',
302 )
Miss Islington (bot)a3d6c1b2018-02-19 17:45:02 -0800303 self.assertEqual(out.strip(), '0')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000304
Miss Islington (bot)b0967fe2019-03-21 10:33:40 -0700305 @requireVenvCreate
Miss Islington (bot)6a9c0fc2019-01-25 15:14:41 -0800306 def test_multiprocessing(self):
307 """
308 Test that the multiprocessing is able to spawn.
309 """
310 rmtree(self.env_dir)
311 self.run_with_capture(venv.create, self.env_dir)
312 envpy = os.path.join(os.path.realpath(self.env_dir),
313 self.bindir, self.exe)
314 out, err = check_output([envpy, '-c',
315 'from multiprocessing import Pool; ' +
316 'print(Pool(1).apply_async("Python".lower).get(3))'])
317 self.assertEqual(out.strip(), "python".encode())
318
Miss Islington (bot)b0967fe2019-03-21 10:33:40 -0700319@requireVenvCreate
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000320class EnsurePipTest(BaseTest):
321 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000322 def assert_pip_not_installed(self):
323 envpy = os.path.join(os.path.realpath(self.env_dir),
324 self.bindir, self.exe)
Steve Dowera73e7902018-09-20 14:39:21 -0700325 out, err = check_output([envpy, '-c',
326 'try:\n import pip\nexcept ImportError:\n print("OK")'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000327 # We force everything to text, so unittest gives the detailed diff
328 # if we get unexpected results
329 err = err.decode("latin-1") # Force to text, prevent decoding errors
330 self.assertEqual(err, "")
331 out = out.decode("latin-1") # Force to text, prevent decoding errors
332 self.assertEqual(out.strip(), "OK")
333
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000334
335 def test_no_pip_by_default(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200336 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000337 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000338 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000339
340 def test_explicit_no_pip(self):
Victor Stinner866c4e22014-10-10 14:23:00 +0200341 rmtree(self.env_dir)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000342 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000343 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000344
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100345 def test_devnull(self):
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000346 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000347 # appear empty. However http://bugs.python.org/issue20541 means
348 # that doesn't currently work properly on Windows. Once that is
349 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000350 with open(os.devnull, "rb") as f:
351 self.assertEqual(f.read(), b"")
352
Victor Stinnerbdc337b2016-03-25 12:30:40 +0100353 # Issue #20541: os.path.exists('nul') is False on Windows
354 if os.devnull.lower() == 'nul':
355 self.assertFalse(os.path.exists(os.devnull))
356 else:
357 self.assertTrue(os.path.exists(os.devnull))
358
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000359 def do_test_with_pip(self, system_site_packages):
Victor Stinner866c4e22014-10-10 14:23:00 +0200360 rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000361 with EnvironmentVarGuard() as envvars:
362 # pip's cross-version compatibility may trigger deprecation
363 # warnings in current versions of Python. Ensure related
364 # environment settings don't cause venv to fail.
365 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000366 # ensurepip is different enough from a normal pip invocation
367 # that we want to ensure it ignores the normal pip environment
368 # variable settings. We set PIP_NO_INSTALL here specifically
369 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000370 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000371 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000372 # Also check that we ignore the pip configuration file
373 # See http://bugs.python.org/issue20053
374 with tempfile.TemporaryDirectory() as home_dir:
375 envvars["HOME"] = home_dir
376 bad_config = "[global]\nno-install=1"
377 # Write to both config file names on all platforms to reduce
378 # cross-platform variation in test code behaviour
379 win_location = ("pip", "pip.ini")
380 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000381 # Skips win_location due to http://bugs.python.org/issue20541
382 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000383 dirpath = os.path.join(home_dir, dirname)
384 os.mkdir(dirpath)
385 fpath = os.path.join(dirpath, fname)
386 with open(fpath, 'w') as f:
387 f.write(bad_config)
388
389 # Actually run the create command with all that unhelpful
390 # config in place to ensure we ignore it
391 try:
392 self.run_with_capture(venv.create, self.env_dir,
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000393 system_site_packages=system_site_packages,
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000394 with_pip=True)
395 except subprocess.CalledProcessError as exc:
396 # The output this produces can be a little hard to read,
397 # but at least it has all the details
398 details = exc.output.decode(errors="replace")
399 msg = "{}\n\n**Subprocess Output**\n{}"
400 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000401 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000402 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Victor Stinner895862a2017-11-20 09:47:03 -0800403 # Ignore DeprecationWarning since pip code is not part of Python
Steve Dowera73e7902018-09-20 14:39:21 -0700404 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
405 '-m', 'pip', '--version'])
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000406 # We force everything to text, so unittest gives the detailed diff
407 # if we get unexpected results
408 err = err.decode("latin-1") # Force to text, prevent decoding errors
409 self.assertEqual(err, "")
410 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000411 expected_version = "pip {}".format(ensurepip.version())
412 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000413 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000414 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000415
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000416 # http://bugs.python.org/issue19728
417 # Check the private uninstall command provided for the Windows
418 # installers works (at least in a virtual environment)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000419 with EnvironmentVarGuard() as envvars:
Steve Dowera73e7902018-09-20 14:39:21 -0700420 out, err = check_output([envpy,
421 '-W', 'ignore::DeprecationWarning', '-I',
422 '-m', 'ensurepip._uninstall'])
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000423 # We force everything to text, so unittest gives the detailed diff
424 # if we get unexpected results
425 err = err.decode("latin-1") # Force to text, prevent decoding errors
Victor Stinner87d6e132016-03-14 18:21:58 +0100426 # Ignore the warning:
427 # "The directory '$HOME/.cache/pip/http' or its parent directory
428 # is not owned by the current user and the cache has been disabled.
429 # Please check the permissions and owner of that directory. If
430 # executing pip with sudo, you may want sudo's -H flag."
431 # where $HOME is replaced by the HOME environment variable.
432 err = re.sub("^The directory .* or its parent directory is not owned "
433 "by the current user .*$", "", err, flags=re.MULTILINE)
434 self.assertEqual(err.rstrip(), "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000435 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000436 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000437 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000438 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000439 self.assertIn("Successfully uninstalled pip", out)
440 self.assertIn("Successfully uninstalled setuptools", out)
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000441 # Check pip is now gone from the virtual environment. This only
442 # applies in the system_site_packages=False case, because in the
443 # other case, pip may still be available in the system site-packages
444 if not system_site_packages:
445 self.assert_pip_not_installed()
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000446
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000447 # Issue #26610: pip/pep425tags.py requires ctypes
448 @unittest.skipUnless(ctypes, 'pip requires ctypes')
Serhiy Storchaka5e0df742017-11-10 12:09:39 +0200449 @requires_zlib
Vinay Sajipdb6322c2017-02-02 19:05:19 +0000450 def test_with_pip(self):
451 self.do_test_with_pip(False)
452 self.do_test_with_pip(True)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000453
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100454if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500455 unittest.main()