Debian Codegraph @

lib-python/3/test/test_venv.py

raw symbols SCIP
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_emscripten, is_wasi,
24 requires_venv_with_pip, TEST_HOME_DIR,
25 requires_resource, copy_python_src_ignore, impl_detail)
26 from test.support.os_helper import (can_symlink, EnvironmentVarGuard, rmtree)
27 import unittest
28 import venv
29 from unittest.mock import patch, Mock
30
31 try:
32 import ctypes
33 except ImportError:
34 ctypes = None
35
36 # Platforms that set sys._base_executable can create venvs from within
37 # another venv, so no need to skip tests that require venv.create().
38 requireVenvCreate = unittest.skipUnless(
39 sys.prefix == sys.base_prefix
40 or sys._base_executable != sys.executable,
41 'cannot run venv.create from within a venv on this platform')
42
43 if is_emscripten or is_wasi:
44 raise unittest.SkipTest("venv is not available on Emscripten/WASI.")
45
46 @requires_subprocess()
47 def check_output(cmd, encoding=None):
48 p = subprocess.Popen(cmd,
49 stdout=subprocess.PIPE,
50 stderr=subprocess.PIPE,
51 encoding=encoding)
52 out, err = p.communicate()
53 if p.returncode:
54 if verbose and err:
55 print(err.decode('utf-8', 'backslashreplace'))
56 raise subprocess.CalledProcessError(
57 p.returncode, cmd, out, err)
58 return out, err
59
60 class BaseTest(unittest.TestCase):
61 """Base class for venv tests."""
62 maxDiff = 80 * 50
63
64 def setUp(self):
65 self.env_dir = os.path.realpath(tempfile.mkdtemp())
66 if os.name == 'nt':
67 self.bindir = 'Scripts'
68 self.lib = ('Lib',)
69 self.include = 'Include'
70 else:
71 self.bindir = 'bin'
72 self.lib = ('lib', 'pypy%d.%d' % sys.version_info[:2])
73 self.include = 'include'
74 executable = sys._base_executable
75 self.exe = os.path.split(executable)[-1]
76 if (sys.platform == 'win32'
77 and os.path.lexists(executable)
78 and not os.path.exists(executable)):
79 self.cannot_link_exe = True
80 else:
81 self.cannot_link_exe = False
82
83 def tearDown(self):
84 rmtree(self.env_dir)
85
86 def run_with_capture(self, func, *args, **kwargs):
87 with captured_stdout() as output:
88 with captured_stderr() as error:
89 func(*args, **kwargs)
90 return output.getvalue(), error.getvalue()
91
92 def get_env_file(self, *args):
93 return os.path.join(self.env_dir, *args)
94
95 def get_text_file_contents(self, *args, encoding='utf-8'):
96 with open(self.get_env_file(*args), 'r', encoding=encoding) as f:
97 result = f.read()
98 return result
99
100 def assertEndsWith(self, string, tail):
101 if not string.endswith(tail):
102 self.fail(f"String {string!r} does not end with {tail!r}")
103
104 class BasicTest(BaseTest):
105 """Test venv module functionality."""
106
107 def isdir(self, *args):
108 fn = self.get_env_file(*args)
109 self.assertTrue(os.path.isdir(fn))
110
111 def test_defaults_with_str_path(self):
112 """
113 Test the create function with default arguments and a str path.
114 """
115 rmtree(self.env_dir)
116 self.run_with_capture(venv.create, self.env_dir)
117 self._check_output_of_default_create()
118
119 def test_defaults_with_pathlib_path(self):
120 """
121 Test the create function with default arguments and a pathlib.Path path.
122 """
123 rmtree(self.env_dir)
124 self.run_with_capture(venv.create, pathlib.Path(self.env_dir))
125 self._check_output_of_default_create()
126
127 def _check_output_of_default_create(self):
128 self.isdir(self.bindir)
129 self.isdir(self.include)
130 self.isdir(*self.lib)
131 # Issue 21197
132 p = self.get_env_file('lib64')
133 conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
134 (sys.platform != 'darwin'))
135 if conditions:
136 self.assertTrue(os.path.islink(p))
137 else:
138 self.assertFalse(os.path.exists(p))
139 data = self.get_text_file_contents('pyvenv.cfg')
140 executable = sys._base_executable
141 path = os.path.dirname(executable)
142 self.assertIn('home = %s' % path, data)
143 self.assertIn('executable = %s' %
144 os.path.realpath(sys.executable), data)
145 copies = '' if os.name=='nt' else ' --copies'
146 cmd = f'command = {sys.executable} -m venv{copies} --without-pip {self.env_dir}'
147 self.assertIn(cmd, data)
148 fn = self.get_env_file(self.bindir, self.exe)
149 if not os.path.exists(fn): # diagnostics for Windows buildbot failures
150 bd = self.get_env_file(self.bindir)
151 print('Contents of %r:' % bd)
152 print(' %r' % os.listdir(bd))
153 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
154
155 def test_config_file_command_key(self):
156 attrs = [
157 (None, None),
158 ('symlinks', '--copies'),
159 ('with_pip', '--without-pip'),
160 ('system_site_packages', '--system-site-packages'),
161 ('clear', '--clear'),
162 ('upgrade', '--upgrade'),
163 ('upgrade_deps', '--upgrade-deps'),
164 ('prompt', '--prompt'),
165 ]
166 for attr, opt in attrs:
167 rmtree(self.env_dir)
168 if not attr:
169 b = venv.EnvBuilder()
170 else:
171 b = venv.EnvBuilder(
172 **{attr: False if attr in ('with_pip', 'symlinks') else True})
173 b.upgrade_dependencies = Mock() # avoid pip command to upgrade deps
174 b._setup_pip = Mock() # avoid pip setup
175 self.run_with_capture(b.create, self.env_dir)
176 data = self.get_text_file_contents('pyvenv.cfg')
177 if not attr:
178 for opt in ('--system-site-packages', '--clear', '--upgrade',
179 '--upgrade-deps', '--prompt'):
180 self.assertNotRegex(data, rf'command = .* {opt}')
181 elif os.name=='nt' and attr=='symlinks':
182 pass
183 else:
184 self.assertRegex(data, rf'command = .* {opt}')
185
186 def test_prompt(self):
187 env_name = os.path.split(self.env_dir)[1]
188
189 rmtree(self.env_dir)
190 builder = venv.EnvBuilder()
191 self.run_with_capture(builder.create, self.env_dir)
192 context = builder.ensure_directories(self.env_dir)
193 data = self.get_text_file_contents('pyvenv.cfg')
194 self.assertEqual(context.prompt, '(%s) ' % env_name)
195 self.assertNotIn("prompt = ", data)
196
197 rmtree(self.env_dir)
198 builder = venv.EnvBuilder(prompt='My prompt')
199 self.run_with_capture(builder.create, self.env_dir)
200 context = builder.ensure_directories(self.env_dir)
201 data = self.get_text_file_contents('pyvenv.cfg')
202 self.assertEqual(context.prompt, '(My prompt) ')
203 self.assertIn("prompt = 'My prompt'\n", data)
204
205 rmtree(self.env_dir)
206 builder = venv.EnvBuilder(prompt='.')
207 cwd = os.path.basename(os.getcwd())
208 self.run_with_capture(builder.create, self.env_dir)
209 context = builder.ensure_directories(self.env_dir)
210 data = self.get_text_file_contents('pyvenv.cfg')
211 self.assertEqual(context.prompt, '(%s) ' % cwd)
212 self.assertIn("prompt = '%s'\n" % cwd, data)
213
214 def test_upgrade_dependencies(self):
215 builder = venv.EnvBuilder()
216 bin_path = 'Scripts' if sys.platform == 'win32' else 'bin'
217 python_exe = os.path.split(sys.executable)[1]
218 with tempfile.TemporaryDirectory() as fake_env_dir:
219 expect_exe = os.path.normcase(
220 os.path.join(fake_env_dir, bin_path, python_exe)
221 )
222 if sys.platform == 'win32':
223 expect_exe = os.path.normcase(os.path.realpath(expect_exe))
224
225 def pip_cmd_checker(cmd, **kwargs):
226 cmd[0] = os.path.normcase(cmd[0])
227 self.assertEqual(
228 cmd,
229 [
230 expect_exe,
231 '-m',
232 'pip',
233 'install',
234 '--upgrade',
235 'pip',
236 'setuptools'
237 ]
238 )
239
240 fake_context = builder.ensure_directories(fake_env_dir)
241 with patch('venv.subprocess.check_output', pip_cmd_checker):
242 builder.upgrade_dependencies(fake_context)
243
244 @requireVenvCreate
245 def test_prefixes(self):
246 """
247 Test that the prefix values are as expected.
248 """
249 # check a venv's prefixes
250 rmtree(self.env_dir)
251 self.run_with_capture(venv.create, self.env_dir)
252 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
253 cmd = [envpy, '-c', None]
254 for prefix, expected in (
255 ('prefix', self.env_dir),
256 ('exec_prefix', self.env_dir),
257 ('base_prefix', sys.base_prefix),
258 ('base_exec_prefix', sys.base_exec_prefix)):
259 cmd[2] = 'import sys; print(sys.%s)' % prefix
260 out, err = check_output(cmd)
261 self.assertEqual(pathlib.Path(out.strip().decode()),
262 pathlib.Path(expected), prefix)
263
264 @requireVenvCreate
265 def test_sysconfig(self):
266 """
267 Test that the sysconfig functions work in a virtual environment.
268 """
269 rmtree(self.env_dir)
270 self.run_with_capture(venv.create, self.env_dir, symlinks=False)
271 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
272 cmd = [envpy, '-c', None]
273 for call, expected in (
274 # installation scheme
275 ('get_preferred_scheme("prefix")', 'venv'),
276 ('get_default_scheme()', 'venv'),
277 # build environment
278 ('is_python_build()', str(sysconfig.is_python_build())),
279 ('get_makefile_filename()', sysconfig.get_makefile_filename()),
280 ('get_config_h_filename()', sysconfig.get_config_h_filename())):
281 with self.subTest(call):
282 cmd[2] = 'import sysconfig; print(sysconfig.%s)' % call
283 out, err = check_output(cmd)
284 self.assertEqual(out.strip(), expected.encode(), err)
285
286 @requireVenvCreate
287 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
288 def test_sysconfig_symlinks(self):
289 """
290 Test that the sysconfig functions work in a virtual environment.
291 """
292 rmtree(self.env_dir)
293 self.run_with_capture(venv.create, self.env_dir, symlinks=True)
294 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
295 cmd = [envpy, '-c', None]
296 for call, expected in (
297 # installation scheme
298 ('get_preferred_scheme("prefix")', 'venv'),
299 ('get_default_scheme()', 'venv'),
300 # build environment
301 ('is_python_build()', str(sysconfig.is_python_build())),
302 ('get_makefile_filename()', sysconfig.get_makefile_filename()),
303 ('get_config_h_filename()', sysconfig.get_config_h_filename())):
304 with self.subTest(call):
305 cmd[2] = 'import sysconfig; print(sysconfig.%s)' % call
306 out, err = check_output(cmd)
307 self.assertEqual(out.strip(), expected.encode(), err)
308
309 if sys.platform == 'win32':
310 ENV_SUBDIRS = (
311 ('Scripts',),
312 ('Include',),
313 ('Lib',),
314 ('Lib', 'site-packages'),
315 )
316 else:
317 ENV_SUBDIRS = (
318 ('bin',),
319 ('include',),
320 ('lib',),
321 ('lib', 'pypy%d.%d' % sys.version_info[:2]),
322 ('lib', 'pypy%d.%d' % sys.version_info[:2], 'site-packages'),
323 )
324
325 def create_contents(self, paths, filename):
326 """
327 Create some files in the environment which are unrelated
328 to the virtual environment.
329 """
330 for subdirs in paths:
331 d = os.path.join(self.env_dir, *subdirs)
332 os.mkdir(d)
333 fn = os.path.join(d, filename)
334 with open(fn, 'wb') as f:
335 f.write(b'Still here?')
336
337 def test_overwrite_existing(self):
338 """
339 Test creating environment in an existing directory.
340 """
341 self.create_contents(self.ENV_SUBDIRS, 'foo')
342 venv.create(self.env_dir)
343 for subdirs in self.ENV_SUBDIRS:
344 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
345 self.assertTrue(os.path.exists(fn))
346 with open(fn, 'rb') as f:
347 self.assertEqual(f.read(), b'Still here?')
348
349 builder = venv.EnvBuilder(clear=True)
350 builder.create(self.env_dir)
351 for subdirs in self.ENV_SUBDIRS:
352 fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
353 self.assertFalse(os.path.exists(fn))
354
355 def clear_directory(self, path):
356 for fn in os.listdir(path):
357 fn = os.path.join(path, fn)
358 if os.path.islink(fn) or os.path.isfile(fn):
359 os.remove(fn)
360 elif os.path.isdir(fn):
361 rmtree(fn)
362
363 def test_unoverwritable_fails(self):
364 #create a file clashing with directories in the env dir
365 for paths in self.ENV_SUBDIRS[:3]:
366 fn = os.path.join(self.env_dir, *paths)
367 with open(fn, 'wb') as f:
368 f.write(b'')
369 self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
370 self.clear_directory(self.env_dir)
371
372 def test_upgrade(self):
373 """
374 Test upgrading an existing environment directory.
375 """
376 # See Issue #21643: the loop needs to run twice to ensure
377 # that everything works on the upgrade (the first run just creates
378 # the venv).
379 for upgrade in (False, True):
380 builder = venv.EnvBuilder(upgrade=upgrade)
381 self.run_with_capture(builder.create, self.env_dir)
382 self.isdir(self.bindir)
383 self.isdir(self.include)
384 self.isdir(*self.lib)
385 fn = self.get_env_file(self.bindir, self.exe)
386 if not os.path.exists(fn):
387 # diagnostics for Windows buildbot failures
388 bd = self.get_env_file(self.bindir)
389 print('Contents of %r:' % bd)
390 print(' %r' % os.listdir(bd))
391 self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
392
393 def test_isolation(self):
394 """
395 Test isolation from system site-packages
396 """
397 for ssp, s in ((True, 'true'), (False, 'false')):
398 builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
399 builder.create(self.env_dir)
400 data = self.get_text_file_contents('pyvenv.cfg')
401 self.assertIn('include-system-site-packages = %s\n' % s, data)
402
403 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
404 def test_symlinking(self):
405 """
406 Test symlinking works as expected
407 """
408 for usl in (False, True):
409 builder = venv.EnvBuilder(clear=True, symlinks=usl)
410 builder.create(self.env_dir)
411 fn = self.get_env_file(self.bindir, self.exe)
412 # Don't test when False, because e.g. 'python' is always
413 # symlinked to 'python3.3' in the env, even when symlinking in
414 # general isn't wanted.
415 if usl:
416 if self.cannot_link_exe:
417 # Symlinking is skipped when our executable is already a
418 # special app symlink
419 self.assertFalse(os.path.islink(fn))
420 else:
421 self.assertTrue(os.path.islink(fn))
422
423 # If a venv is created from a source build and that venv is used to
424 # run the test, the pyvenv.cfg in the venv created in the test will
425 # point to the venv being used to run the test, and we lose the link
426 # to the source build - so Python can't initialise properly.
427 @requireVenvCreate
428 def test_executable(self):
429 """
430 Test that the sys.executable value is as expected.
431 """
432 rmtree(self.env_dir)
433 self.run_with_capture(venv.create, self.env_dir)
434 envpy = os.path.join(os.path.realpath(self.env_dir),
435 self.bindir, self.exe)
436 out, err = check_output([envpy, '-c',
437 'import sys; print(sys.executable)'])
438 self.assertEqual(out.strip(), envpy.encode())
439
440 @unittest.skipUnless(can_symlink(), 'Needs symlinks')
441 def test_executable_symlinks(self):
442 """
443 Test that the sys.executable value is as expected.
444 """
445 rmtree(self.env_dir)
446 builder = venv.EnvBuilder(clear=True, symlinks=True)
447 builder.create(self.env_dir)
448 envpy = os.path.join(os.path.realpath(self.env_dir),
449 self.bindir, self.exe)
450 out, err = check_output([envpy, '-c',
451 'import sys; print(sys.executable)'])
452 self.assertEqual(out.strip(), envpy.encode())
453
454 # gh-124651: test quoted strings
455 @unittest.skipIf(os.name == 'nt', 'contains invalid characters on Windows')
456 def test_special_chars_bash(self):
457 """
458 Test that the template strings are quoted properly (bash)
459 """
460 rmtree(self.env_dir)
461 bash = shutil.which('bash')
462 if bash is None:
463 self.skipTest('bash required for this test')
464 env_name = '"\';&&$e|\'"'
465 env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
466 builder = venv.EnvBuilder(clear=True)
467 builder.create(env_dir)
468 activate = os.path.join(env_dir, self.bindir, 'activate')
469 test_script = os.path.join(self.env_dir, 'test_special_chars.sh')
470 with open(test_script, "w") as f:
471 f.write(f'source {shlex.quote(activate)}\n'
472 'python -c \'import sys; print(sys.executable)\'\n'
473 'python -c \'import os; print(os.environ["VIRTUAL_ENV"])\'\n'
474 'deactivate\n')
475 out, err = check_output([bash, test_script])
476 lines = out.splitlines()
477 self.assertTrue(env_name.encode() in lines[0])
478 self.assertEndsWith(lines[1], env_name.encode())
479
480 # gh-124651: test quoted strings
481 @unittest.skipIf(os.name == 'nt', 'contains invalid characters on Windows')
482 def test_special_chars_csh(self):
483 """
484 Test that the template strings are quoted properly (csh)
485 """
486 rmtree(self.env_dir)
487 csh = shutil.which('tcsh') or shutil.which('csh')
488 if csh is None:
489 self.skipTest('csh required for this test')
490 env_name = '"\';&&$e|\'"'
491 env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
492 builder = venv.EnvBuilder(clear=True)
493 builder.create(env_dir)
494 activate = os.path.join(env_dir, self.bindir, 'activate.csh')
495 test_script = os.path.join(self.env_dir, 'test_special_chars.csh')
496 with open(test_script, "w") as f:
497 f.write(f'source {shlex.quote(activate)}\n'
498 'python -c \'import sys; print(sys.executable)\'\n'
499 'python -c \'import os; print(os.environ["VIRTUAL_ENV"])\'\n'
500 'deactivate\n')
501 out, err = check_output([csh, test_script])
502 lines = out.splitlines()
503 self.assertTrue(env_name.encode() in lines[0])
504 self.assertEndsWith(lines[1], env_name.encode())
505
506 # gh-124651: test quoted strings on Windows
507 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
508 def test_special_chars_windows(self):
509 """
510 Test that the template strings are quoted properly on Windows
511 """
512 rmtree(self.env_dir)
513 env_name = "'&&^$e"
514 env_dir = os.path.join(os.path.realpath(self.env_dir), env_name)
515 builder = venv.EnvBuilder(clear=True)
516 builder.create(env_dir)
517 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
518 test_batch = os.path.join(self.env_dir, 'test_special_chars.bat')
519 with open(test_batch, "w") as f:
520 f.write('@echo off\n'
521 f'"{activate}" & '
522 f'{self.exe} -c "import sys; print(sys.executable)" & '
523 f'{self.exe} -c "import os; print(os.environ[\'VIRTUAL_ENV\'])" & '
524 'deactivate')
525 out, err = check_output([test_batch])
526 lines = out.splitlines()
527 self.assertTrue(env_name.encode() in lines[0])
528 self.assertEndsWith(lines[1], env_name.encode())
529
530 @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
531 def test_unicode_in_batch_file(self):
532 """
533 Test handling of Unicode paths
534 """
535 rmtree(self.env_dir)
536 env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
537 builder = venv.EnvBuilder(clear=True)
538 builder.create(env_dir)
539 activate = os.path.join(env_dir, self.bindir, 'activate.bat')
540 envpy = os.path.join(env_dir, self.bindir, self.exe)
541 out, err = check_output(
542 [activate, '&', self.exe, '-c', 'print(0)'],
543 encoding='oem',
544 )
545 self.assertEqual(out.strip(), '0')
546
547 @requireVenvCreate
548 def test_multiprocessing(self):
549 """
550 Test that the multiprocessing is able to spawn.
551 """
552 # bpo-36342: Instantiation of a Pool object imports the
553 # multiprocessing.synchronize module. Skip the test if this module
554 # cannot be imported.
555 skip_if_broken_multiprocessing_synchronize()
556
557 rmtree(self.env_dir)
558 self.run_with_capture(venv.create, self.env_dir)
559 envpy = os.path.join(os.path.realpath(self.env_dir),
560 self.bindir, self.exe)
561 out, err = check_output([envpy, '-c',
562 'from multiprocessing import Pool; '
563 'pool = Pool(1); '
564 'print(pool.apply_async("Python".lower).get(3)); '
565 'pool.terminate()'])
566 self.assertEqual(out.strip(), "python".encode())
567
568 @requireVenvCreate
569 def test_multiprocessing_recursion(self):
570 """
571 Test that the multiprocessing is able to spawn itself
572 """
573 skip_if_broken_multiprocessing_synchronize()
574
575 rmtree(self.env_dir)
576 self.run_with_capture(venv.create, self.env_dir)
577 envpy = os.path.join(os.path.realpath(self.env_dir),
578 self.bindir, self.exe)
579 script = os.path.join(TEST_HOME_DIR, '_test_venv_multiprocessing.py')
580 subprocess.check_call([envpy, "-I", script])
581
582 @unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
583 def test_deactivate_with_strict_bash_opts(self):
584 bash = shutil.which("bash")
585 if bash is None:
586 self.skipTest("bash required for this test")
587 rmtree(self.env_dir)
588 builder = venv.EnvBuilder(clear=True)
589 builder.create(self.env_dir)
590 activate = os.path.join(self.env_dir, self.bindir, "activate")
591 test_script = os.path.join(self.env_dir, "test_strict.sh")
592 with open(test_script, "w") as f:
593 f.write("set -euo pipefail\n"
594 f"source {activate}\n"
595 "deactivate\n")
596 out, err = check_output([bash, test_script])
597 self.assertEqual(out, "".encode())
598 self.assertEqual(err, "".encode())
599
600
601 @unittest.skipUnless(sys.platform == 'darwin', 'only relevant on macOS')
602 def test_macos_env(self):
603 rmtree(self.env_dir)
604 builder = venv.EnvBuilder()
605 builder.create(self.env_dir)
606
607 envpy = os.path.join(os.path.realpath(self.env_dir),
608 self.bindir, self.exe)
609 out, err = check_output([envpy, '-c',
610 'import os; print("__PYVENV_LAUNCHER__" in os.environ)'])
611 self.assertEqual(out.strip(), 'False'.encode())
612
613 def test_pathsep_error(self):
614 """
615 Test that venv creation fails when the target directory contains
616 the path separator.
617 """
618 rmtree(self.env_dir)
619 bad_itempath = self.env_dir + os.pathsep
620 self.assertRaises(ValueError, venv.create, bad_itempath)
621 self.assertRaises(ValueError, venv.create, pathlib.Path(bad_itempath))
622
623 @unittest.skipIf(os.name == 'nt', 'not relevant on Windows')
624 @requireVenvCreate
625 @impl_detail("pypy does not add zip to sys.path unless it exists", pypy=False)
626 def test_zippath_from_non_installed_posix(self):
627 """
628 Test that when create venv from non-installed python, the zip path
629 value is as expected.
630 """
631 rmtree(self.env_dir)
632 # First try to create a non-installed python. It's not a real full
633 # functional non-installed python, but enough for this test.
634 platlibdir = sys.platlibdir
635 non_installed_dir = os.path.realpath(tempfile.mkdtemp())
636 self.addCleanup(rmtree, non_installed_dir)
637 bindir = os.path.join(non_installed_dir, self.bindir)
638 os.mkdir(bindir)
639 shutil.copy2(sys.executable, bindir)
640 # PYPY: also copy the shared library
641 old_bindir = os.path.split(sys.executable)[0]
642 for f in os.listdir(old_bindir):
643 if f.startswith('libpypy'):
644 shutil.copy2(os.path.join(old_bindir, f), bindir)
645 # end of PYPY
646 libdir = os.path.join(non_installed_dir, platlibdir, self.lib[1])
647 os.makedirs(libdir)
648 landmark = os.path.join(libdir, "os.py")
649 stdlib_zip = "pypy%d%d.zip" % sys.version_info[:2]
650 zip_landmark = os.path.join(non_installed_dir,
651 platlibdir,
652 stdlib_zip)
653 additional_pythonpath_for_non_installed = []
654
655 # Copy stdlib files to the non-installed python so venv can
656 # correctly calculate the prefix.
657 for eachpath in sys.path:
658 if eachpath.endswith(".zip"):
659 if os.path.isfile(eachpath):
660 shutil.copyfile(
661 eachpath,
662 os.path.join(non_installed_dir, platlibdir))
663 elif (os.path.isfile(os.path.join(eachpath, "os.py")) or
664 # PYPY: also copy lib_pypy when testing a source build
665 os.path.isfile(os.path.join(eachpath, "_pypy_generic_alias.py"))) :
666 names = os.listdir(eachpath)
667 ignored_names = copy_python_src_ignore(eachpath, names)
668 for name in names:
669 if name in ignored_names:
670 continue
671 if name == "site-packages":
672 continue
673 fn = os.path.join(eachpath, name)
674 if os.path.isfile(fn):
675 shutil.copy(fn, libdir)
676 elif os.path.isdir(fn):
677 shutil.copytree(fn, os.path.join(libdir, name),
678 ignore=copy_python_src_ignore)
679 else:
680 additional_pythonpath_for_non_installed.append(
681 eachpath)
682 cmd = [os.path.join(non_installed_dir, self.bindir, self.exe),
683 "-m",
684 "venv",
685 "--without-pip",
686 self.env_dir]
687 # Our fake non-installed python is not fully functional because
688 # it cannot find the extensions. Set PYTHONPATH so it can run the
689 # venv module correctly.
690 pythonpath = os.pathsep.join(
691 additional_pythonpath_for_non_installed)
692 # For python built with shared enabled. We need to set
693 # LD_LIBRARY_PATH so the non-installed python can find and link
694 # libpython.so
695 ld_library_path = sysconfig.get_config_var("LIBDIR")
696 if not ld_library_path or sysconfig.is_python_build():
697 ld_library_path = os.path.abspath(os.path.dirname(sys.executable))
698 if sys.platform == 'darwin':
699 ld_library_path_env = "DYLD_LIBRARY_PATH"
700 else:
701 ld_library_path_env = "LD_LIBRARY_PATH"
702 subprocess.check_call(cmd,
703 env={"PYTHONPATH": pythonpath,
704 ld_library_path_env: ld_library_path})
705 envpy = os.path.join(self.env_dir, self.bindir, self.exe)
706 # Now check the venv created from the non-installed python has
707 # correct zip path in pythonpath.
708 cmd = [envpy, '-S', '-c', 'import sys; print(sys.path)']
709 out, err = check_output(cmd)
710 import pdb;pdb.set_trace()
711 self.assertTrue(zip_landmark.encode() in out)
712
713 @requireVenvCreate
714 class EnsurePipTest(BaseTest):
715 """Test venv module installation of pip."""
716 def assert_pip_not_installed(self):
717 envpy = os.path.join(os.path.realpath(self.env_dir),
718 self.bindir, self.exe)
719 out, err = check_output([envpy, '-c',
720 'try:\n import pip\nexcept ImportError:\n print("OK")'])
721 # We force everything to text, so unittest gives the detailed diff
722 # if we get unexpected results
723 err = err.decode("latin-1") # Force to text, prevent decoding errors
724 self.assertEqual(err, "")
725 out = out.decode("latin-1") # Force to text, prevent decoding errors
726 self.assertEqual(out.strip(), "OK")
727
728
729 def test_no_pip_by_default(self):
730 rmtree(self.env_dir)
731 self.run_with_capture(venv.create, self.env_dir)
732 self.assert_pip_not_installed()
733
734 def test_explicit_no_pip(self):
735 rmtree(self.env_dir)
736 self.run_with_capture(venv.create, self.env_dir, with_pip=False)
737 self.assert_pip_not_installed()
738
739 def test_devnull(self):
740 # Fix for issue #20053 uses os.devnull to force a config file to
741 # appear empty. However http://bugs.python.org/issue20541 means
742 # that doesn't currently work properly on Windows. Once that is
743 # fixed, the "win_location" part of test_with_pip should be restored
744 with open(os.devnull, "rb") as f:
745 self.assertEqual(f.read(), b"")
746
747 self.assertTrue(os.path.exists(os.devnull))
748
749 def do_test_with_pip(self, system_site_packages):
750 rmtree(self.env_dir)
751 with EnvironmentVarGuard() as envvars:
752 # pip's cross-version compatibility may trigger deprecation
753 # warnings in current versions of Python. Ensure related
754 # environment settings don't cause venv to fail.
755 envvars["PYTHONWARNINGS"] = "ignore"
756 # ensurepip is different enough from a normal pip invocation
757 # that we want to ensure it ignores the normal pip environment
758 # variable settings. We set PIP_NO_INSTALL here specifically
759 # to check that ensurepip (and hence venv) ignores it.
760 # See http://bugs.python.org/issue19734
761 envvars["PIP_NO_INSTALL"] = "1"
762 # Also check that we ignore the pip configuration file
763 # See http://bugs.python.org/issue20053
764 with tempfile.TemporaryDirectory() as home_dir:
765 envvars["HOME"] = home_dir
766 bad_config = "[global]\nno-install=1"
767 # Write to both config file names on all platforms to reduce
768 # cross-platform variation in test code behaviour
769 win_location = ("pip", "pip.ini")
770 posix_location = (".pip", "pip.conf")
771 # Skips win_location due to http://bugs.python.org/issue20541
772 for dirname, fname in (posix_location,):
773 dirpath = os.path.join(home_dir, dirname)
774 os.mkdir(dirpath)
775 fpath = os.path.join(dirpath, fname)
776 with open(fpath, 'w') as f:
777 f.write(bad_config)
778
779 # Actually run the create command with all that unhelpful
780 # config in place to ensure we ignore it
781 with self.nicer_error():
782 self.run_with_capture(venv.create, self.env_dir,
783 system_site_packages=system_site_packages,
784 with_pip=True)
785 # Ensure pip is available in the virtual environment
786 envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
787 # Ignore DeprecationWarning since pip code is not part of Python
788 out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning',
789 '-W', 'ignore::ImportWarning', '-I',
790 '-m', 'pip', '--version'])
791 # We force everything to text, so unittest gives the detailed diff
792 # if we get unexpected results
793 err = err.decode("latin-1") # Force to text, prevent decoding errors
794 self.assertEqual(err, "")
795 out = out.decode("latin-1") # Force to text, prevent decoding errors
796 expected_version = "pip {}".format(ensurepip.version())
797 self.assertEqual(out[:len(expected_version)], expected_version)
798 env_dir = os.fsencode(self.env_dir).decode("latin-1")
799 self.assertIn(env_dir, out)
800
801 # http://bugs.python.org/issue19728
802 # Check the private uninstall command provided for the Windows
803 # installers works (at least in a virtual environment)
804 with EnvironmentVarGuard() as envvars:
805 with self.nicer_error():
806 # It seems ensurepip._uninstall calls subprocesses which do not
807 # inherit the interpreter settings.
808 envvars["PYTHONWARNINGS"] = "ignore"
809 out, err = check_output([envpy,
810 '-W', 'ignore::DeprecationWarning',
811 '-W', 'ignore::ImportWarning', '-I',
812 '-m', 'ensurepip._uninstall'])
813 # We force everything to text, so unittest gives the detailed diff
814 # if we get unexpected results
815 err = err.decode("latin-1") # Force to text, prevent decoding errors
816 # Ignore the warning:
817 # "The directory '$HOME/.cache/pip/http' or its parent directory
818 # is not owned by the current user and the cache has been disabled.
819 # Please check the permissions and owner of that directory. If
820 # executing pip with sudo, you may want sudo's -H flag."
821 # where $HOME is replaced by the HOME environment variable.
822 err = re.sub("^(WARNING: )?The directory .* or its parent directory "
823 "is not owned or is not writable by the current user.*$", "",
824 err, flags=re.MULTILINE)
825 self.assertEqual(err.rstrip(), "")
826 # Being fairly specific regarding the expected behaviour for the
827 # initial bundling phase in Python 3.4. If the output changes in
828 # future pip versions, this test can likely be relaxed further.
829 out = out.decode("latin-1") # Force to text, prevent decoding errors
830 self.assertIn("Successfully uninstalled pip", out)
831 self.assertIn("Successfully uninstalled setuptools", out)
832 # Check pip is now gone from the virtual environment. This only
833 # applies in the system_site_packages=False case, because in the
834 # other case, pip may still be available in the system site-packages
835 if not system_site_packages:
836 self.assert_pip_not_installed()
837
838 @contextlib.contextmanager
839 def nicer_error(self):
840 """
841 Capture output from a failed subprocess for easier debugging.
842
843 The output this handler produces can be a little hard to read,
844 but at least it has all the details.
845 """
846 try:
847 yield
848 except subprocess.CalledProcessError as exc:
849 out = (exc.output or b'').decode(errors="replace")
850 err = (exc.stderr or b'').decode(errors="replace")
851 self.fail(
852 f"{exc}\n\n"
853 f"**Subprocess Output**\n{out}\n\n"
854 f"**Subprocess Error**\n{err}"
855 )
856
857 @requires_venv_with_pip()
858 @requires_resource('cpu')
859 def test_with_pip(self):
860 self.do_test_with_pip(False)
861 self.do_test_with_pip(True)
862
863
864 if __name__ == "__main__":
865 unittest.main()