Debian Codegraph @

Lib/test/test_venv.py

raw
1 """
2 Test harness for the venv module.
3
4 Copyright (C) 2011-2012 Vinay Sajip.
5 Licensed to the PSF under a contributor agreement.
6 """
7
8 import contextlib
9 import ensurepip
10 import os
11 import os.path
12 import pathlib
13 import re
14 import shutil
15 import struct
16 import subprocess
17 import sys
18 import sysconfig
19 import tempfile
20 import shlex
21 from test.support import (captured_stdout, captured_stderr,
22 skip_if_broken_multiprocessing_synchronize, verbose,
23 requires_subprocess, is_android, is_apple_mobile,
24 is_emscripten, is_wasi,
25 requires_venv_with_pip, TEST_HOME_DIR,
26 requires_resource, copy_python_src_ignore)
27 from test.support.os_helper import (can_symlink, EnvironmentVarGuard, rmtree,
28 TESTFN, FakePath)
29 from test.support.testcase import ExtraAssertions
30 import unittest
31 import venv
32 from unittest.mock import patch, Mock
33
34 try:
35 import ctypes
36 except ImportError:
37 ctypes = None
38
39 # Platforms that set sys._base_executable can create venvs from within
40 # another venv, so no need to skip tests that require venv.create().
41 requireVenvCreate = unittest.skipUnless(
42 sys.prefix == sys.base_prefix
43 or sys._base_executable != sys.executable,
44 'cannot run venv.create from within a venv on this platform')
45
46 if is_android or is_apple_mobile or is_emscripten or is_wasi:
47 raise unittest.SkipTest("venv is not available on this platform")
48
49 @requires_subprocess()
50 def check_output(cmd, encoding=None):
51 p = subprocess.Popen(cmd,
52 stdout=subprocess.PIPE,
53 stderr=subprocess.PIPE,
54 env={**os.environ, "PYTHONHOME": ""})
55 out, err = p.communicate()
56 if p.returncode:
57 if verbose and err:
58 print(err.decode(encoding or 'utf-8', 'backslashreplace'))
59 raise subprocess.CalledProcessError(
60 p.returncode, cmd, out, err)
61 if encoding:
62 return (
63 out.decode(encoding, 'backslashreplace'),
64 err.decode(encoding, 'backslashreplace'),
65 )
66 return out, err
67
68 class BaseTest(unittest.TestCase, ExtraAssertions):
69 """Base class for venv tests."""
70 maxDiff = 80 * 50
71
72 def setUp(self):
73 self.env_dir = os.path.realpath(tempfile.mkdtemp())
74 if os.name == 'nt':
75 self.bindir = 'Scripts'
76 self.lib = ('Lib',)
77 self.include = 'Include'
78 else:
79 self.bindir = 'bin'
80 self.lib = ('lib', f'python{sysconfig._get_python_version_abi()}')
81 self.include = 'include'
82 executable = sys._base_executable
83 self.exe = os.path.split(executable)[-1]
84 if (sys.platform == 'win32'
85 and os.path.lexists(executable)
86 and not os.path.exists(executable)):
87 self.cannot_link_exe = True
88 else:
89 self.cannot_link_exe = False
90
91 def tearDown(self):
92 rmtree(self.env_dir)
93
94 def envpy(self, *, real_env_dir=False):
95 if real_env_dir:
96 env_dir = os.path.realpath(self.env_dir)
97 else:
98 env_dir = self.env_dir
99 return os.path.join(env_dir, self.bindir, self.exe)
100
101 def run_with_capture(self, func, *args, **kwargs):
102 with captured_stdout() as output:
103 with captured_stderr() as error:
104 func(*args, **kwargs)
105 return output.getvalue(), error.getvalue()
106
107 def get_env_file(self, *args):
108 return os.path.join(self.env_dir, *args)
109
110 def get_text_file_contents(self, *args, encoding='utf-8'):
111 with open(self.get_env_file(*args), 'r', encoding=encoding) as f:
112 result = f.read()
113 return result
114
115 class BasicTest(BaseTest):
116 """Test venv module functionality."""
117
118 def isdir(self, *args):
119 fn = self.get_env_file(*args)
120 self.assertTrue(os.path.isdir(fn))
121
122 def test_defaults_with_str_path(self):
123 """
124 Test the create function with default arguments and a str path.
125 """
126 rmtree(self.env_dir)
127 self.run_with_capture(venv.create, self.env_dir)
128 self._check_output_of_default_create()
129
130 def test_defaults_with_pathlike(self):
131 """
132 Test the create function with default arguments and a path-like path.
133 """
134 rmtree(self.env_dir)
135 self.run_with_capture(venv.create, FakePath(self.env_dir))
136 self._check_output_of_default_create()
137
138 def _check_output_of_default_create(self):
139 self.isdir(self.bindir)
140 self.isdir(self.include)
141 self.isdir(*self.lib)
142 # Issue 21197
143 p = self.get_env_file('lib64')
144 conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
145 (sys.platform != 'darwin'))
146 if conditions:
147 self.assertTrue(os.path.islink(p))
148 else:
149 self.assertFalse(os.path.exists(p))
150 data = self.get_text_file_contents('pyvenv.cfg')
151 executable = sys._base_executable
152 path = os.path.dirname(executable)
153 self.assertIn('home = %s' % path, data)
154 self.assertIn('executable = %s' %
155 os.path.realpath(sys.executable), data)
156 copies = '' if os.name=='nt' else ' --copies'
157 cmd = (f'command = {sys.executable} -m venv{copies} --without-pip '
158 f'--without-scm-ignore-files {self.env_dir}')
159 self.assertIn(cmd, data)
160 fn = self.get_env_file(self.bindir, self.exe)
161 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
162 bd = self.get_env_file(self.bindir)
163 print('Contents of %r:' % bd)
164 print(' %r' % os.listdir(bd))
165 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
166
167 def test_config_file_command_key(self):
168 options = [
169 (None, None, None), # Default case.
170 ('--copies', 'symlinks', False),
171 ('--without-pip', 'with_pip', False),
172 ('--system-site-packages', 'system_site_packages', True),
173 ('--clear', 'clear', True),
174 ('--upgrade', 'upgrade', True),
175 ('--upgrade-deps', 'upgrade_deps', True),
176 ('--prompt="foobar"', 'prompt', 'foobar'),
177 ('--without-scm-ignore-files', 'scm_ignore_files', frozenset()),
178 ]
179 for opt, attr, value in options:
180 with self.subTest(opt=opt, attr=attr, value=value):
181 rmtree(self.env_dir)
182 if not attr:
183 kwargs = {}
184 else:
185 kwargs = {attr: value}
186 b = venv.EnvBuilder(**kwargs)
187 b.upgrade_dependencies = Mock() # avoid pip command to upgrade deps
188 b._setup_pip = Mock() # avoid pip setup
189 self.run_with_capture(b.create, self.env_dir)
190 data = self.get_text_file_contents('pyvenv.cfg')
191 if not attr or opt.endswith('git'):
192 for opt in ('--system-site-packages', '--clear', '--upgrade',
193 '--upgrade-deps', '--prompt'):
194 self.assertNotRegex(data, rf'command = .* {opt}')
195 elif os.name=='nt' and attr=='symlinks':
196 pass
197 else:
198 self.assertRegex(data, rf'command = .* {opt}')
199
200 def test_prompt(self):
201 env_name = os.path.split(self.env_dir)[1]
202
203 rmtree(self.env_dir)
204 builder = venv.EnvBuilder()
205 self.run_with_capture(builder.create, self.env_dir)
206 context = builder.ensure_directories(self.env_dir)
207 data = self.get_text_file_contents('pyvenv.cfg')
208 self.assertEqual(context.prompt, env_name)
209 self.assertNotIn("prompt = ", data)
210
211 rmtree(self.env_dir)
212 builder = venv.EnvBuilder(prompt='My prompt')
213 self.run_with_capture(builder.create, self.env_dir)
214 context = builder.ensure_directories(self.env_dir)
215 data = self.get_text_file_contents('pyvenv.cfg')
216 self.assertEqual(context.prompt, 'My prompt')
217 self.assertIn("prompt = 'My prompt'\n", data)
218
219 rmtree(self.env_dir)
220 builder = venv.EnvBuilder(prompt='.')
221 cwd = os.path.basename(os.getcwd())
222 self.run_with_capture(builder.create, self.env_dir)
223 context = builder.ensure_directories(self.env_dir)
224 data = self.get_text_file_contents('pyvenv.cfg')
225 self.assertEqual(context.prompt, cwd)
226 self.assertIn("prompt = '%s'\n" % cwd, data)
227
228 def test_upgrade_dependencies(self):
229 builder = venv.EnvBuilder()
230 bin_path = 'bin'
231 python_exe = os.path.split(sys.executable)[1]
232 if sys.platform == 'win32':
233 bin_path = 'Scripts'
234 if os.path.normcase(os.path.splitext(python_exe)[0]).endswith('_d'):
235 python_exe = 'python_d.exe'
236 else:
237 python_exe = 'python.exe'
238 with tempfile.TemporaryDirectory() as fake_env_dir:
239 expect_exe = os.path.normcase(
240 os.path.join(fake_env_dir, bin_path, python_exe)
241 )
242 if sys.platform == 'win32':
243 expect_exe = os.path.normcase(os.path.realpath(expect_exe))
244
245 def pip_cmd_checker(cmd, **kwargs):
246 cmd[0] = os.path.normcase(cmd[0])
247 self.assertEqual(
248 cmd,
249 [
250 expect_exe,
251 '-m',
252 'pip',
253 'install',
254 '--upgrade',
255 'pip',
256 ]
257 )
258
259 fake_context = builder.ensure_directories(fake_env_dir)
260 with patch('venv.subprocess.check_output', pip_cmd_checker):
261 builder.upgrade_dependencies(fake_context)
262
263 @requireVenvCreate
264 def test_prefixes(self):
265 """
266 Test that the prefix values are as expected.
267 """
268 # check a venv's prefixes
269 rmtree(self.env_dir)
270 self.run_with_capture(venv.create, self.env_dir)
271 cmd = [self.envpy(), '-c', None]
272 for prefix, expected in (
273 ('prefix', self.env_dir),
274 ('exec_prefix', self.env_dir),
275 ('base_prefix', sys.base_prefix),
276 ('base_exec_prefix', sys.base_exec_prefix)):
277 cmd[2] = 'import sys; print(sys.%s)' % prefix
278 out, err = check_output(cmd)
279 self.assertEqual(pathlib.Path(out.strip().decode()),
280 pathlib.Path(expected), prefix)
281
282 @requireVenvCreate
283 def test_sysconfig(self):
284 """
285 Test that the sysconfig functions work in a virtual environment.
286 """
287 rmtree(self.env_dir)
288 self.run_with_capture(venv.create, self.env_dir, symlinks=False)
289 cmd = [self.envpy(), '-c', None]
290 for call, expected in (
291 # installation scheme
292 ('get_preferred_scheme("prefix")', 'venv'),
293 ('get_default_scheme()', 'venv'),
294 # build environment
295 ('is_python_build()', str(sysconfig.is_python_build())),
296 ('get_makefile_filename()', sysconfig.get_makefile_filename()),
297 ('get_config_h_filename()', sysconfig.get_config_h_filename()),
298 ('get_config_var("Py_GIL_DISABLED")',
299 str(sysconfig.get_config_var("Py_GIL_DISABLED")))):
300 with self.subTest(call):
301 cmd[2] = 'import sysconfig; print(sysconfig.%s)' % call
302 out, err = check_output(cmd, encoding='utf-8')
303 self.assertEqual(out.strip(), expected, err)
304 for attr, expected in (
305 ('executable', self.envpy()),
306 # Usually compare to sys.executable, but if we're running in our own
307 # venv then we really need to compare to our base executable
308 ('_base_executable', sys._base_executable),
309 ):
310 with self.subTest(attr):
311 cmd[2] = f'import sys; print(sys.{attr})'
312 out, err = check_output(cmd, encoding='utf-8')
313 self.assertEqual(out.strip(), expected, err)
314
315 @requireVenvCreate
316 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
317 def test_sysconfig_symlinks(self):
318 """
319 Test that the sysconfig functions work in a virtual environment.
320 """
321 rmtree(self.env_dir)
322 self.run_with_capture(venv.create, self.env_dir, symlinks=True)
323 cmd = [self.envpy(), '-c', None]
324 for call, expected in (
325 # installation scheme
326 ('get_preferred_scheme("prefix")', 'venv'),
327 ('get_default_scheme()', 'venv'),
328 # build environment
329 ('is_python_build()', str(sysconfig.is_python_build())),
330 ('get_makefile_filename()', sysconfig.get_makefile_filename()),
331 ('get_config_h_filename()', sysconfig.get_config_h_filename()),
332 ('get_config_var("Py_GIL_DISABLED")',
333 str(sysconfig.get_config_var("Py_GIL_DISABLED")))):
334 with self.subTest(call):
335 cmd[2] = 'import sysconfig; print(sysconfig.%s)' % call
336 out, err = check_output(cmd, encoding='utf-8')
337 self.assertEqual(out.strip(), expected, err)
338 for attr, expected in (
339 ('executable', self.envpy()),
340 # Usually compare to sys.executable, but if we're running in our own
341 # venv then we really need to compare to our base executable
342 # HACK: Test fails on POSIX with unversioned binary (PR gh-113033)
343 #('_base_executable', sys._base_executable),
344 ):
345 with self.subTest(attr):
346 cmd[2] = f'import sys; print(sys.{attr})'
347 out, err = check_output(cmd, encoding='utf-8')
348 self.assertEqual(out.strip(), expected, err)
349
350 if sys.platform == 'win32':
351 ENV_SUBDIRS = (
352 ('Scripts',),
353 ('Include',),
354 ('Lib',),
355 ('Lib', 'site-packages'),
356 )
357 else:
358 ENV_SUBDIRS = (
359 ('bin',),
360 ('include',),
361 ('lib',),
362 ('lib', 'python%d.%d' % sys.version_info[:2]),
363 ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
364 )
365
366 def create_contents(self, paths, filename):
367 """
368 Create some files in the environment which are unrelated
369 to the virtual environment.
370 """
371 for subdirs in paths:
372 d = os.path.join(self.env_dir, *subdirs)
373 os.mkdir(d)
374 fn = os.path.join(d, filename)
375 with open(fn, 'wb') as f:
376 f.write(b'Still here?')
377
378 def test_overwrite_existing(self):
379 """
380 Test creating environment in an existing directory.
381 """
382 self.create_contents(self.ENV_SUBDIRS, 'foo')
383 venv.create(self.env_dir)
384 for subdirs in self.ENV_SUBDIRS:
385 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
386 self.assertTrue(os.path.exists(fn))
387 with open(fn, 'rb') as f:
388 self.assertEqual(f.read(), b'Still here?')
389
390 builder = venv.EnvBuilder(clear=True)
391 builder.create(self.env_dir)
392 for subdirs in self.ENV_SUBDIRS:
393 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
394 self.assertFalse(os.path.exists(fn))
395
396 def clear_directory(self, path):
397 for fn in os.listdir(path):
398 fn = os.path.join(path, fn)
399 if os.path.islink(fn) or os.path.isfile(fn):
400 os.remove(fn)
401 elif os.path.isdir(fn):
402 rmtree(fn)
403
404 def test_unoverwritable_fails(self):
405 #create a file clashing with directories in the env dir
406 for paths in self.ENV_SUBDIRS[:3]:
407 fn = os.path.join(self.env_dir, *paths)
408 with open(fn, 'wb') as f:
409 f.write(b'')
410 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
411 self.clear_directory(self.env_dir)
412
413 def test_upgrade(self):
414 """
415 Test upgrading an existing environment directory.
416 """
417 # See Issue #21643: the loop needs to run twice to ensure
418 # that everything works on the upgrade (the first run just creates
419 # the venv).
420 for upgrade in (False, True):
421 builder = venv.EnvBuilder(upgrade=upgrade)
422 self.run_with_capture(builder.create, self.env_dir)
423 self.isdir(self.bindir)
424 self.isdir(self.include)
425 self.isdir(*self.lib)
426 fn = self.get_env_file(self.bindir, self.exe)
427 if not os.path.exists(fn):
428 # diagnostics for Windows buildbot failures
429 bd = self.get_env_file(self.bindir)
430 print('Contents of %r:' % bd)
431 print(' %r' % os.listdir(bd))
432 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
433
434 def test_isolation(self):
435 """
436 Test isolation from system site-packages
437 """
438 for ssp, s in ((True, 'true'), (False, 'false')):
439 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
440 builder.create(self.env_dir)
441 data = self.get_text_file_contents('pyvenv.cfg')
442 self.assertIn('include-system-site-packages = %s\n' % s, data)
443
444 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
445 def test_symlinking(self):
446 """
447 Test symlinking works as expected
448 """
449 for usl in (False, True):
450 builder = venv.EnvBuilder(clear=True, symlinks=usl)
451 builder.create(self.env_dir)
452 fn = self.get_env_file(self.bindir, self.exe)
453 # Don't test when False, because e.g. 'python' is always
454 # symlinked to 'python3.3' in the env, even when symlinking in
455 # general isn't wanted.
456 if usl:
457 if self.cannot_link_exe:
458 # Symlinking is skipped when our executable is already a
459 # special app symlink
460 self.assertFalse(os.path.islink(fn))
461 else:
462 self.assertTrue(os.path.islink(fn))
463
464 # If a venv is created from a source build and that venv is used to
465 # run the test, the pyvenv.cfg in the venv created in the test will
466 # point to the venv being used to run the test, and we lose the link
467 # to the source build - so Python can't initialise properly.
468 @requireVenvCreate
469 def test_executable(self):
470 """
471 Test that the sys.executable value is as expected.
472 """
473 rmtree(self.env_dir)
474 self.run_with_capture(venv.create, self.env_dir)
475 envpy = self.envpy(real_env_dir=True)
476 out, err = check_output([envpy, '-c',
477 'import sys; print(sys.executable)'])
478 self.assertEqual(out.strip(), envpy.encode())
479
480 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
481 def test_executable_symlinks(self):
482 """
483 Test that the sys.executable value is as expected.
484 """
485 rmtree(self.env_dir)
486 builder = venv.EnvBuilder(clear=True, symlinks=True)
487 builder.create(self.env_dir)
488 envpy = self.envpy(real_env_dir=True)
489 out, err = check_output([envpy, '-c',
490 'import sys; print(sys.executable)'])
491 self.assertEqual(out.strip(), envpy.encode())
492
493 # gh-124651: test quoted strings
494 @unittest.skipIf(os.name == 'nt', 'contains invalid characters on Windows')
495 def test_special_chars_bash(self):
496 """
497 Test that the template strings are quoted properly (bash)
498 """
499 rmtree(self.env_dir)
500 bash = shutil.which('bash')
501 if bash is None:
502 self.skipTest('bash required for this test')
503 env_name = '"\';&&$e|\'"'
504 env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
505 builder = venv.EnvBuilder(clear=True)
506 builder.create(env_dir)
507 activate = os.path.join(env_dir, self.bindir, 'activate')
508 test_script = os.path.join(self.env_dir, 'test_special_chars.sh')
509 with open(test_script, "w") as f:
510 f.write(f'source {shlex.quote(activate)}\n'
511 'python -c \'import sys; print(sys.executable)\'\n'
512 'python -c \'import os; print(os.environ["VIRTUAL_ENV"])\'\n'
513 'deactivate\n')
514 out, err = check_output([bash, test_script])
515 lines = out.splitlines()
516 self.assertTrue(env_name.encode() in lines[0])
517 self.assertEndsWith(lines[1], env_name.encode())
518
519 # gh-124651: test quoted strings
520 @unittest.skipIf(os.name == 'nt', 'contains invalid characters on Windows')
521 @unittest.skipIf(sys.platform.startswith('netbsd'),
522 "NetBSD csh fails with quoted special chars; see gh-139308")
523 def test_special_chars_csh(self):
524 """
525 Test that the template strings are quoted properly (csh)
526 """
527 rmtree(self.env_dir)
528 csh = shutil.which('tcsh') or shutil.which('csh')
529 if csh is None:
530 self.skipTest('csh required for this test')
531 env_name = '"\';&&$e|\'"'
532 env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
533 builder = venv.EnvBuilder(clear=True)
534 builder.create(env_dir)
535 activate = os.path.join(env_dir, self.bindir, 'activate.csh')
536 test_script = os.path.join(self.env_dir, 'test_special_chars.csh')
537 with open(test_script, "w") as f:
538 f.write(f'source {shlex.quote(activate)}\n'
539 'python -c \'import sys; print(sys.executable)\'\n'
540 'python -c \'import os; print(os.environ["VIRTUAL_ENV"])\'\n'
541 'deactivate\n')
542 out, err = check_output([csh, test_script])
543 lines = out.splitlines()
544 self.assertTrue(env_name.encode() in lines[0])
545 self.assertEndsWith(lines[1], env_name.encode())
546
547 # gh-124651: test quoted strings on Windows
548 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
549 def test_special_chars_windows(self):
550 """
551 Test that the template strings are quoted properly on Windows
552 """
553 rmtree(self.env_dir)
554 env_name = "'&&^$e"
555 env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
556 builder = venv.EnvBuilder(clear=True)
557 builder.create(env_dir)
558 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
559 test_batch = os.path.join(self.env_dir, 'test_special_chars.bat')
560 with open(test_batch, "w") as f:
561 f.write('@echo off\n'
562 f'"{activate}" & '
563 f'{self.exe} -c "import sys; print(sys.executable)" & '
564 f'{self.exe} -c "import os; print(os.environ[\'VIRTUAL_ENV\'])" & '
565 'deactivate')
566 out, err = check_output([test_batch])
567 lines = out.splitlines()
568 self.assertTrue(env_name.encode() in lines[0])
569 self.assertEndsWith(lines[1], env_name.encode())
570
571 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
572 def test_unicode_in_batch_file(self):
573 """
574 Test handling of Unicode paths
575 """
576 rmtree(self.env_dir)
577 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
578 builder = venv.EnvBuilder(clear=True)
579 builder.create(env_dir)
580 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
581 out, err = check_output(
582 [activate, '&', self.exe, '-c', 'print(0)'],
583 encoding='oem',
584 )
585 self.assertEqual(out.strip(), '0')
586
587 @unittest.skipUnless(os.name == 'nt' and can_symlink(),
588 'symlinks on Windows')
589 def test_failed_symlink(self):
590 """
591 Test handling of failed symlinks on Windows.
592 """
593 rmtree(self.env_dir)
594 env_dir = os.path.join(os.path.realpath(self.env_dir), 'venv')
595 with patch('os.symlink') as mock_symlink:
596 mock_symlink.side_effect = OSError()
597 builder = venv.EnvBuilder(clear=True, symlinks=True)
598 _, err = self.run_with_capture(builder.create, env_dir)
599 filepath_regex = r"'[A-Z]:\\\\(?:[^\\\\]+\\\\)*[^\\\\]+'"
600 self.assertRegex(err, rf"Unable to symlink {filepath_regex} to {filepath_regex}")
601
602 @requireVenvCreate
603 def test_multiprocessing(self):
604 """
605 Test that the multiprocessing is able to spawn.
606 """
607 # bpo-36342: Instantiation of a Pool object imports the
608 # multiprocessing.synchronize module. Skip the test if this module
609 # cannot be imported.
610 skip_if_broken_multiprocessing_synchronize()
611
612 rmtree(self.env_dir)
613 self.run_with_capture(venv.create, self.env_dir)
614 out, err = check_output([self.envpy(real_env_dir=True), '-c',
615 'from multiprocessing import Pool; '
616 'pool = Pool(1); '
617 'print(pool.apply_async("Python".lower).get(3)); '
618 'pool.terminate()'])
619 self.assertEqual(out.strip(), "python".encode())
620
621 @requireVenvCreate
622 def test_multiprocessing_recursion(self):
623 """
624 Test that the multiprocessing is able to spawn itself
625 """
626 skip_if_broken_multiprocessing_synchronize()
627
628 rmtree(self.env_dir)
629 self.run_with_capture(venv.create, self.env_dir)
630 script = os.path.join(TEST_HOME_DIR, '_test_venv_multiprocessing.py')
631 subprocess.check_call([self.envpy(real_env_dir=True), "-I", script])
632
633 @unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
634 def test_deactivate_with_strict_bash_opts(self):
635 bash = shutil.which("bash")
636 if bash is None:
637 self.skipTest("bash required for this test")
638 rmtree(self.env_dir)
639 builder = venv.EnvBuilder(clear=True)
640 builder.create(self.env_dir)
641 activate = os.path.join(self.env_dir, self.bindir, "activate")
642 test_script = os.path.join(self.env_dir, "test_strict.sh")
643 with open(test_script, "w") as f:
644 f.write("set -euo pipefail\n"
645 f"source {activate}\n"
646 "deactivate\n")
647 out, err = check_output([bash, test_script])
648 self.assertEqual(out, "".encode())
649 self.assertEqual(err, "".encode())
650
651
652 @unittest.skipUnless(sys.platform == 'darwin', 'only relevant on macOS')
653 def test_macos_env(self):
654 rmtree(self.env_dir)
655 builder = venv.EnvBuilder()
656 builder.create(self.env_dir)
657
658 out, err = check_output([self.envpy(real_env_dir=True), '-c',
659 'import os; print("__PYVENV_LAUNCHER__" in os.environ)'])
660 self.assertEqual(out.strip(), 'False'.encode())
661
662 def test_pathsep_error(self):
663 """
664 Test that venv creation fails when the target directory contains
665 the path separator.
666 """
667 rmtree(self.env_dir)
668 bad_itempath = self.env_dir + os.pathsep
669 self.assertRaises(ValueError, venv.create, bad_itempath)
670 self.assertRaises(ValueError, venv.create, FakePath(bad_itempath))
671
672 @unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
673 @requireVenvCreate
674 def test_zippath_from_non_installed_posix(self):
675 """
676 Test that when create venv from non-installed python, the zip path
677 value is as expected.
678 """
679 rmtree(self.env_dir)
680 # First try to create a non-installed python. It's not a real full
681 # functional non-installed python, but enough for this test.
682 platlibdir = sys.platlibdir
683 non_installed_dir = os.path.realpath(tempfile.mkdtemp())
684 self.addCleanup(rmtree, non_installed_dir)
685 bindir = os.path.join(non_installed_dir, self.bindir)
686 os.mkdir(bindir)
687 shutil.copy2(sys.executable, bindir)
688 libdir = os.path.join(non_installed_dir, platlibdir, self.lib[1])
689 os.makedirs(libdir)
690 landmark = os.path.join(libdir, "os.py")
691 abi_thread = "t" if sysconfig.get_config_var("Py_GIL_DISABLED") else ""
692 stdlib_zip = f"python{sys.version_info.major}{sys.version_info.minor}{abi_thread}"
693 zip_landmark = os.path.join(non_installed_dir,
694 platlibdir,
695 stdlib_zip)
696 additional_pythonpath_for_non_installed = []
697
698 # Copy stdlib files to the non-installed python so venv can
699 # correctly calculate the prefix.
700 for eachpath in sys.path:
701 if eachpath.endswith(".zip"):
702 if os.path.isfile(eachpath):
703 shutil.copyfile(
704 eachpath,
705 os.path.join(non_installed_dir, platlibdir))
706 elif os.path.isfile(os.path.join(eachpath, "os.py")):
707 names = os.listdir(eachpath)
708 ignored_names = copy_python_src_ignore(eachpath, names)
709 for name in names:
710 if name in ignored_names:
711 continue
712 if name == "site-packages":
713 continue
714 fn = os.path.join(eachpath, name)
715 if os.path.isfile(fn):
716 shutil.copy(fn, libdir)
717 elif os.path.isdir(fn):
718 shutil.copytree(fn, os.path.join(libdir, name),
719 ignore=copy_python_src_ignore)
720 else:
721 additional_pythonpath_for_non_installed.append(
722 eachpath)
723 cmd = [os.path.join(non_installed_dir, self.bindir, self.exe),
724 "-m",
725 "venv",
726 "--without-pip",
727 "--without-scm-ignore-files",
728 self.env_dir]
729 # Our fake non-installed python is not fully functional because
730 # it cannot find the extensions. Set PYTHONPATH so it can run the
731 # venv module correctly.
732 pythonpath = os.pathsep.join(
733 additional_pythonpath_for_non_installed)
734 # For python built with shared enabled. We need to set
735 # LD_LIBRARY_PATH so the non-installed python can find and link
736 # libpython.so
737 ld_library_path = sysconfig.get_config_var("LIBDIR")
738 if not ld_library_path or sysconfig.is_python_build():
739 ld_library_path = os.path.abspath(os.path.dirname(sys.executable))
740 if sys.platform == 'darwin':
741 ld_library_path_env = "DYLD_LIBRARY_PATH"
742 else:
743 ld_library_path_env = "LD_LIBRARY_PATH"
744 child_env = {
745 "PYTHONPATH": pythonpath,
746 ld_library_path_env: ld_library_path,
747 }
748 if asan_options := os.environ.get("ASAN_OPTIONS"):
749 # prevent https://github.com/python/cpython/issues/104839
750 child_env["ASAN_OPTIONS"] = asan_options
751 subprocess.check_call(cmd, env=child_env)
752 # Now check the venv created from the non-installed python has
753 # correct zip path in pythonpath.
754 cmd = [self.envpy(), '-S', '-c', 'import sys; print(sys.path)']
755 out, err = check_output(cmd)
756 self.assertTrue(zip_landmark.encode() in out)
757
758 @requireVenvCreate
759 def test_activate_shell_script_has_no_dos_newlines(self):
760 """
761 Test that the `activate` shell script contains no CR LF.
762 This is relevant for Cygwin, as the Windows build might have
763 converted line endings accidentally.
764 """
765 venv_dir = pathlib.Path(self.env_dir)
766 rmtree(venv_dir)
767 [[scripts_dir], *_] = self.ENV_SUBDIRS
768 script_path = venv_dir / scripts_dir / "activate"
769 venv.create(venv_dir)
770 with open(script_path, 'rb') as script:
771 for i, line in enumerate(script, 1):
772 error_message = f"CR LF found in line {i}"
773 self.assertFalse(line.endswith(b'\r\n'), error_message)
774
775 @requireVenvCreate
776 def test_scm_ignore_files_git(self):
777 """
778 Test that a .gitignore file is created when "git" is specified.
779 The file should contain a `*\n` line.
780 """
781 self.run_with_capture(venv.create, self.env_dir,
782 scm_ignore_files={'git'})
783 file_lines = self.get_text_file_contents('.gitignore').splitlines()
784 self.assertIn('*', file_lines)
785
786 @requireVenvCreate
787 def test_create_scm_ignore_files_multiple(self):
788 """
789 Test that ``scm_ignore_files`` can work with multiple SCMs.
790 """
791 bzrignore_name = ".bzrignore"
792 contents = "# For Bazaar.\n*\n"
793
794 class BzrEnvBuilder(venv.EnvBuilder):
795 def create_bzr_ignore_file(self, context):
796 gitignore_path = os.path.join(context.env_dir, bzrignore_name)
797 with open(gitignore_path, 'w', encoding='utf-8') as file:
798 file.write(contents)
799
800 builder = BzrEnvBuilder(scm_ignore_files={'git', 'bzr'})
801 self.run_with_capture(builder.create, self.env_dir)
802
803 gitignore_lines = self.get_text_file_contents('.gitignore').splitlines()
804 self.assertIn('*', gitignore_lines)
805
806 bzrignore = self.get_text_file_contents(bzrignore_name)
807 self.assertEqual(bzrignore, contents)
808
809 @requireVenvCreate
810 def test_create_scm_ignore_files_empty(self):
811 """
812 Test that no default ignore files are created when ``scm_ignore_files``
813 is empty.
814 """
815 # scm_ignore_files is set to frozenset() by default.
816 self.run_with_capture(venv.create, self.env_dir)
817 with self.assertRaises(FileNotFoundError):
818 self.get_text_file_contents('.gitignore')
819
820 self.assertIn("--without-scm-ignore-files",
821 self.get_text_file_contents('pyvenv.cfg'))
822
823 @requireVenvCreate
824 def test_cli_with_scm_ignore_files(self):
825 """
826 Test that default SCM ignore files are created by default via the CLI.
827 """
828 self.run_with_capture(venv.main, ['--without-pip', self.env_dir])
829
830 gitignore_lines = self.get_text_file_contents('.gitignore').splitlines()
831 self.assertIn('*', gitignore_lines)
832
833 @requireVenvCreate
834 def test_cli_without_scm_ignore_files(self):
835 """
836 Test that ``--without-scm-ignore-files`` doesn't create SCM ignore files.
837 """
838 args = ['--without-pip', '--without-scm-ignore-files', self.env_dir]
839 self.run_with_capture(venv.main, args)
840
841 with self.assertRaises(FileNotFoundError):
842 self.get_text_file_contents('.gitignore')
843
844 def test_venv_same_path(self):
845 same_path = venv.EnvBuilder._same_path
846 if sys.platform == 'win32':
847 # Case-insensitive, and handles short/long names
848 tests = [
849 (True, TESTFN, TESTFN),
850 (True, TESTFN.lower(), TESTFN.upper()),
851 ]
852 import _winapi
853 # ProgramFiles is the most reliable path that will have short/long
854 progfiles = os.getenv('ProgramFiles')
855 if progfiles:
856 tests = [
857 *tests,
858 (True, progfiles, progfiles),
859 (True, _winapi.GetShortPathName(progfiles), _winapi.GetLongPathName(progfiles)),
860 ]
861 else:
862 # Just a simple case-sensitive comparison
863 tests = [
864 (True, TESTFN, TESTFN),
865 (False, TESTFN.lower(), TESTFN.upper()),
866 ]
867 for r, path1, path2 in tests:
868 with self.subTest(f"{path1}-{path2}"):
869 if r:
870 self.assertTrue(same_path(path1, path2))
871 else:
872 self.assertFalse(same_path(path1, path2))
873
874 # gh-126084: venvwlauncher should run pythonw, not python
875 @requireVenvCreate
876 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
877 def test_venvwlauncher(self):
878 """
879 Test that the GUI launcher runs the GUI python.
880 """
881 rmtree(self.env_dir)
882 venv.create(self.env_dir)
883 exename = self.exe
884 # Retain the debug suffix if present
885 if "python" in exename and not "pythonw" in exename:
886 exename = exename.replace("python", "pythonw")
887 envpyw = os.path.join(self.env_dir, self.bindir, exename)
888 try:
889 subprocess.check_call([envpyw, "-c", "import sys; "
890 "assert sys._base_executable.endswith('%s')" % exename])
891 except subprocess.CalledProcessError:
892 self.fail("venvwlauncher.exe did not run %s" % exename)
893
894
895 @requireVenvCreate
896 class EnsurePipTest(BaseTest):
897 """Test venv module installation of pip."""
898 def assert_pip_not_installed(self):
899 out, err = check_output([self.envpy(real_env_dir=True), '-c',
900 'try:\n import pip\nexcept ImportError:\n print("OK")'])
901 # We force everything to text, so unittest gives the detailed diff
902 # if we get unexpected results
903 err = err.decode("latin-1") # Force to text, prevent decoding errors
904 self.assertEqual(err, "")
905 out = out.decode("latin-1") # Force to text, prevent decoding errors
906 self.assertEqual(out.strip(), "OK")
907
908
909 def test_no_pip_by_default(self):
910 rmtree(self.env_dir)
911 self.run_with_capture(venv.create, self.env_dir)
912 self.assert_pip_not_installed()
913
914 def test_explicit_no_pip(self):
915 rmtree(self.env_dir)
916 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
917 self.assert_pip_not_installed()
918
919 def test_devnull(self):
920 # Fix for issue #20053 uses os.devnull to force a config file to
921 # appear empty. However http://bugs.python.org/issue20541 means
922 # that doesn't currently work properly on Windows. Once that is
923 # fixed, the "win_location" part of test_with_pip should be restored
924 with open(os.devnull, "rb") as f:
925 self.assertEqual(f.read(), b"")
926
927 self.assertTrue(os.path.exists(os.devnull))
928
929 def do_test_with_pip(self, system_site_packages):
930 rmtree(self.env_dir)
931 with EnvironmentVarGuard() as envvars:
932 # pip's cross-version compatibility may trigger deprecation
933 # warnings in current versions of Python. Ensure related
934 # environment settings don't cause venv to fail.
935 envvars["PYTHONWARNINGS"] = "ignore"
936 # ensurepip is different enough from a normal pip invocation
937 # that we want to ensure it ignores the normal pip environment
938 # variable settings. We set PIP_NO_INSTALL here specifically
939 # to check that ensurepip (and hence venv) ignores it.
940 # See http://bugs.python.org/issue19734
941 envvars["PIP_NO_INSTALL"] = "1"
942 # Also check that we ignore the pip configuration file
943 # See http://bugs.python.org/issue20053
944 with tempfile.TemporaryDirectory() as home_dir:
945 envvars["HOME"] = home_dir
946 bad_config = "[global]\nno-install=1"
947 # Write to both config file names on all platforms to reduce
948 # cross-platform variation in test code behaviour
949 win_location = ("pip", "pip.ini")
950 posix_location = (".pip", "pip.conf")
951 # Skips win_location due to http://bugs.python.org/issue20541
952 for dirname, fname in (posix_location,):
953 dirpath = os.path.join(home_dir, dirname)
954 os.mkdir(dirpath)
955 fpath = os.path.join(dirpath, fname)
956 with open(fpath, 'w') as f:
957 f.write(bad_config)
958
959 # Actually run the create command with all that unhelpful
960 # config in place to ensure we ignore it
961 with self.nicer_error():
962 self.run_with_capture(venv.create, self.env_dir,
963 system_site_packages=system_site_packages,
964 with_pip=True)
965 # Ensure pip is available in the virtual environment
966 # Ignore DeprecationWarning since pip code is not part of Python
967 out, err = check_output([self.envpy(real_env_dir=True),
968 '-W', 'ignore::DeprecationWarning',
969 '-W', 'ignore::ImportWarning', '-I',
970 '-m', 'pip', '--version'])
971 # We force everything to text, so unittest gives the detailed diff
972 # if we get unexpected results
973 err = err.decode("latin-1") # Force to text, prevent decoding errors
974 self.assertEqual(err, "")
975 out = out.decode("latin-1") # Force to text, prevent decoding errors
976 expected_version = "pip {}".format(ensurepip.version())
977 self.assertEqual(out[:len(expected_version)], expected_version)
978 env_dir = os.fsencode(self.env_dir).decode("latin-1")
979 self.assertIn(env_dir, out)
980
981 # http://bugs.python.org/issue19728
982 # Check the private uninstall command provided for the Windows
983 # installers works (at least in a virtual environment)
984 with EnvironmentVarGuard() as envvars:
985 with self.nicer_error():
986 # It seems ensurepip._uninstall calls subprocesses which do not
987 # inherit the interpreter settings.
988 envvars["PYTHONWARNINGS"] = "ignore"
989 out, err = check_output([self.envpy(real_env_dir=True),
990 '-W', 'ignore::DeprecationWarning',
991 '-W', 'ignore::ImportWarning', '-I',
992 '-m', 'ensurepip._uninstall'])
993 # We force everything to text, so unittest gives the detailed diff
994 # if we get unexpected results
995 err = err.decode("latin-1") # Force to text, prevent decoding errors
996 # Ignore the warning:
997 # "The directory '$HOME/.cache/pip/http' or its parent directory
998 # is not owned by the current user and the cache has been disabled.
999 # Please check the permissions and owner of that directory. If
1000 # executing pip with sudo, you may want sudo's -H flag."
1001 # where $HOME is replaced by the HOME environment variable.
1002 err = re.sub("^(WARNING: )?The directory .* or its parent directory "
1003 "is not owned or is not writable by the current user.*$", "",
1004 err, flags=re.MULTILINE)
1005 # Ignore warning about missing optional module:
1006 try:
1007 import ssl
1008 except ImportError:
1009 err = re.sub(
1010 "^WARNING: Disabling truststore since ssl support is missing$",
1011 "",
1012 err, flags=re.MULTILINE)
1013 self.assertEqual(err.rstrip(), "")
1014 # Being fairly specific regarding the expected behaviour for the
1015 # initial bundling phase in Python 3.4. If the output changes in
1016 # future pip versions, this test can likely be relaxed further.
1017 out = out.decode("latin-1") # Force to text, prevent decoding errors
1018 self.assertIn("Successfully uninstalled pip", out)
1019 # Check pip is now gone from the virtual environment. This only
1020 # applies in the system_site_packages=False case, because in the
1021 # other case, pip may still be available in the system site-packages
1022 if not system_site_packages:
1023 self.assert_pip_not_installed()
1024
1025 @contextlib.contextmanager
1026 def nicer_error(self):
1027 """
1028 Capture output from a failed subprocess for easier debugging.
1029
1030 The output this handler produces can be a little hard to read,
1031 but at least it has all the details.
1032 """
1033 try:
1034 yield
1035 except subprocess.CalledProcessError as exc:
1036 out = (exc.output or b'').decode(errors="replace")
1037 err = (exc.stderr or b'').decode(errors="replace")
1038 self.fail(
1039 f"{exc}\n\n"
1040 f"**Subprocess Output**\n{out}\n\n"
1041 f"**Subprocess Error**\n{err}"
1042 )
1043
1044 @requires_venv_with_pip()
1045 @requires_resource('cpu')
1046 def test_with_pip(self):
1047 self.do_test_with_pip(False)
1048 self.do_test_with_pip(True)
1049
1050
1051 if __name__ == "__main__":
1052 unittest.main()