blob: 1084a99a5e365c3b787574cfc08612633b0c0791 [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
Nick Coghlan11c5afd2014-02-07 23:46:38 +100031# os.path.exists('nul') is False: http://bugs.python.org/issue20541
32if os.devnull.lower() == 'nul':
33 failsOnWindows = unittest.expectedFailure
34else:
35 def failsOnWindows(f):
36 return f
Nick Coghlan8fbdb092013-11-23 00:30:34 +100037
Vinay Sajip7ded1f02012-05-26 03:45:29 +010038class BaseTest(unittest.TestCase):
39 """Base class for venv tests."""
40
41 def setUp(self):
Ned Deily045bd532012-07-13 15:48:04 -070042 self.env_dir = os.path.realpath(tempfile.mkdtemp())
Vinay Sajip7ded1f02012-05-26 03:45:29 +010043 if os.name == 'nt':
44 self.bindir = 'Scripts'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010045 self.lib = ('Lib',)
46 self.include = 'Include'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010047 else:
48 self.bindir = 'bin'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010049 self.lib = ('lib', 'python%s' % sys.version[:3])
50 self.include = 'include'
Vinay Sajip28952442012-06-25 00:47:46 +010051 if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in os.environ:
52 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip382a7c02012-05-28 16:34:47 +010053 else:
54 executable = sys.executable
55 self.exe = os.path.split(executable)[-1]
Vinay Sajip7ded1f02012-05-26 03:45:29 +010056
57 def tearDown(self):
58 shutil.rmtree(self.env_dir)
59
60 def run_with_capture(self, func, *args, **kwargs):
61 with captured_stdout() as output:
62 with captured_stderr() as error:
63 func(*args, **kwargs)
64 return output.getvalue(), error.getvalue()
65
66 def get_env_file(self, *args):
67 return os.path.join(self.env_dir, *args)
68
69 def get_text_file_contents(self, *args):
70 with open(self.get_env_file(*args), 'r') as f:
71 result = f.read()
72 return result
73
74class BasicTest(BaseTest):
75 """Test venv module functionality."""
76
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010077 def isdir(self, *args):
78 fn = self.get_env_file(*args)
79 self.assertTrue(os.path.isdir(fn))
80
Vinay Sajip7ded1f02012-05-26 03:45:29 +010081 def test_defaults(self):
82 """
83 Test the create function with default arguments.
84 """
Vinay Sajip7ded1f02012-05-26 03:45:29 +010085 shutil.rmtree(self.env_dir)
86 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010087 self.isdir(self.bindir)
88 self.isdir(self.include)
89 self.isdir(*self.lib)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010090 data = self.get_text_file_contents('pyvenv.cfg')
Vinay Sajip28952442012-06-25 00:47:46 +010091 if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010092 in os.environ):
Vinay Sajip28952442012-06-25 00:47:46 +010093 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip7ded1f02012-05-26 03:45:29 +010094 else:
95 executable = sys.executable
96 path = os.path.dirname(executable)
97 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010098 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +010099 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100100 bd = self.get_env_file(self.bindir)
101 print('Contents of %r:' % bd)
102 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +0100103 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100104
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000105 @skipInVenv
Vinay Sajip3874e542012-07-03 16:56:40 +0100106 def test_prefixes(self):
107 """
108 Test that the prefix values are as expected.
109 """
110 #check our prefixes
111 self.assertEqual(sys.base_prefix, sys.prefix)
112 self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
113
114 # check a venv's prefixes
115 shutil.rmtree(self.env_dir)
116 self.run_with_capture(venv.create, self.env_dir)
117 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
118 cmd = [envpy, '-c', None]
119 for prefix, expected in (
120 ('prefix', self.env_dir),
121 ('prefix', self.env_dir),
122 ('base_prefix', sys.prefix),
123 ('base_exec_prefix', sys.exec_prefix)):
124 cmd[2] = 'import sys; print(sys.%s)' % prefix
125 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
126 stderr=subprocess.PIPE)
127 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200128 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100129
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100130 if sys.platform == 'win32':
131 ENV_SUBDIRS = (
132 ('Scripts',),
133 ('Include',),
134 ('Lib',),
135 ('Lib', 'site-packages'),
136 )
137 else:
138 ENV_SUBDIRS = (
139 ('bin',),
140 ('include',),
141 ('lib',),
142 ('lib', 'python%d.%d' % sys.version_info[:2]),
143 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
144 )
145
146 def create_contents(self, paths, filename):
147 """
148 Create some files in the environment which are unrelated
149 to the virtual environment.
150 """
151 for subdirs in paths:
152 d = os.path.join(self.env_dir, *subdirs)
153 os.mkdir(d)
154 fn = os.path.join(d, filename)
155 with open(fn, 'wb') as f:
156 f.write(b'Still here?')
157
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100158 def test_overwrite_existing(self):
159 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100160 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100161 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100162 self.create_contents(self.ENV_SUBDIRS, 'foo')
163 venv.create(self.env_dir)
164 for subdirs in self.ENV_SUBDIRS:
165 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
166 self.assertTrue(os.path.exists(fn))
167 with open(fn, 'rb') as f:
168 self.assertEqual(f.read(), b'Still here?')
169
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100170 builder = venv.EnvBuilder(clear=True)
171 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100172 for subdirs in self.ENV_SUBDIRS:
173 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
174 self.assertFalse(os.path.exists(fn))
175
176 def clear_directory(self, path):
177 for fn in os.listdir(path):
178 fn = os.path.join(path, fn)
179 if os.path.islink(fn) or os.path.isfile(fn):
180 os.remove(fn)
181 elif os.path.isdir(fn):
182 shutil.rmtree(fn)
183
184 def test_unoverwritable_fails(self):
185 #create a file clashing with directories in the env dir
186 for paths in self.ENV_SUBDIRS[:3]:
187 fn = os.path.join(self.env_dir, *paths)
188 with open(fn, 'wb') as f:
189 f.write(b'')
190 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
191 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100192
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100193 def test_upgrade(self):
194 """
195 Test upgrading an existing environment directory.
196 """
197 builder = venv.EnvBuilder(upgrade=True)
198 self.run_with_capture(builder.create, self.env_dir)
199 self.isdir(self.bindir)
200 self.isdir(self.include)
201 self.isdir(*self.lib)
202 fn = self.get_env_file(self.bindir, self.exe)
203 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
204 bd = self.get_env_file(self.bindir)
205 print('Contents of %r:' % bd)
206 print(' %r' % os.listdir(bd))
207 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
208
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100209 def test_isolation(self):
210 """
211 Test isolation from system site-packages
212 """
213 for ssp, s in ((True, 'true'), (False, 'false')):
214 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
215 builder.create(self.env_dir)
216 data = self.get_text_file_contents('pyvenv.cfg')
217 self.assertIn('include-system-site-packages = %s\n' % s, data)
218
219 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
220 def test_symlinking(self):
221 """
222 Test symlinking works as expected
223 """
224 for usl in (False, True):
225 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100226 builder.create(self.env_dir)
227 fn = self.get_env_file(self.bindir, self.exe)
228 # Don't test when False, because e.g. 'python' is always
229 # symlinked to 'python3.3' in the env, even when symlinking in
230 # general isn't wanted.
231 if usl:
232 self.assertTrue(os.path.islink(fn))
233
234 # If a venv is created from a source build and that venv is used to
235 # run the test, the pyvenv.cfg in the venv created in the test will
236 # point to the venv being used to run the test, and we lose the link
237 # to the source build - so Python can't initialise properly.
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000238 @skipInVenv
Vinay Sajip90db6612012-07-17 17:33:46 +0100239 def test_executable(self):
240 """
241 Test that the sys.executable value is as expected.
242 """
243 shutil.rmtree(self.env_dir)
244 self.run_with_capture(venv.create, self.env_dir)
245 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
246 cmd = [envpy, '-c', 'import sys; print(sys.executable)']
247 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
248 stderr=subprocess.PIPE)
249 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200250 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100251
252 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
253 def test_executable_symlinks(self):
254 """
255 Test that the sys.executable value is as expected.
256 """
257 shutil.rmtree(self.env_dir)
258 builder = venv.EnvBuilder(clear=True, symlinks=True)
259 builder.create(self.env_dir)
260 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
261 cmd = [envpy, '-c', 'import sys; print(sys.executable)']
262 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
263 stderr=subprocess.PIPE)
264 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200265 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100266
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000267
268@skipInVenv
269class EnsurePipTest(BaseTest):
270 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000271 def assert_pip_not_installed(self):
272 envpy = os.path.join(os.path.realpath(self.env_dir),
273 self.bindir, self.exe)
274 try_import = 'try:\n import pip\nexcept ImportError:\n print("OK")'
275 cmd = [envpy, '-c', try_import]
276 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
277 stderr=subprocess.PIPE)
278 out, err = p.communicate()
279 # We force everything to text, so unittest gives the detailed diff
280 # if we get unexpected results
281 err = err.decode("latin-1") # Force to text, prevent decoding errors
282 self.assertEqual(err, "")
283 out = out.decode("latin-1") # Force to text, prevent decoding errors
284 self.assertEqual(out.strip(), "OK")
285
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000286
287 def test_no_pip_by_default(self):
288 shutil.rmtree(self.env_dir)
289 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000290 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000291
292 def test_explicit_no_pip(self):
293 shutil.rmtree(self.env_dir)
294 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000295 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000296
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000297 @failsOnWindows
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000298 def test_devnull_exists_and_is_empty(self):
299 # Fix for issue #20053 uses os.devnull to force a config file to
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000300 # appear empty. However http://bugs.python.org/issue20541 means
301 # that doesn't currently work properly on Windows. Once that is
302 # fixed, the "win_location" part of test_with_pip should be restored
Nick Coghland49fa5e2014-02-07 22:28:18 +1000303 self.assertTrue(os.path.exists(os.devnull))
Nick Coghlan456ab5d2014-02-05 23:54:55 +1000304 with open(os.devnull, "rb") as f:
305 self.assertEqual(f.read(), b"")
306
Nick Coghlanae2ee962013-12-23 23:07:07 +1000307 # Requesting pip fails without SSL (http://bugs.python.org/issue19744)
308 @unittest.skipIf(ssl is None, ensurepip._MISSING_SSL_MESSAGE)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000309 def test_with_pip(self):
310 shutil.rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000311 with EnvironmentVarGuard() as envvars:
312 # pip's cross-version compatibility may trigger deprecation
313 # warnings in current versions of Python. Ensure related
314 # environment settings don't cause venv to fail.
315 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000316 # ensurepip is different enough from a normal pip invocation
317 # that we want to ensure it ignores the normal pip environment
318 # variable settings. We set PIP_NO_INSTALL here specifically
319 # to check that ensurepip (and hence venv) ignores it.
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000320 # See http://bugs.python.org/issue19734
Nick Coghlan6256fcb2013-12-23 16:16:07 +1000321 envvars["PIP_NO_INSTALL"] = "1"
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000322 # Also check that we ignore the pip configuration file
323 # See http://bugs.python.org/issue20053
324 with tempfile.TemporaryDirectory() as home_dir:
325 envvars["HOME"] = home_dir
326 bad_config = "[global]\nno-install=1"
327 # Write to both config file names on all platforms to reduce
328 # cross-platform variation in test code behaviour
329 win_location = ("pip", "pip.ini")
330 posix_location = (".pip", "pip.conf")
Nick Coghlan11c5afd2014-02-07 23:46:38 +1000331 # Skips win_location due to http://bugs.python.org/issue20541
332 for dirname, fname in (posix_location,):
Nick Coghlan6edd82a2014-02-04 23:02:36 +1000333 dirpath = os.path.join(home_dir, dirname)
334 os.mkdir(dirpath)
335 fpath = os.path.join(dirpath, fname)
336 with open(fpath, 'w') as f:
337 f.write(bad_config)
338
339 # Actually run the create command with all that unhelpful
340 # config in place to ensure we ignore it
341 try:
342 self.run_with_capture(venv.create, self.env_dir,
343 with_pip=True)
344 except subprocess.CalledProcessError as exc:
345 # The output this produces can be a little hard to read,
346 # but at least it has all the details
347 details = exc.output.decode(errors="replace")
348 msg = "{}\n\n**Subprocess Output**\n{}"
349 self.fail(msg.format(exc, details))
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000350 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000351 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Nick Coghlan1d1d8342013-11-24 16:49:20 +1000352 cmd = [envpy, '-Im', 'pip', '--version']
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000353 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
Nick Coghlan1d1d8342013-11-24 16:49:20 +1000354 stderr=subprocess.PIPE)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000355 out, err = p.communicate()
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000356 # We force everything to text, so unittest gives the detailed diff
357 # if we get unexpected results
358 err = err.decode("latin-1") # Force to text, prevent decoding errors
359 self.assertEqual(err, "")
360 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000361 expected_version = "pip {}".format(ensurepip.version())
362 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000363 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000364 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000365
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000366 # http://bugs.python.org/issue19728
367 # Check the private uninstall command provided for the Windows
368 # installers works (at least in a virtual environment)
369 cmd = [envpy, '-Im', 'ensurepip._uninstall']
370 with EnvironmentVarGuard() as envvars:
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000371 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
372 stderr=subprocess.PIPE)
373 out, err = p.communicate()
374 # We force everything to text, so unittest gives the detailed diff
375 # if we get unexpected results
376 err = err.decode("latin-1") # Force to text, prevent decoding errors
377 self.assertEqual(err, "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000378 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000379 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000380 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000381 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000382 self.assertIn("Successfully uninstalled pip", out)
383 self.assertIn("Successfully uninstalled setuptools", out)
384 # Check pip is now gone from the virtual environment
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000385 self.assert_pip_not_installed()
386
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000387
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100388def test_main():
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000389 run_unittest(BasicTest, EnsurePipTest)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100390
391if __name__ == "__main__":
392 test_main()