blob: 58551bed9515877207af3bf46194782de14cd944 [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
11import shutil
Vinay Sajip3874e542012-07-03 16:56:40 +010012import subprocess
Vinay Sajip7ded1f02012-05-26 03:45:29 +010013import sys
14import tempfile
15from test.support import (captured_stdout, captured_stderr, run_unittest,
Nick Coghland76cdc12013-11-23 11:37:28 +100016 can_symlink, EnvironmentVarGuard)
Nick Coghlanfdf3a622013-11-30 17:15:09 +100017import textwrap
Vinay Sajip7ded1f02012-05-26 03:45:29 +010018import unittest
19import venv
Nick Coghlanae2ee962013-12-23 23:07:07 +100020
21# pip currently requires ssl support, so we ensure we handle
22# it being missing (http://bugs.python.org/issue19744)
Nick Coghlan878d2582013-11-24 12:45:25 +100023try:
24 import ssl
25except ImportError:
26 ssl = None
Vinay Sajip7ded1f02012-05-26 03:45:29 +010027
Nick Coghlan8fbdb092013-11-23 00:30:34 +100028skipInVenv = unittest.skipIf(sys.prefix != sys.base_prefix,
29 'Test not appropriate in a venv')
30
31
Vinay Sajip7ded1f02012-05-26 03:45:29 +010032class BaseTest(unittest.TestCase):
33 """Base class for venv tests."""
34
35 def setUp(self):
Ned Deily045bd532012-07-13 15:48:04 -070036 self.env_dir = os.path.realpath(tempfile.mkdtemp())
Vinay Sajip7ded1f02012-05-26 03:45:29 +010037 if os.name == 'nt':
38 self.bindir = 'Scripts'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010039 self.lib = ('Lib',)
40 self.include = 'Include'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010041 else:
42 self.bindir = 'bin'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010043 self.lib = ('lib', 'python%s' % sys.version[:3])
44 self.include = 'include'
Vinay Sajip28952442012-06-25 00:47:46 +010045 if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in os.environ:
46 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip382a7c02012-05-28 16:34:47 +010047 else:
48 executable = sys.executable
49 self.exe = os.path.split(executable)[-1]
Vinay Sajip7ded1f02012-05-26 03:45:29 +010050
51 def tearDown(self):
52 shutil.rmtree(self.env_dir)
53
54 def run_with_capture(self, func, *args, **kwargs):
55 with captured_stdout() as output:
56 with captured_stderr() as error:
57 func(*args, **kwargs)
58 return output.getvalue(), error.getvalue()
59
60 def get_env_file(self, *args):
61 return os.path.join(self.env_dir, *args)
62
63 def get_text_file_contents(self, *args):
64 with open(self.get_env_file(*args), 'r') as f:
65 result = f.read()
66 return result
67
68class BasicTest(BaseTest):
69 """Test venv module functionality."""
70
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010071 def isdir(self, *args):
72 fn = self.get_env_file(*args)
73 self.assertTrue(os.path.isdir(fn))
74
Vinay Sajip7ded1f02012-05-26 03:45:29 +010075 def test_defaults(self):
76 """
77 Test the create function with default arguments.
78 """
Vinay Sajip7ded1f02012-05-26 03:45:29 +010079 shutil.rmtree(self.env_dir)
80 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010081 self.isdir(self.bindir)
82 self.isdir(self.include)
83 self.isdir(*self.lib)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010084 data = self.get_text_file_contents('pyvenv.cfg')
Vinay Sajip28952442012-06-25 00:47:46 +010085 if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010086 in os.environ):
Vinay Sajip28952442012-06-25 00:47:46 +010087 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip7ded1f02012-05-26 03:45:29 +010088 else:
89 executable = sys.executable
90 path = os.path.dirname(executable)
91 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010092 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +010093 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010094 bd = self.get_env_file(self.bindir)
95 print('Contents of %r:' % bd)
96 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +010097 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010098
Nick Coghlan8fbdb092013-11-23 00:30:34 +100099 @skipInVenv
Vinay Sajip3874e542012-07-03 16:56:40 +0100100 def test_prefixes(self):
101 """
102 Test that the prefix values are as expected.
103 """
104 #check our prefixes
105 self.assertEqual(sys.base_prefix, sys.prefix)
106 self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
107
108 # check a venv's prefixes
109 shutil.rmtree(self.env_dir)
110 self.run_with_capture(venv.create, self.env_dir)
111 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
112 cmd = [envpy, '-c', None]
113 for prefix, expected in (
114 ('prefix', self.env_dir),
115 ('prefix', self.env_dir),
116 ('base_prefix', sys.prefix),
117 ('base_exec_prefix', sys.exec_prefix)):
118 cmd[2] = 'import sys; print(sys.%s)' % prefix
119 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
120 stderr=subprocess.PIPE)
121 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200122 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100123
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100124 if sys.platform == 'win32':
125 ENV_SUBDIRS = (
126 ('Scripts',),
127 ('Include',),
128 ('Lib',),
129 ('Lib', 'site-packages'),
130 )
131 else:
132 ENV_SUBDIRS = (
133 ('bin',),
134 ('include',),
135 ('lib',),
136 ('lib', 'python%d.%d' % sys.version_info[:2]),
137 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
138 )
139
140 def create_contents(self, paths, filename):
141 """
142 Create some files in the environment which are unrelated
143 to the virtual environment.
144 """
145 for subdirs in paths:
146 d = os.path.join(self.env_dir, *subdirs)
147 os.mkdir(d)
148 fn = os.path.join(d, filename)
149 with open(fn, 'wb') as f:
150 f.write(b'Still here?')
151
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100152 def test_overwrite_existing(self):
153 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100154 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100155 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100156 self.create_contents(self.ENV_SUBDIRS, 'foo')
157 venv.create(self.env_dir)
158 for subdirs in self.ENV_SUBDIRS:
159 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
160 self.assertTrue(os.path.exists(fn))
161 with open(fn, 'rb') as f:
162 self.assertEqual(f.read(), b'Still here?')
163
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100164 builder = venv.EnvBuilder(clear=True)
165 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100166 for subdirs in self.ENV_SUBDIRS:
167 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
168 self.assertFalse(os.path.exists(fn))
169
170 def clear_directory(self, path):
171 for fn in os.listdir(path):
172 fn = os.path.join(path, fn)
173 if os.path.islink(fn) or os.path.isfile(fn):
174 os.remove(fn)
175 elif os.path.isdir(fn):
176 shutil.rmtree(fn)
177
178 def test_unoverwritable_fails(self):
179 #create a file clashing with directories in the env dir
180 for paths in self.ENV_SUBDIRS[:3]:
181 fn = os.path.join(self.env_dir, *paths)
182 with open(fn, 'wb') as f:
183 f.write(b'')
184 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
185 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100186
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100187 def test_upgrade(self):
188 """
189 Test upgrading an existing environment directory.
190 """
191 builder = venv.EnvBuilder(upgrade=True)
192 self.run_with_capture(builder.create, self.env_dir)
193 self.isdir(self.bindir)
194 self.isdir(self.include)
195 self.isdir(*self.lib)
196 fn = self.get_env_file(self.bindir, self.exe)
197 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
198 bd = self.get_env_file(self.bindir)
199 print('Contents of %r:' % bd)
200 print(' %r' % os.listdir(bd))
201 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
202
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100203 def test_isolation(self):
204 """
205 Test isolation from system site-packages
206 """
207 for ssp, s in ((True, 'true'), (False, 'false')):
208 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
209 builder.create(self.env_dir)
210 data = self.get_text_file_contents('pyvenv.cfg')
211 self.assertIn('include-system-site-packages = %s\n' % s, data)
212
213 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
214 def test_symlinking(self):
215 """
216 Test symlinking works as expected
217 """
218 for usl in (False, True):
219 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100220 builder.create(self.env_dir)
221 fn = self.get_env_file(self.bindir, self.exe)
222 # Don't test when False, because e.g. 'python' is always
223 # symlinked to 'python3.3' in the env, even when symlinking in
224 # general isn't wanted.
225 if usl:
226 self.assertTrue(os.path.islink(fn))
227
228 # If a venv is created from a source build and that venv is used to
229 # run the test, the pyvenv.cfg in the venv created in the test will
230 # point to the venv being used to run the test, and we lose the link
231 # to the source build - so Python can't initialise properly.
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000232 @skipInVenv
Vinay Sajip90db6612012-07-17 17:33:46 +0100233 def test_executable(self):
234 """
235 Test that the sys.executable value is as expected.
236 """
237 shutil.rmtree(self.env_dir)
238 self.run_with_capture(venv.create, self.env_dir)
239 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
240 cmd = [envpy, '-c', 'import sys; print(sys.executable)']
241 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
242 stderr=subprocess.PIPE)
243 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200244 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100245
246 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
247 def test_executable_symlinks(self):
248 """
249 Test that the sys.executable value is as expected.
250 """
251 shutil.rmtree(self.env_dir)
252 builder = venv.EnvBuilder(clear=True, symlinks=True)
253 builder.create(self.env_dir)
254 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
255 cmd = [envpy, '-c', 'import sys; print(sys.executable)']
256 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
257 stderr=subprocess.PIPE)
258 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200259 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100260
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000261
262@skipInVenv
263class EnsurePipTest(BaseTest):
264 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000265 def assert_pip_not_installed(self):
266 envpy = os.path.join(os.path.realpath(self.env_dir),
267 self.bindir, self.exe)
268 try_import = 'try:\n import pip\nexcept ImportError:\n print("OK")'
269 cmd = [envpy, '-c', try_import]
270 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
271 stderr=subprocess.PIPE)
272 out, err = p.communicate()
273 # We force everything to text, so unittest gives the detailed diff
274 # if we get unexpected results
275 err = err.decode("latin-1") # Force to text, prevent decoding errors
276 self.assertEqual(err, "")
277 out = out.decode("latin-1") # Force to text, prevent decoding errors
278 self.assertEqual(out.strip(), "OK")
279
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000280
281 def test_no_pip_by_default(self):
282 shutil.rmtree(self.env_dir)
283 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000284 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000285
286 def test_explicit_no_pip(self):
287 shutil.rmtree(self.env_dir)
288 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000289 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000290
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000291 def test_devnull_exists_and_is_empty(self):
292 # Fix for issue #20053 uses os.devnull to force a config file to
293 # appear empty. Make sure that assumption is valid cross platform.
294 self.assertTrue(os.path.exists, os.devnull)
295 with open(os.devnull, "rb") as f:
296 self.assertEqual(f.read(), b"")
297
Nick Coghlanae2ee962013-12-23 23:07:07 +1000298 # Requesting pip fails without SSL (http://bugs.python.org/issue19744)
299 @unittest.skipIf(ssl is None, ensurepip._MISSING_SSL_MESSAGE)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000300 def test_with_pip(self):
301 shutil.rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000302 with EnvironmentVarGuard() as envvars:
303 # pip's cross-version compatibility may trigger deprecation
304 # warnings in current versions of Python. Ensure related
305 # environment settings don't cause venv to fail.
306 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000307 # ensurepip is different enough from a normal pip invocation
308 # that we want to ensure it ignores the normal pip environment
309 # variable settings. We set PIP_NO_INSTALL here specifically
310 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000311 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000312 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000313 # Also check that we ignore the pip configuration file
314 # See http://bugs.python.org/issue20053
315 with tempfile.TemporaryDirectory() as home_dir:
316 envvars["HOME"] = home_dir
317 bad_config = "[global]\nno-install=1"
318 # Write to both config file names on all platforms to reduce
319 # cross-platform variation in test code behaviour
320 win_location = ("pip", "pip.ini")
321 posix_location = (".pip", "pip.conf")
322 for dirname, fname in (win_location, posix_location):
323 dirpath = os.path.join(home_dir, dirname)
324 os.mkdir(dirpath)
325 fpath = os.path.join(dirpath, fname)
326 with open(fpath, 'w') as f:
327 f.write(bad_config)
328
329 # Actually run the create command with all that unhelpful
330 # config in place to ensure we ignore it
331 try:
332 self.run_with_capture(venv.create, self.env_dir,
333 with_pip=True)
334 except subprocess.CalledProcessError as exc:
335 # The output this produces can be a little hard to read,
336 # but at least it has all the details
337 details = exc.output.decode(errors="replace")
338 msg = "{}\n\n**Subprocess Output**\n{}"
339 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000340 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000341 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Nick Coghlan1d1d8342013-11-24 16:49:20 +1000342 cmd = [envpy, '-Im', 'pip', '--version']
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000343 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
Nick Coghlan1d1d8342013-11-24 16:49:20 +1000344 stderr=subprocess.PIPE)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000345 out, err = p.communicate()
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000346 # We force everything to text, so unittest gives the detailed diff
347 # if we get unexpected results
348 err = err.decode("latin-1") # Force to text, prevent decoding errors
349 self.assertEqual(err, "")
350 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000351 expected_version = "pip {}".format(ensurepip.version())
352 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000353 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000354 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000355
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000356 # http://bugs.python.org/issue19728
357 # Check the private uninstall command provided for the Windows
358 # installers works (at least in a virtual environment)
359 cmd = [envpy, '-Im', 'ensurepip._uninstall']
360 with EnvironmentVarGuard() as envvars:
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000361 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
362 stderr=subprocess.PIPE)
363 out, err = p.communicate()
364 # We force everything to text, so unittest gives the detailed diff
365 # if we get unexpected results
366 err = err.decode("latin-1") # Force to text, prevent decoding errors
367 self.assertEqual(err, "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000368 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000369 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000370 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000371 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000372 self.assertIn("Successfully uninstalled pip", out)
373 self.assertIn("Successfully uninstalled setuptools", out)
374 # Check pip is now gone from the virtual environment
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000375 self.assert_pip_not_installed()
376
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000377
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100378def test_main():
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000379 run_unittest(BasicTest, EnsurePipTest)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100380
381if __name__ == "__main__":
382 test_main()