blob: eb225fa4aec97fa119d88633e76537c48b65fea5 [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 Coghlan878d2582013-11-24 12:45:25 +100020try:
21 import ssl
22except ImportError:
23 ssl = None
Vinay Sajip7ded1f02012-05-26 03:45:29 +010024
Nick Coghlan8fbdb092013-11-23 00:30:34 +100025skipInVenv = unittest.skipIf(sys.prefix != sys.base_prefix,
26 'Test not appropriate in a venv')
27
28
Vinay Sajip7ded1f02012-05-26 03:45:29 +010029class BaseTest(unittest.TestCase):
30 """Base class for venv tests."""
31
32 def setUp(self):
Ned Deily045bd532012-07-13 15:48:04 -070033 self.env_dir = os.path.realpath(tempfile.mkdtemp())
Vinay Sajip7ded1f02012-05-26 03:45:29 +010034 if os.name == 'nt':
35 self.bindir = 'Scripts'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010036 self.lib = ('Lib',)
37 self.include = 'Include'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010038 else:
39 self.bindir = 'bin'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010040 self.lib = ('lib', 'python%s' % sys.version[:3])
41 self.include = 'include'
Vinay Sajip28952442012-06-25 00:47:46 +010042 if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in os.environ:
43 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip382a7c02012-05-28 16:34:47 +010044 else:
45 executable = sys.executable
46 self.exe = os.path.split(executable)[-1]
Vinay Sajip7ded1f02012-05-26 03:45:29 +010047
48 def tearDown(self):
49 shutil.rmtree(self.env_dir)
50
51 def run_with_capture(self, func, *args, **kwargs):
52 with captured_stdout() as output:
53 with captured_stderr() as error:
54 func(*args, **kwargs)
55 return output.getvalue(), error.getvalue()
56
57 def get_env_file(self, *args):
58 return os.path.join(self.env_dir, *args)
59
60 def get_text_file_contents(self, *args):
61 with open(self.get_env_file(*args), 'r') as f:
62 result = f.read()
63 return result
64
65class BasicTest(BaseTest):
66 """Test venv module functionality."""
67
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010068 def isdir(self, *args):
69 fn = self.get_env_file(*args)
70 self.assertTrue(os.path.isdir(fn))
71
Vinay Sajip7ded1f02012-05-26 03:45:29 +010072 def test_defaults(self):
73 """
74 Test the create function with default arguments.
75 """
Vinay Sajip7ded1f02012-05-26 03:45:29 +010076 shutil.rmtree(self.env_dir)
77 self.run_with_capture(venv.create, self.env_dir)
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010078 self.isdir(self.bindir)
79 self.isdir(self.include)
80 self.isdir(*self.lib)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010081 data = self.get_text_file_contents('pyvenv.cfg')
Vinay Sajip28952442012-06-25 00:47:46 +010082 if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
Vinay Sajip7ded1f02012-05-26 03:45:29 +010083 in os.environ):
Vinay Sajip28952442012-06-25 00:47:46 +010084 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip7ded1f02012-05-26 03:45:29 +010085 else:
86 executable = sys.executable
87 path = os.path.dirname(executable)
88 self.assertIn('home = %s' % path, data)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010089 fn = self.get_env_file(self.bindir, self.exe)
Vinay Sajip7e203492012-05-27 17:30:09 +010090 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
Vinay Sajipb3b49cd2012-05-27 18:39:22 +010091 bd = self.get_env_file(self.bindir)
92 print('Contents of %r:' % bd)
93 print(' %r' % os.listdir(bd))
Vinay Sajip7e203492012-05-27 17:30:09 +010094 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010095
Nick Coghlan8fbdb092013-11-23 00:30:34 +100096 @skipInVenv
Vinay Sajip3874e542012-07-03 16:56:40 +010097 def test_prefixes(self):
98 """
99 Test that the prefix values are as expected.
100 """
101 #check our prefixes
102 self.assertEqual(sys.base_prefix, sys.prefix)
103 self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
104
105 # check a venv's prefixes
106 shutil.rmtree(self.env_dir)
107 self.run_with_capture(venv.create, self.env_dir)
108 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
109 cmd = [envpy, '-c', None]
110 for prefix, expected in (
111 ('prefix', self.env_dir),
112 ('prefix', self.env_dir),
113 ('base_prefix', sys.prefix),
114 ('base_exec_prefix', sys.exec_prefix)):
115 cmd[2] = 'import sys; print(sys.%s)' % prefix
116 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
117 stderr=subprocess.PIPE)
118 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200119 self.assertEqual(out.strip(), expected.encode())
Vinay Sajip3874e542012-07-03 16:56:40 +0100120
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100121 if sys.platform == 'win32':
122 ENV_SUBDIRS = (
123 ('Scripts',),
124 ('Include',),
125 ('Lib',),
126 ('Lib', 'site-packages'),
127 )
128 else:
129 ENV_SUBDIRS = (
130 ('bin',),
131 ('include',),
132 ('lib',),
133 ('lib', 'python%d.%d' % sys.version_info[:2]),
134 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
135 )
136
137 def create_contents(self, paths, filename):
138 """
139 Create some files in the environment which are unrelated
140 to the virtual environment.
141 """
142 for subdirs in paths:
143 d = os.path.join(self.env_dir, *subdirs)
144 os.mkdir(d)
145 fn = os.path.join(d, filename)
146 with open(fn, 'wb') as f:
147 f.write(b'Still here?')
148
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100149 def test_overwrite_existing(self):
150 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100151 Test creating environment in an existing directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100152 """
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100153 self.create_contents(self.ENV_SUBDIRS, 'foo')
154 venv.create(self.env_dir)
155 for subdirs in self.ENV_SUBDIRS:
156 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
157 self.assertTrue(os.path.exists(fn))
158 with open(fn, 'rb') as f:
159 self.assertEqual(f.read(), b'Still here?')
160
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100161 builder = venv.EnvBuilder(clear=True)
162 builder.create(self.env_dir)
Vinay Sajipbd40d3e2012-10-11 17:22:45 +0100163 for subdirs in self.ENV_SUBDIRS:
164 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
165 self.assertFalse(os.path.exists(fn))
166
167 def clear_directory(self, path):
168 for fn in os.listdir(path):
169 fn = os.path.join(path, fn)
170 if os.path.islink(fn) or os.path.isfile(fn):
171 os.remove(fn)
172 elif os.path.isdir(fn):
173 shutil.rmtree(fn)
174
175 def test_unoverwritable_fails(self):
176 #create a file clashing with directories in the env dir
177 for paths in self.ENV_SUBDIRS[:3]:
178 fn = os.path.join(self.env_dir, *paths)
179 with open(fn, 'wb') as f:
180 f.write(b'')
181 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
182 self.clear_directory(self.env_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100183
Vinay Sajipb3b49cd2012-05-27 18:39:22 +0100184 def test_upgrade(self):
185 """
186 Test upgrading an existing environment directory.
187 """
188 builder = venv.EnvBuilder(upgrade=True)
189 self.run_with_capture(builder.create, self.env_dir)
190 self.isdir(self.bindir)
191 self.isdir(self.include)
192 self.isdir(*self.lib)
193 fn = self.get_env_file(self.bindir, self.exe)
194 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
195 bd = self.get_env_file(self.bindir)
196 print('Contents of %r:' % bd)
197 print(' %r' % os.listdir(bd))
198 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
199
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100200 def test_isolation(self):
201 """
202 Test isolation from system site-packages
203 """
204 for ssp, s in ((True, 'true'), (False, 'false')):
205 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
206 builder.create(self.env_dir)
207 data = self.get_text_file_contents('pyvenv.cfg')
208 self.assertIn('include-system-site-packages = %s\n' % s, data)
209
210 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
211 def test_symlinking(self):
212 """
213 Test symlinking works as expected
214 """
215 for usl in (False, True):
216 builder = venv.EnvBuilder(clear=True, symlinks=usl)
Vinay Sajip90db6612012-07-17 17:33:46 +0100217 builder.create(self.env_dir)
218 fn = self.get_env_file(self.bindir, self.exe)
219 # Don't test when False, because e.g. 'python' is always
220 # symlinked to 'python3.3' in the env, even when symlinking in
221 # general isn't wanted.
222 if usl:
223 self.assertTrue(os.path.islink(fn))
224
225 # If a venv is created from a source build and that venv is used to
226 # run the test, the pyvenv.cfg in the venv created in the test will
227 # point to the venv being used to run the test, and we lose the link
228 # to the source build - so Python can't initialise properly.
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000229 @skipInVenv
Vinay Sajip90db6612012-07-17 17:33:46 +0100230 def test_executable(self):
231 """
232 Test that the sys.executable value is as expected.
233 """
234 shutil.rmtree(self.env_dir)
235 self.run_with_capture(venv.create, self.env_dir)
236 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
237 cmd = [envpy, '-c', 'import sys; print(sys.executable)']
238 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
239 stderr=subprocess.PIPE)
240 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200241 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip90db6612012-07-17 17:33:46 +0100242
243 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
244 def test_executable_symlinks(self):
245 """
246 Test that the sys.executable value is as expected.
247 """
248 shutil.rmtree(self.env_dir)
249 builder = venv.EnvBuilder(clear=True, symlinks=True)
250 builder.create(self.env_dir)
251 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
252 cmd = [envpy, '-c', 'import sys; print(sys.executable)']
253 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
254 stderr=subprocess.PIPE)
255 out, err = p.communicate()
Antoine Pitrou9c92a692012-08-05 00:33:10 +0200256 self.assertEqual(out.strip(), envpy.encode())
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100257
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000258
259@skipInVenv
260class EnsurePipTest(BaseTest):
261 """Test venv module installation of pip."""
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000262 def assert_pip_not_installed(self):
263 envpy = os.path.join(os.path.realpath(self.env_dir),
264 self.bindir, self.exe)
265 try_import = 'try:\n import pip\nexcept ImportError:\n print("OK")'
266 cmd = [envpy, '-c', try_import]
267 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
268 stderr=subprocess.PIPE)
269 out, err = p.communicate()
270 # We force everything to text, so unittest gives the detailed diff
271 # if we get unexpected results
272 err = err.decode("latin-1") # Force to text, prevent decoding errors
273 self.assertEqual(err, "")
274 out = out.decode("latin-1") # Force to text, prevent decoding errors
275 self.assertEqual(out.strip(), "OK")
276
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000277
278 def test_no_pip_by_default(self):
279 shutil.rmtree(self.env_dir)
280 self.run_with_capture(venv.create, self.env_dir)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000281 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000282
283 def test_explicit_no_pip(self):
284 shutil.rmtree(self.env_dir)
285 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000286 self.assert_pip_not_installed()
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000287
Nick Coghlan878d2582013-11-24 12:45:25 +1000288 # Temporary skip for http://bugs.python.org/issue19744
289 @unittest.skipIf(ssl is None, 'pip needs SSL support')
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000290 def test_with_pip(self):
291 shutil.rmtree(self.env_dir)
Nick Coghland76cdc12013-11-23 11:37:28 +1000292 with EnvironmentVarGuard() as envvars:
293 # pip's cross-version compatibility may trigger deprecation
294 # warnings in current versions of Python. Ensure related
295 # environment settings don't cause venv to fail.
296 envvars["PYTHONWARNINGS"] = "e"
Nick Coghlan091167c2013-11-24 14:58:31 +1000297 # pip doesn't ignore environment variables when running in
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000298 # isolated mode, and we don't have an active virtualenv here,
299 # we're relying on the native venv support in 3.3+
Nick Coghlan091167c2013-11-24 14:58:31 +1000300 # See http://bugs.python.org/issue19734 for details
301 del envvars["PIP_REQUIRE_VIRTUALENV"]
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000302 try:
303 self.run_with_capture(venv.create, self.env_dir, with_pip=True)
304 except subprocess.CalledProcessError as exc:
305 # The output this produces can be a little hard to read, but
306 # least it has all the details
307 details = exc.output.decode(errors="replace")
308 msg = "{}\n\n**Subprocess Output**\n{}".format(exc, details)
309 self.fail(msg)
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000310 # Ensure pip is available in the virtual environment
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000311 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
Nick Coghlan1d1d8342013-11-24 16:49:20 +1000312 cmd = [envpy, '-Im', 'pip', '--version']
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000313 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
Nick Coghlan1d1d8342013-11-24 16:49:20 +1000314 stderr=subprocess.PIPE)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000315 out, err = p.communicate()
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000316 # We force everything to text, so unittest gives the detailed diff
317 # if we get unexpected results
318 err = err.decode("latin-1") # Force to text, prevent decoding errors
319 self.assertEqual(err, "")
320 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan1b1b1782013-11-30 15:56:58 +1000321 expected_version = "pip {}".format(ensurepip.version())
322 self.assertEqual(out[:len(expected_version)], expected_version)
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000323 env_dir = os.fsencode(self.env_dir).decode("latin-1")
Nick Coghlan6fd12f22013-11-24 11:36:31 +1000324 self.assertIn(env_dir, out)
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000325
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000326 # http://bugs.python.org/issue19728
327 # Check the private uninstall command provided for the Windows
328 # installers works (at least in a virtual environment)
329 cmd = [envpy, '-Im', 'ensurepip._uninstall']
330 with EnvironmentVarGuard() as envvars:
331 # pip doesn't ignore environment variables when running in
332 # isolated mode, and we don't have an active virtualenv here,
333 # we're relying on the native venv support in 3.3+
334 # See http://bugs.python.org/issue19734 for details
335 del envvars["PIP_REQUIRE_VIRTUALENV"]
336 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
337 stderr=subprocess.PIPE)
338 out, err = p.communicate()
339 # We force everything to text, so unittest gives the detailed diff
340 # if we get unexpected results
341 err = err.decode("latin-1") # Force to text, prevent decoding errors
342 self.assertEqual(err, "")
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000343 # Being fairly specific regarding the expected behaviour for the
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000344 # initial bundling phase in Python 3.4. If the output changes in
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000345 # future pip versions, this test can likely be relaxed further.
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000346 out = out.decode("latin-1") # Force to text, prevent decoding errors
Nick Coghlan8ddd59e2013-11-30 18:35:32 +1000347 self.assertIn("Successfully uninstalled pip", out)
348 self.assertIn("Successfully uninstalled setuptools", out)
349 # Check pip is now gone from the virtual environment
Nick Coghlanfdf3a622013-11-30 17:15:09 +1000350 self.assert_pip_not_installed()
351
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000352
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100353def test_main():
Nick Coghlan8fbdb092013-11-23 00:30:34 +1000354 run_unittest(BasicTest, EnsurePipTest)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100355
356if __name__ == "__main__":
357 test_main()