Home | History | Annotate | Download | only in test
      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 ensurepip
      9 import os
     10 import os.path
     11 import re
     12 import struct
     13 import subprocess
     14 import sys
     15 import tempfile
     16 from test.support import (captured_stdout, captured_stderr, requires_zlib,
     17                           can_symlink, EnvironmentVarGuard, rmtree)
     18 import threading
     19 import unittest
     20 import venv
     21 
     22 try:
     23     import ctypes
     24 except ImportError:
     25     ctypes = None
     26 
     27 skipInVenv = unittest.skipIf(sys.prefix != sys.base_prefix,
     28                              'Test not appropriate in a venv')
     29 
     30 def check_output(cmd, encoding=None):
     31     p = subprocess.Popen(cmd,
     32         stdout=subprocess.PIPE,
     33         stderr=subprocess.PIPE,
     34         encoding=encoding)
     35     out, err = p.communicate()
     36     if p.returncode:
     37         raise subprocess.CalledProcessError(
     38             p.returncode, cmd, out, err)
     39     return out, err
     40 
     41 class BaseTest(unittest.TestCase):
     42     """Base class for venv tests."""
     43     maxDiff = 80 * 50
     44 
     45     def setUp(self):
     46         self.env_dir = os.path.realpath(tempfile.mkdtemp())
     47         if os.name == 'nt':
     48             self.bindir = 'Scripts'
     49             self.lib = ('Lib',)
     50             self.include = 'Include'
     51         else:
     52             self.bindir = 'bin'
     53             self.lib = ('lib', 'python%d.%d' % sys.version_info[:2])
     54             self.include = 'include'
     55         executable = getattr(sys, '_base_executable', sys.executable)
     56         self.exe = os.path.split(executable)[-1]
     57 
     58     def tearDown(self):
     59         rmtree(self.env_dir)
     60 
     61     def run_with_capture(self, func, *args, **kwargs):
     62         with captured_stdout() as output:
     63             with captured_stderr() as error:
     64                 func(*args, **kwargs)
     65         return output.getvalue(), error.getvalue()
     66 
     67     def get_env_file(self, *args):
     68         return os.path.join(self.env_dir, *args)
     69 
     70     def get_text_file_contents(self, *args):
     71         with open(self.get_env_file(*args), 'r') as f:
     72             result = f.read()
     73         return result
     74 
     75 class BasicTest(BaseTest):
     76     """Test venv module functionality."""
     77 
     78     def isdir(self, *args):
     79         fn = self.get_env_file(*args)
     80         self.assertTrue(os.path.isdir(fn))
     81 
     82     def test_defaults(self):
     83         """
     84         Test the create function with default arguments.
     85         """
     86         rmtree(self.env_dir)
     87         self.run_with_capture(venv.create, self.env_dir)
     88         self.isdir(self.bindir)
     89         self.isdir(self.include)
     90         self.isdir(*self.lib)
     91         # Issue 21197
     92         p = self.get_env_file('lib64')
     93         conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
     94                       (sys.platform != 'darwin'))
     95         if conditions:
     96             self.assertTrue(os.path.islink(p))
     97         else:
     98             self.assertFalse(os.path.exists(p))
     99         data = self.get_text_file_contents('pyvenv.cfg')
    100         executable = getattr(sys, '_base_executable', sys.executable)
    101         path = os.path.dirname(executable)
    102         self.assertIn('home = %s' % path, data)
    103         fn = self.get_env_file(self.bindir, self.exe)
    104         if not os.path.exists(fn):  # diagnostics for Windows buildbot failures
    105             bd = self.get_env_file(self.bindir)
    106             print('Contents of %r:' % bd)
    107             print('    %r' % os.listdir(bd))
    108         self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
    109 
    110     def test_prompt(self):
    111         env_name = os.path.split(self.env_dir)[1]
    112 
    113         builder = venv.EnvBuilder()
    114         context = builder.ensure_directories(self.env_dir)
    115         self.assertEqual(context.prompt, '(%s) ' % env_name)
    116 
    117         builder = venv.EnvBuilder(prompt='My prompt')
    118         context = builder.ensure_directories(self.env_dir)
    119         self.assertEqual(context.prompt, '(My prompt) ')
    120 
    121     @skipInVenv
    122     def test_prefixes(self):
    123         """
    124         Test that the prefix values are as expected.
    125         """
    126         #check our prefixes
    127         self.assertEqual(sys.base_prefix, sys.prefix)
    128         self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)
    129 
    130         # check a venv's prefixes
    131         rmtree(self.env_dir)
    132         self.run_with_capture(venv.create, self.env_dir)
    133         envpy = os.path.join(self.env_dir, self.bindir, self.exe)
    134         cmd = [envpy, '-c', None]
    135         for prefix, expected in (
    136             ('prefix', self.env_dir),
    137             ('prefix', self.env_dir),
    138             ('base_prefix', sys.prefix),
    139             ('base_exec_prefix', sys.exec_prefix)):
    140             cmd[2] = 'import sys; print(sys.%s)' % prefix
    141             out, err = check_output(cmd)
    142             self.assertEqual(out.strip(), expected.encode())
    143 
    144     if sys.platform == 'win32':
    145         ENV_SUBDIRS = (
    146             ('Scripts',),
    147             ('Include',),
    148             ('Lib',),
    149             ('Lib', 'site-packages'),
    150         )
    151     else:
    152         ENV_SUBDIRS = (
    153             ('bin',),
    154             ('include',),
    155             ('lib',),
    156             ('lib', 'python%d.%d' % sys.version_info[:2]),
    157             ('lib', 'python%d.%d' % sys.version_info[:2], 'site-packages'),
    158         )
    159 
    160     def create_contents(self, paths, filename):
    161         """
    162         Create some files in the environment which are unrelated
    163         to the virtual environment.
    164         """
    165         for subdirs in paths:
    166             d = os.path.join(self.env_dir, *subdirs)
    167             os.mkdir(d)
    168             fn = os.path.join(d, filename)
    169             with open(fn, 'wb') as f:
    170                 f.write(b'Still here?')
    171 
    172     def test_overwrite_existing(self):
    173         """
    174         Test creating environment in an existing directory.
    175         """
    176         self.create_contents(self.ENV_SUBDIRS, 'foo')
    177         venv.create(self.env_dir)
    178         for subdirs in self.ENV_SUBDIRS:
    179             fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
    180             self.assertTrue(os.path.exists(fn))
    181             with open(fn, 'rb') as f:
    182                 self.assertEqual(f.read(), b'Still here?')
    183 
    184         builder = venv.EnvBuilder(clear=True)
    185         builder.create(self.env_dir)
    186         for subdirs in self.ENV_SUBDIRS:
    187             fn = os.path.join(self.env_dir, *(subdirs + ('foo',)))
    188             self.assertFalse(os.path.exists(fn))
    189 
    190     def clear_directory(self, path):
    191         for fn in os.listdir(path):
    192             fn = os.path.join(path, fn)
    193             if os.path.islink(fn) or os.path.isfile(fn):
    194                 os.remove(fn)
    195             elif os.path.isdir(fn):
    196                 rmtree(fn)
    197 
    198     def test_unoverwritable_fails(self):
    199         #create a file clashing with directories in the env dir
    200         for paths in self.ENV_SUBDIRS[:3]:
    201             fn = os.path.join(self.env_dir, *paths)
    202             with open(fn, 'wb') as f:
    203                 f.write(b'')
    204             self.assertRaises((ValueError, OSError), venv.create, self.env_dir)
    205             self.clear_directory(self.env_dir)
    206 
    207     def test_upgrade(self):
    208         """
    209         Test upgrading an existing environment directory.
    210         """
    211         # See Issue #21643: the loop needs to run twice to ensure
    212         # that everything works on the upgrade (the first run just creates
    213         # the venv).
    214         for upgrade in (False, True):
    215             builder = venv.EnvBuilder(upgrade=upgrade)
    216             self.run_with_capture(builder.create, self.env_dir)
    217             self.isdir(self.bindir)
    218             self.isdir(self.include)
    219             self.isdir(*self.lib)
    220             fn = self.get_env_file(self.bindir, self.exe)
    221             if not os.path.exists(fn):
    222                 # diagnostics for Windows buildbot failures
    223                 bd = self.get_env_file(self.bindir)
    224                 print('Contents of %r:' % bd)
    225                 print('    %r' % os.listdir(bd))
    226             self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
    227 
    228     def test_isolation(self):
    229         """
    230         Test isolation from system site-packages
    231         """
    232         for ssp, s in ((True, 'true'), (False, 'false')):
    233             builder = venv.EnvBuilder(clear=True, system_site_packages=ssp)
    234             builder.create(self.env_dir)
    235             data = self.get_text_file_contents('pyvenv.cfg')
    236             self.assertIn('include-system-site-packages = %s\n' % s, data)
    237 
    238     @unittest.skipUnless(can_symlink(), 'Needs symlinks')
    239     def test_symlinking(self):
    240         """
    241         Test symlinking works as expected
    242         """
    243         for usl in (False, True):
    244             builder = venv.EnvBuilder(clear=True, symlinks=usl)
    245             builder.create(self.env_dir)
    246             fn = self.get_env_file(self.bindir, self.exe)
    247             # Don't test when False, because e.g. 'python' is always
    248             # symlinked to 'python3.3' in the env, even when symlinking in
    249             # general isn't wanted.
    250             if usl:
    251                 self.assertTrue(os.path.islink(fn))
    252 
    253     # If a venv is created from a source build and that venv is used to
    254     # run the test, the pyvenv.cfg in the venv created in the test will
    255     # point to the venv being used to run the test, and we lose the link
    256     # to the source build - so Python can't initialise properly.
    257     @skipInVenv
    258     def test_executable(self):
    259         """
    260         Test that the sys.executable value is as expected.
    261         """
    262         rmtree(self.env_dir)
    263         self.run_with_capture(venv.create, self.env_dir)
    264         envpy = os.path.join(os.path.realpath(self.env_dir),
    265                              self.bindir, self.exe)
    266         out, err = check_output([envpy, '-c',
    267             'import sys; print(sys.executable)'])
    268         self.assertEqual(out.strip(), envpy.encode())
    269 
    270     @unittest.skipUnless(can_symlink(), 'Needs symlinks')
    271     def test_executable_symlinks(self):
    272         """
    273         Test that the sys.executable value is as expected.
    274         """
    275         rmtree(self.env_dir)
    276         builder = venv.EnvBuilder(clear=True, symlinks=True)
    277         builder.create(self.env_dir)
    278         envpy = os.path.join(os.path.realpath(self.env_dir),
    279                              self.bindir, self.exe)
    280         out, err = check_output([envpy, '-c',
    281             'import sys; print(sys.executable)'])
    282         self.assertEqual(out.strip(), envpy.encode())
    283 
    284     @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows')
    285     def test_unicode_in_batch_file(self):
    286         """
    287         Test handling of Unicode paths
    288         """
    289         rmtree(self.env_dir)
    290         env_dir = os.path.join(os.path.realpath(self.env_dir), '')
    291         builder = venv.EnvBuilder(clear=True)
    292         builder.create(env_dir)
    293         activate = os.path.join(env_dir, self.bindir, 'activate.bat')
    294         envpy = os.path.join(env_dir, self.bindir, self.exe)
    295         out, err = check_output(
    296             [activate, '&', self.exe, '-c', 'print(0)'],
    297             encoding='oem',
    298         )
    299         self.assertEqual(out.strip(), '0')
    300 
    301     def test_multiprocessing(self):
    302         """
    303         Test that the multiprocessing is able to spawn.
    304         """
    305         rmtree(self.env_dir)
    306         self.run_with_capture(venv.create, self.env_dir)
    307         envpy = os.path.join(os.path.realpath(self.env_dir),
    308                              self.bindir, self.exe)
    309         out, err = check_output([envpy, '-c',
    310             'from multiprocessing import Pool; ' +
    311             'print(Pool(1).apply_async("Python".lower).get(3))'])
    312         self.assertEqual(out.strip(), "python".encode())
    313 
    314 @skipInVenv
    315 class EnsurePipTest(BaseTest):
    316     """Test venv module installation of pip."""
    317     def assert_pip_not_installed(self):
    318         envpy = os.path.join(os.path.realpath(self.env_dir),
    319                              self.bindir, self.exe)
    320         out, err = check_output([envpy, '-c',
    321             'try:\n import pip\nexcept ImportError:\n print("OK")'])
    322         # We force everything to text, so unittest gives the detailed diff
    323         # if we get unexpected results
    324         err = err.decode("latin-1") # Force to text, prevent decoding errors
    325         self.assertEqual(err, "")
    326         out = out.decode("latin-1") # Force to text, prevent decoding errors
    327         self.assertEqual(out.strip(), "OK")
    328 
    329 
    330     def test_no_pip_by_default(self):
    331         rmtree(self.env_dir)
    332         self.run_with_capture(venv.create, self.env_dir)
    333         self.assert_pip_not_installed()
    334 
    335     def test_explicit_no_pip(self):
    336         rmtree(self.env_dir)
    337         self.run_with_capture(venv.create, self.env_dir, with_pip=False)
    338         self.assert_pip_not_installed()
    339 
    340     def test_devnull(self):
    341         # Fix for issue #20053 uses os.devnull to force a config file to
    342         # appear empty. However http://bugs.python.org/issue20541 means
    343         # that doesn't currently work properly on Windows. Once that is
    344         # fixed, the "win_location" part of test_with_pip should be restored
    345         with open(os.devnull, "rb") as f:
    346             self.assertEqual(f.read(), b"")
    347 
    348         # Issue #20541: os.path.exists('nul') is False on Windows
    349         if os.devnull.lower() == 'nul':
    350             self.assertFalse(os.path.exists(os.devnull))
    351         else:
    352             self.assertTrue(os.path.exists(os.devnull))
    353 
    354     def do_test_with_pip(self, system_site_packages):
    355         rmtree(self.env_dir)
    356         with EnvironmentVarGuard() as envvars:
    357             # pip's cross-version compatibility may trigger deprecation
    358             # warnings in current versions of Python. Ensure related
    359             # environment settings don't cause venv to fail.
    360             envvars["PYTHONWARNINGS"] = "e"
    361             # ensurepip is different enough from a normal pip invocation
    362             # that we want to ensure it ignores the normal pip environment
    363             # variable settings. We set PIP_NO_INSTALL here specifically
    364             # to check that ensurepip (and hence venv) ignores it.
    365             # See http://bugs.python.org/issue19734
    366             envvars["PIP_NO_INSTALL"] = "1"
    367             # Also check that we ignore the pip configuration file
    368             # See http://bugs.python.org/issue20053
    369             with tempfile.TemporaryDirectory() as home_dir:
    370                 envvars["HOME"] = home_dir
    371                 bad_config = "[global]\nno-install=1"
    372                 # Write to both config file names on all platforms to reduce
    373                 # cross-platform variation in test code behaviour
    374                 win_location = ("pip", "pip.ini")
    375                 posix_location = (".pip", "pip.conf")
    376                 # Skips win_location due to http://bugs.python.org/issue20541
    377                 for dirname, fname in (posix_location,):
    378                     dirpath = os.path.join(home_dir, dirname)
    379                     os.mkdir(dirpath)
    380                     fpath = os.path.join(dirpath, fname)
    381                     with open(fpath, 'w') as f:
    382                         f.write(bad_config)
    383 
    384                 # Actually run the create command with all that unhelpful
    385                 # config in place to ensure we ignore it
    386                 try:
    387                     self.run_with_capture(venv.create, self.env_dir,
    388                                           system_site_packages=system_site_packages,
    389                                           with_pip=True)
    390                 except subprocess.CalledProcessError as exc:
    391                     # The output this produces can be a little hard to read,
    392                     # but at least it has all the details
    393                     details = exc.output.decode(errors="replace")
    394                     msg = "{}\n\n**Subprocess Output**\n{}"
    395                     self.fail(msg.format(exc, details))
    396         # Ensure pip is available in the virtual environment
    397         envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
    398         # Ignore DeprecationWarning since pip code is not part of Python
    399         out, err = check_output([envpy, '-W', 'ignore::DeprecationWarning', '-I',
    400                '-m', 'pip', '--version'])
    401         # We force everything to text, so unittest gives the detailed diff
    402         # if we get unexpected results
    403         err = err.decode("latin-1") # Force to text, prevent decoding errors
    404         self.assertEqual(err, "")
    405         out = out.decode("latin-1") # Force to text, prevent decoding errors
    406         expected_version = "pip {}".format(ensurepip.version())
    407         self.assertEqual(out[:len(expected_version)], expected_version)
    408         env_dir = os.fsencode(self.env_dir).decode("latin-1")
    409         self.assertIn(env_dir, out)
    410 
    411         # http://bugs.python.org/issue19728
    412         # Check the private uninstall command provided for the Windows
    413         # installers works (at least in a virtual environment)
    414         with EnvironmentVarGuard() as envvars:
    415             out, err = check_output([envpy,
    416                 '-W', 'ignore::DeprecationWarning', '-I',
    417                 '-m', 'ensurepip._uninstall'])
    418         # We force everything to text, so unittest gives the detailed diff
    419         # if we get unexpected results
    420         err = err.decode("latin-1") # Force to text, prevent decoding errors
    421         # Ignore the warning:
    422         #   "The directory '$HOME/.cache/pip/http' or its parent directory
    423         #    is not owned by the current user and the cache has been disabled.
    424         #    Please check the permissions and owner of that directory. If
    425         #    executing pip with sudo, you may want sudo's -H flag."
    426         # where $HOME is replaced by the HOME environment variable.
    427         err = re.sub("^The directory .* or its parent directory is not owned "
    428                      "by the current user .*$", "", err, flags=re.MULTILINE)
    429         self.assertEqual(err.rstrip(), "")
    430         # Being fairly specific regarding the expected behaviour for the
    431         # initial bundling phase in Python 3.4. If the output changes in
    432         # future pip versions, this test can likely be relaxed further.
    433         out = out.decode("latin-1") # Force to text, prevent decoding errors
    434         self.assertIn("Successfully uninstalled pip", out)
    435         self.assertIn("Successfully uninstalled setuptools", out)
    436         # Check pip is now gone from the virtual environment. This only
    437         # applies in the system_site_packages=False case, because in the
    438         # other case, pip may still be available in the system site-packages
    439         if not system_site_packages:
    440             self.assert_pip_not_installed()
    441 
    442     # Issue #26610: pip/pep425tags.py requires ctypes
    443     @unittest.skipUnless(ctypes, 'pip requires ctypes')
    444     @requires_zlib
    445     def test_with_pip(self):
    446         self.do_test_with_pip(False)
    447         self.do_test_with_pip(True)
    448 
    449 if __name__ == "__main__":
    450     unittest.main()
    451