test_venv.py 31 KB

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