Exemple #1
0
 def clear_directory(self, path):
     for fn in os.listdir(path):
         fn = os.path.join(path, fn)
         if os.path.islink(fn) or os.path.isfile(fn):
             os.remove(fn)
         elif os.path.isdir(fn):
             rmtree(fn)
Exemple #2
0
 def restore_files(self, saved_value):
     fn = support.TESTFN
     if fn not in saved_value and (fn + '/') not in saved_value:
         if os.path.isfile(fn):
             support.unlink(fn)
         elif os.path.isdir(fn):
             support.rmtree(fn)
Exemple #3
0
 def test_defaults(self):
     """
     Test the create function with default arguments.
     """
     rmtree(self.env_dir)
     self.run_with_capture(venv.create, self.env_dir)
     self.isdir(self.bindir)
     self.isdir(self.include)
     self.isdir(*self.lib)
     # Issue 21197
     p = self.get_env_file('lib64')
     conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and
                   (sys.platform != 'darwin'))
     if conditions:
         self.assertTrue(os.path.islink(p))
     else:
         self.assertFalse(os.path.exists(p))
     data = self.get_text_file_contents('pyvenv.cfg')
     if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'
                                      in os.environ):
         executable =  os.environ['__PYVENV_LAUNCHER__']
     else:
         executable = sys.executable
     path = os.path.dirname(executable)
     self.assertIn('home = %s' % path, data)
     fn = self.get_env_file(self.bindir, self.exe)
     if not os.path.exists(fn):  # diagnostics for Windows buildbot failures
         bd = self.get_env_file(self.bindir)
         print('Contents of %r:' % bd)
         print('    %r' % os.listdir(bd))
     self.assertTrue(os.path.exists(fn), 'File %r should exist.' % fn)
Exemple #4
0
    def test_collision_with_existing_directory(self):
        # _mkstemp_inner tries another name when a directory with
        # the chosen name already exists
        container_dir = tempfile.mkdtemp()
        try:
            def mock_get_candidate_names():
                return iter(['aaa', 'aaa', 'bbb'])
            with support.swap_attr(tempfile,
                                   '_get_candidate_names',
                                   mock_get_candidate_names):
                dir = tempfile.mkdtemp(dir=container_dir)
                self.assertTrue(dir.endswith('aaa'))

                flags = tempfile._bin_openflags
                (fd, name) = tempfile._mkstemp_inner(container_dir,
                                                     tempfile.template,
                                                     '',
                                                     flags)
                try:
                    self.assertTrue(name.endswith('bbb'))
                finally:
                    os.close(fd)
                    os.unlink(name)
        finally:
            support.rmtree(container_dir)
Exemple #5
0
 def test_relative_imports_on_plain_module(self):
     # Validates running a plain module. See bpo32691
     self.module_name = 't_main'
     support.rmtree(self.module_name)
     main_file = self.module_name + '/runme.py'
     init_file = self.module_name + '/__init__.py'
     module_file = self.module_name + '/module.py'
     self.addCleanup(support.rmtree, self.module_name)
     os.mkdir(self.module_name)
     with open(init_file, 'w') as f:
         f.write(textwrap.dedent("""
             top_var = "VAR from top"
         """))
     with open(main_file, 'w') as f:
         f.write(textwrap.dedent("""
             from . import module
             pass # We'll stop here and print the vars
         """))
     with open(module_file, 'w') as f:
         f.write(textwrap.dedent("""
             var = "VAR from module"
         """))
     commands = """
         b 3
         c
         p module.var
         quit
     """
     stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
     self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
Exemple #6
0
def remove_files(name):
    for f in (name + ".py",
              name + ".pyc",
              name + ".pyw",
              name + "$py.class"):
        unlink(f)
    rmtree('__pycache__')
def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, "tempdir", dir):
            yield
    finally:
        support.rmtree(dir)
Exemple #8
0
    def test_getcwd_long_pathnames(self):
        dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
        curdir = os.getcwd()
        base_path = os.path.abspath(support.TESTFN) + '.getcwd'

        try:
            os.mkdir(base_path)
            os.chdir(base_path)
        except:
            #  Just returning nothing instead of the SkipTest exception, because
            #  the test results in Error in that case.  Is that ok?
            #  raise unittest.SkipTest("cannot create directory for testing")
            return

            def _create_and_do_getcwd(dirname, current_path_length = 0):
                try:
                    os.mkdir(dirname)
                except:
                    raise unittest.SkipTest("mkdir cannot create directory sufficiently deep for getcwd test")

                os.chdir(dirname)
                try:
                    os.getcwd()
                    if current_path_length < 1027:
                        _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
                finally:
                    os.chdir('..')
                    os.rmdir(dirname)

            _create_and_do_getcwd(dirname)

        finally:
            os.chdir(curdir)
            support.rmtree(base_path)
Exemple #9
0
 def test_mkdir_dir_fd(self):
     f = posix.open(posix.getcwd(), posix.O_RDONLY)
     try:
         posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
         posix.stat(support.TESTFN + 'dir') # should not raise exception
     finally:
         posix.close(f)
         support.rmtree(support.TESTFN + 'dir')
 def newdirinpath(dir):
     os.mkdir(dir)
     sys.path.insert(0, dir)
     try:
         yield
     finally:
         sys.path.pop(0)
         rmtree(dir)
Exemple #11
0
 def tearDown(self):
     sys.path[:] = self.sys_path
     if self.orig_module is not None:
         sys.modules[self.module_name] = self.orig_module
     else:
         unload(self.module_name)
     unlink(self.file_name)
     unlink(self.compiled_name)
     rmtree(self.dir_name)
Exemple #12
0
def create_modules(*names):
    """Temporarily create each named module with an attribute (named 'attr')
    that contains the name passed into the context manager that caused the
    creation of the module.

    All files are created in a temporary directory returned by
    tempfile.mkdtemp(). This directory is inserted at the beginning of
    sys.path. When the context manager exits all created files (source and
    bytecode) are explicitly deleted.

    No magic is performed when creating packages! This means that if you create
    a module within a package you must also create the package's __init__ as
    well.

    """
    source = 'attr = {0!r}'
    created_paths = []
    mapping = {}
    state_manager = None
    uncache_manager = None
    try:
        temp_dir = tempfile.mkdtemp()
        mapping['.root'] = temp_dir
        import_names = set()
        for name in names:
            if not name.endswith('__init__'):
                import_name = name
            else:
                import_name = name[:-len('.__init__')]
            import_names.add(import_name)
            if import_name in sys.modules:
                del sys.modules[import_name]
            name_parts = name.split('.')
            file_path = temp_dir
            for directory in name_parts[:-1]:
                file_path = os.path.join(file_path, directory)
                if not os.path.exists(file_path):
                    os.mkdir(file_path)
                    created_paths.append(file_path)
            file_path = os.path.join(file_path, name_parts[-1] + '.py')
            with open(file_path, 'w') as file:
                file.write(source.format(name))
            created_paths.append(file_path)
            mapping[name] = file_path
        uncache_manager = uncache(*import_names)
        uncache_manager.__enter__()
        state_manager = import_state(path=[temp_dir])
        state_manager.__enter__()
        yield mapping
    finally:
        if state_manager is not None:
            state_manager.__exit__(None, None, None)
        if uncache_manager is not None:
            uncache_manager.__exit__(None, None, None)
        support.rmtree(temp_dir)
Exemple #13
0
 def test_module_without_a_main(self):
     module_name = 't_main'
     support.rmtree(module_name)
     init_file = module_name + '/__init__.py'
     os.mkdir(module_name)
     with open(init_file, 'w') as f:
         pass
     self.addCleanup(support.rmtree, module_name)
     stdout, stderr = self._run_pdb(['-m', module_name], "")
     self.assertIn("ImportError: No module named t_main.__main__",
                   stdout.splitlines())
Exemple #14
0
 def test_executable(self):
     """
     Test that the sys.executable value is as expected.
     """
     rmtree(self.env_dir)
     self.run_with_capture(venv.create, self.env_dir)
     envpy = os.path.join(os.path.realpath(self.env_dir),
                          self.bindir, self.exe)
     out, err = check_output([envpy, '-c',
         'import sys; print(sys.executable)'])
     self.assertEqual(out.strip(), envpy.encode())
Exemple #15
0
 def test_executable(self):
     """
     Test that the sys.executable value is as expected.
     """
     rmtree(self.env_dir)
     self.run_with_capture(venv.create, self.env_dir)
     envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
     cmd = [envpy, '-c', 'import sys; print(sys.executable)']
     p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE)
     out, err = p.communicate()
     self.assertEqual(out.strip(), envpy.encode())
Exemple #16
0
 def test_executable_symlinks(self):
     """
     Test that the sys.executable value is as expected.
     """
     rmtree(self.env_dir)
     builder = venv.EnvBuilder(clear=True, symlinks=True)
     builder.create(self.env_dir)
     envpy = os.path.join(os.path.realpath(self.env_dir),
                          self.bindir, self.exe)
     out, err = check_output([envpy, '-c',
         'import sys; print(sys.executable)'])
     self.assertEqual(out.strip(), envpy.encode())
Exemple #17
0
 def test_multiprocessing(self):
     """
     Test that the multiprocessing is able to spawn.
     """
     rmtree(self.env_dir)
     self.run_with_capture(venv.create, self.env_dir)
     envpy = os.path.join(os.path.realpath(self.env_dir),
                          self.bindir, self.exe)
     out, err = check_output([envpy, '-c',
         'from multiprocessing import Pool; ' +
         'print(Pool(1).apply_async("Python".lower).get(3))'])
     self.assertEqual(out.strip(), "python".encode())
Exemple #18
0
 def run_pdb_module(self, script, commands):
     """Runs the script code as part of a module"""
     self.module_name = 't_main'
     support.rmtree(self.module_name)
     main_file = self.module_name + '/__main__.py'
     init_file = self.module_name + '/__init__.py'
     os.mkdir(self.module_name)
     with open(init_file, 'w') as f:
         pass
     with open(main_file, 'w') as f:
         f.write(textwrap.dedent(script))
     self.addCleanup(support.rmtree, self.module_name)
     return self._run_pdb(['-m', self.module_name], commands)
Exemple #19
0
 def test_executable_symlinks(self):
     """
     Test that the sys.executable value is as expected.
     """
     rmtree(self.env_dir)
     builder = venv.EnvBuilder(clear=True, symlinks=True)
     builder.create(self.env_dir)
     envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir, self.exe)
     cmd = [envpy, '-c', 'import sys; print(sys.executable)']
     p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE)
     out, err = p.communicate()
     self.assertEqual(out.strip(), envpy.encode())
Exemple #20
0
    def test_temp_dir(self):
        """Test that temp_dir() creates and destroys its directory."""
        parent_dir = tempfile.mkdtemp()
        parent_dir = os.path.realpath(parent_dir)

        try:
            path = os.path.join(parent_dir, 'temp')
            self.assertFalse(os.path.isdir(path))
            with support.temp_dir(path) as temp_path:
                self.assertEqual(temp_path, path)
                self.assertTrue(os.path.isdir(path))
            self.assertFalse(os.path.isdir(path))
        finally:
            support.rmtree(parent_dir)
Exemple #21
0
    def test_forget(self):
        mod_filename = TESTFN + '.py'
        with open(mod_filename, 'wt') as f:
            f.write('foo = 1\n')
        sys.path.insert(0, os.curdir)
        try:
            mod = __import__(TESTFN)
            self.assertIn(TESTFN, sys.modules)

            support.forget(TESTFN)
            self.assertNotIn(TESTFN, sys.modules)
        finally:
            del sys.path[0]
            support.unlink(mod_filename)
            support.rmtree('__pycache__')
Exemple #22
0
    def _do_directory(self, make_name, chdir_name):
        if os.path.isdir(make_name):
            rmtree(make_name)
        os.mkdir(make_name)
        try:
            with change_cwd(chdir_name):
                cwd_result = os.getcwd()
                name_result = make_name

                cwd_result = unicodedata.normalize("NFD", cwd_result)
                name_result = unicodedata.normalize("NFD", name_result)

                self.assertEqual(os.path.basename(cwd_result),name_result)
        finally:
            os.rmdir(make_name)
Exemple #23
0
 def test_unicode_in_batch_file(self):
     """
     Test handling of Unicode paths
     """
     rmtree(self.env_dir)
     env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
     builder = venv.EnvBuilder(clear=True)
     builder.create(env_dir)
     activate = os.path.join(env_dir, self.bindir, 'activate.bat')
     envpy = os.path.join(env_dir, self.bindir, self.exe)
     out, err = check_output(
         [activate, '&', self.exe, '-c', 'print(0)'],
         encoding='oem',
     )
     self.assertEqual(out.strip(), '0')
Exemple #24
0
    def test_forget(self):
        mod_filename = TESTFN + '.py'
        with open(mod_filename, 'w') as f:
            print('foo = 1', file=f)
        sys.path.insert(0, os.curdir)
        importlib.invalidate_caches()
        try:
            mod = __import__(TESTFN)
            self.assertIn(TESTFN, sys.modules)

            support.forget(TESTFN)
            self.assertNotIn(TESTFN, sys.modules)
        finally:
            del sys.path[0]
            support.unlink(mod_filename)
            support.rmtree('__pycache__')
Exemple #25
0
 def test_unicode_in_batch_file(self):
     """
     Test isolation from system site-packages
     """
     rmtree(self.env_dir)
     env_dir = os.path.join(os.path.realpath(self.env_dir), 'ϼўТλФЙ')
     builder = venv.EnvBuilder(clear=True)
     builder.create(env_dir)
     activate = os.path.join(env_dir, self.bindir, 'activate.bat')
     envpy = os.path.join(env_dir, self.bindir, self.exe)
     cmd = [activate, '&', self.exe, '-c', 'print(0)']
     p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE, encoding='oem',
                          shell=True)
     out, err = p.communicate()
     print(err)
     self.assertEqual(out.strip(), '0')
Exemple #26
0
    def test_prefixes(self):
        """
        Test that the prefix values are as expected.
        """
        #check our prefixes
        self.assertEqual(sys.base_prefix, sys.prefix)
        self.assertEqual(sys.base_exec_prefix, sys.exec_prefix)

        # check a venv's prefixes
        rmtree(self.env_dir)
        self.run_with_capture(venv.create, self.env_dir)
        envpy = os.path.join(self.env_dir, self.bindir, self.exe)
        cmd = [envpy, '-c', None]
        for prefix, expected in (
            ('prefix', self.env_dir),
            ('prefix', self.env_dir),
            ('base_prefix', sys.prefix),
            ('base_exec_prefix', sys.exec_prefix)):
            cmd[2] = 'import sys; print(sys.%s)' % prefix
            out, err = check_output(cmd)
            self.assertEqual(out.strip(), expected.encode())
    def test_file_parse(self):
        # issue1134: all encodings outside latin-1 and utf-8 fail on
        # multiline strings and long lines (>512 columns)
        unload(TESTFN)
        filename = TESTFN + ".py"
        f = open(filename, "w", encoding="cp1252")
        sys.path.insert(0, os.curdir)
        try:
            with f:
                f.write("# -*- coding: cp1252 -*-\n")
                f.write("'''A short string\n")
                f.write("'''\n")
                f.write("'A very long string %s'\n" % ("X" * 1000))

            importlib.invalidate_caches()
            __import__(TESTFN)
        finally:
            del sys.path[0]
            unlink(filename)
            unlink(filename + "c")
            unlink(filename + "o")
            unload(TESTFN)
            rmtree('__pycache__')
    def _do_directory(self, make_name, chdir_name, encoded):
        cwd = os.getcwdb()
        if os.path.isdir(make_name):
            rmtree(make_name)
        os.mkdir(make_name)
        try:
            os.chdir(chdir_name)
            try:
                if not encoded:
                    cwd_result = os.getcwd()
                    name_result = make_name
                else:
                    cwd_result = os.getcwdb().decode(TESTFN_ENCODING)
                    name_result = make_name.decode(TESTFN_ENCODING)

                cwd_result = unicodedata.normalize("NFD", cwd_result)
                name_result = unicodedata.normalize("NFD", name_result)

                self.assertEqual(os.path.basename(cwd_result), name_result)
            finally:
                os.chdir(cwd)
        finally:
            os.rmdir(make_name)
Exemple #29
0
 def test_relative_imports(self):
     self.module_name = 't_main'
     support.rmtree(self.module_name)
     main_file = self.module_name + '/__main__.py'
     init_file = self.module_name + '/__init__.py'
     module_file = self.module_name + '/module.py'
     self.addCleanup(support.rmtree, self.module_name)
     os.mkdir(self.module_name)
     with open(init_file, 'w') as f:
         f.write(textwrap.dedent("""
             top_var = "VAR from top"
         """))
     with open(main_file, 'w') as f:
         f.write(textwrap.dedent("""
             from . import top_var
             from .module import var
             from . import module
             pass # We'll stop here and print the vars
         """))
     with open(module_file, 'w') as f:
         f.write(textwrap.dedent("""
             var = "VAR from module"
             var2 = "second var"
         """))
     commands = """
         b 5
         c
         p top_var
         p var
         p module.var2
         quit
     """
     stdout, _ = self._run_pdb(['-m', self.module_name], commands)
     self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
     self.assertTrue(any("VAR from top" in l for l in stdout.splitlines()))
     self.assertTrue(any("second var" in l for l in stdout.splitlines()))
Exemple #30
0
    def test_rmtree(self):
        TESTDIRN = os.path.basename(tempfile.mkdtemp(dir='.'))
        self.addCleanup(support.rmtree, TESTDIRN)
        support.rmtree(TESTDIRN)

        os.mkdir(TESTDIRN)
        os.mkdir(os.path.join(TESTDIRN, TESTDIRN))
        support.rmtree(TESTDIRN)
        self.assertFalse(os.path.exists(TESTDIRN))
        support.rmtree(TESTDIRN)
Exemple #31
0
 def tearDown(self):
     rmtree(self.env_dir)
Exemple #32
0
 def tearDown(self):
     rmtree(TESTFN)
     unlink(TESTFN)
Exemple #33
0
 def setUp(self):
     support.unlink(TESTFN)
     support.rmtree(TESTDIRN)
Exemple #34
0
 def test_rmtree(self):
     os.mkdir(TESTDIRN)
     os.mkdir(os.path.join(TESTDIRN, TESTDIRN))
     support.rmtree(TESTDIRN)
     self.assertFalse(os.path.exists(TESTDIRN))
     support.rmtree(TESTDIRN)
Exemple #35
0
 def wrapper(*args, **kwargs):
     os.makedirs(directory)
     try:
         return function(*args, **kwargs)
     finally:
         support.rmtree(directory)
 def tearDown(self):
     sys.path[:] = self.old_path
     rmtree(TESTFN)
def remove_files(name):
    for f in (name + ".py", name + ".pyc", name + ".pyw", name + "$py.class"):
        unlink(f)
    rmtree('__pycache__')
 def tearDown(self):
     rmtree(self.path)
     sys.path[:] = self.syspath
Exemple #39
0
    def do_test_with_pip(self, system_site_packages):
        rmtree(self.env_dir)
        with EnvironmentVarGuard() as envvars:
            # pip's cross-version compatibility may trigger deprecation
            # warnings in current versions of Python. Ensure related
            # environment settings don't cause venv to fail.
            envvars["PYTHONWARNINGS"] = "e"
            # ensurepip is different enough from a normal pip invocation
            # that we want to ensure it ignores the normal pip environment
            # variable settings. We set PIP_NO_INSTALL here specifically
            # to check that ensurepip (and hence venv) ignores it.
            # See http://bugs.python.org/issue19734
            envvars["PIP_NO_INSTALL"] = "1"
            # Also check that we ignore the pip configuration file
            # See http://bugs.python.org/issue20053
            with tempfile.TemporaryDirectory() as home_dir:
                envvars["HOME"] = home_dir
                bad_config = "[global]\nno-install=1"
                # Write to both config file names on all platforms to reduce
                # cross-platform variation in test code behaviour
                win_location = ("pip", "pip.ini")
                posix_location = (".pip", "pip.conf")
                # Skips win_location due to http://bugs.python.org/issue20541
                for dirname, fname in (posix_location, ):
                    dirpath = os.path.join(home_dir, dirname)
                    os.mkdir(dirpath)
                    fpath = os.path.join(dirpath, fname)
                    with open(fpath, 'w') as f:
                        f.write(bad_config)

                # Actually run the create command with all that unhelpful
                # config in place to ensure we ignore it
                try:
                    self.run_with_capture(
                        venv.create,
                        self.env_dir,
                        system_site_packages=system_site_packages,
                        with_pip=True)
                except subprocess.CalledProcessError as exc:
                    # The output this produces can be a little hard to read,
                    # but at least it has all the details
                    details = exc.output.decode(errors="replace")
                    msg = "{}\n\n**Subprocess Output**\n{}"
                    self.fail(msg.format(exc, details))
        # Ensure pip is available in the virtual environment
        envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir,
                             self.exe)
        # Ignore DeprecationWarning since pip code is not part of Python
        out, err = check_output([
            envpy, '-W', 'ignore::DeprecationWarning', '-I', '-m', 'pip',
            '--version'
        ])
        # We force everything to text, so unittest gives the detailed diff
        # if we get unexpected results
        err = err.decode("latin-1")  # Force to text, prevent decoding errors
        self.assertEqual(err, "")
        out = out.decode("latin-1")  # Force to text, prevent decoding errors
        expected_version = "pip {}".format(ensurepip.version())
        self.assertEqual(out[:len(expected_version)], expected_version)
        env_dir = os.fsencode(self.env_dir).decode("latin-1")
        self.assertIn(env_dir, out)

        # http://bugs.python.org/issue19728
        # Check the private uninstall command provided for the Windows
        # installers works (at least in a virtual environment)
        with EnvironmentVarGuard() as envvars:
            out, err = check_output([
                envpy, '-W', 'ignore::DeprecationWarning', '-I', '-m',
                'ensurepip._uninstall'
            ])
        # We force everything to text, so unittest gives the detailed diff
        # if we get unexpected results
        err = err.decode("latin-1")  # Force to text, prevent decoding errors
        # Ignore the warning:
        #   "The directory '$HOME/.cache/pip/http' or its parent directory
        #    is not owned by the current user and the cache has been disabled.
        #    Please check the permissions and owner of that directory. If
        #    executing pip with sudo, you may want sudo's -H flag."
        # where $HOME is replaced by the HOME environment variable.
        err = re.sub(
            "^The directory .* or its parent directory is not owned "
            "by the current user .*$",
            "",
            err,
            flags=re.MULTILINE)
        self.assertEqual(err.rstrip(), "")
        # Being fairly specific regarding the expected behaviour for the
        # initial bundling phase in Python 3.4. If the output changes in
        # future pip versions, this test can likely be relaxed further.
        out = out.decode("latin-1")  # Force to text, prevent decoding errors
        self.assertIn("Successfully uninstalled pip", out)
        self.assertIn("Successfully uninstalled setuptools", out)
        # Check pip is now gone from the virtual environment. This only
        # applies in the system_site_packages=False case, because in the
        # other case, pip may still be available in the system site-packages
        if not system_site_packages:
            self.assert_pip_not_installed()
Exemple #40
0
 def tearDown(self):
     self.env.__exit__()
     del self.env
     support.rmtree(os.path.split(LOCALEDIR)[0])
Exemple #41
0
 def tearDown(self):
     support.rmtree(self.directory)
 def tearDownClass(cls):
     support.rmtree(support.TESTFN)
Exemple #43
0
def tearDownModule():
    if os.path.exists(TEMPDIR):
        support.rmtree(TEMPDIR)
    def test_with_pip(self):
        rmtree(self.env_dir)
        with EnvironmentVarGuard() as envvars:
            # pip's cross-version compatibility may trigger deprecation
            # warnings in current versions of Python. Ensure related
            # environment settings don't cause venv to fail.
            envvars["PYTHONWARNINGS"] = "e"
            # ensurepip is different enough from a normal pip invocation
            # that we want to ensure it ignores the normal pip environment
            # variable settings. We set PIP_NO_INSTALL here specifically
            # to check that ensurepip (and hence venv) ignores it.
            # See http://bugs.python.org/issue19734
            envvars["PIP_NO_INSTALL"] = "1"
            # Also check that we ignore the pip configuration file
            # See http://bugs.python.org/issue20053
            with tempfile.TemporaryDirectory() as home_dir:
                envvars["HOME"] = home_dir
                bad_config = "[global]\nno-install=1"
                # Write to both config file names on all platforms to reduce
                # cross-platform variation in test code behaviour
                win_location = ("pip", "pip.ini")
                posix_location = (".pip", "pip.conf")
                # Skips win_location due to http://bugs.python.org/issue20541
                for dirname, fname in (posix_location, ):
                    dirpath = os.path.join(home_dir, dirname)
                    os.mkdir(dirpath)
                    fpath = os.path.join(dirpath, fname)
                    with open(fpath, 'w') as f:
                        f.write(bad_config)

                # Actually run the create command with all that unhelpful
                # config in place to ensure we ignore it
                try:
                    self.run_with_capture(venv.create,
                                          self.env_dir,
                                          with_pip=True)
                except subprocess.CalledProcessError as exc:
                    # The output this produces can be a little hard to read,
                    # but at least it has all the details
                    details = exc.output.decode(errors="replace")
                    msg = "{}\n\n**Subprocess Output**\n{}"
                    self.fail(msg.format(exc, details))
        # Ensure pip is available in the virtual environment
        envpy = os.path.join(os.path.realpath(self.env_dir), self.bindir,
                             self.exe)
        cmd = [envpy, '-Im', 'pip', '--version']
        p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        out, err = p.communicate()
        # We force everything to text, so unittest gives the detailed diff
        # if we get unexpected results
        err = err.decode("latin-1")  # Force to text, prevent decoding errors
        self.assertEqual(err, "")
        out = out.decode("latin-1")  # Force to text, prevent decoding errors
        expected_version = "pip {}".format(ensurepip.version())
        self.assertEqual(out[:len(expected_version)], expected_version)
        env_dir = os.fsencode(self.env_dir).decode("latin-1")
        self.assertIn(env_dir, out)

        # http://bugs.python.org/issue19728
        # Check the private uninstall command provided for the Windows
        # installers works (at least in a virtual environment)
        cmd = [envpy, '-Im', 'ensurepip._uninstall']
        with EnvironmentVarGuard() as envvars:
            p = subprocess.Popen(cmd,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            out, err = p.communicate()
        # We force everything to text, so unittest gives the detailed diff
        # if we get unexpected results
        err = err.decode("latin-1")  # Force to text, prevent decoding errors
        self.assertEqual(err, "")
        # Being fairly specific regarding the expected behaviour for the
        # initial bundling phase in Python 3.4. If the output changes in
        # future pip versions, this test can likely be relaxed further.
        out = out.decode("latin-1")  # Force to text, prevent decoding errors
        self.assertIn("Successfully uninstalled pip", out)
        self.assertIn("Successfully uninstalled setuptools", out)
        # Check pip is now gone from the virtual environment
        self.assert_pip_not_installed()
 def cleanup():
     rmtree('pep3147')
     unload('pep3147.foo')
     unload('pep3147')
Exemple #46
0
 def _cleanup(self):
     support.rmtree(self.directory)
Exemple #47
0
 def test_no_pip_by_default(self):
     rmtree(self.env_dir)
     self.run_with_capture(venv.create, self.env_dir)
     self.assert_pip_not_installed()
 def _clean(self):
     forget(TESTFN)
     rmtree('__pycache__')
     unlink(self.source)
Exemple #49
0
 def test_explicit_no_pip(self):
     rmtree(self.env_dir)
     self.run_with_capture(venv.create, self.env_dir, with_pip=False)
     self.assert_pip_not_installed()
Exemple #50
0
 def newdirinpath(dir):
     os.mkdir(dir)
     sys.path.insert(0, dir)
     yield
     sys.path.pop(0)
     rmtree(dir)
Exemple #51
0
    def test_issue5604(self):
        # Test cannot cover imp.load_compiled function.
        # Martin von Loewis note what shared library cannot have non-ascii
        # character because init_xxx function cannot be compiled
        # and issue never happens for dynamic modules.
        # But sources modified to follow generic way for processing pathes.

        # the return encoding could be uppercase or None
        fs_encoding = sys.getfilesystemencoding()

        # covers utf-8 and Windows ANSI code pages
        # one non-space symbol from every page
        # (http://en.wikipedia.org/wiki/Code_page)
        known_locales = {
            'utf-8' : b'\xc3\xa4',
            'cp1250' : b'\x8C',
            'cp1251' : b'\xc0',
            'cp1252' : b'\xc0',
            'cp1253' : b'\xc1',
            'cp1254' : b'\xc0',
            'cp1255' : b'\xe0',
            'cp1256' : b'\xe0',
            'cp1257' : b'\xc0',
            'cp1258' : b'\xc0',
            }

        if sys.platform == 'darwin':
            self.assertEqual(fs_encoding, 'utf-8')
            # Mac OS X uses the Normal Form D decomposition
            # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
            special_char = b'a\xcc\x88'
        else:
            special_char = known_locales.get(fs_encoding)

        if not special_char:
            self.skipTest("can't run this test with %s as filesystem encoding"
                          % fs_encoding)
        decoded_char = special_char.decode(fs_encoding)
        temp_mod_name = 'test_imp_helper_' + decoded_char
        test_package_name = 'test_imp_helper_package_' + decoded_char
        init_file_name = os.path.join(test_package_name, '__init__.py')
        try:
            # if the curdir is not in sys.path the test fails when run with
            # ./python ./Lib/test/regrtest.py test_imp
            sys.path.insert(0, os.curdir)
            with open(temp_mod_name + '.py', 'w') as file:
                file.write('a = 1\n')
            file, filename, info = imp.find_module(temp_mod_name)
            with file:
                self.assertIsNotNone(file)
                self.assertTrue(filename[:-3].endswith(temp_mod_name))
                self.assertEqual(info[0], '.py')
                self.assertEqual(info[1], 'r')
                self.assertEqual(info[2], imp.PY_SOURCE)

                mod = imp.load_module(temp_mod_name, file, filename, info)
                self.assertEqual(mod.a, 1)

            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
            self.assertEqual(mod.a, 1)

            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                if not sys.dont_write_bytecode:
                    mod = imp.load_compiled(
                        temp_mod_name,
                        imp.cache_from_source(temp_mod_name + '.py'))
            self.assertEqual(mod.a, 1)

            if not os.path.exists(test_package_name):
                os.mkdir(test_package_name)
            with open(init_file_name, 'w') as file:
                file.write('b = 2\n')
            with warnings.catch_warnings():
                warnings.simplefilter('ignore')
                package = imp.load_package(test_package_name, test_package_name)
            self.assertEqual(package.b, 2)
        finally:
            del sys.path[0]
            for ext in ('.py', '.pyc'):
                support.unlink(temp_mod_name + ext)
                support.unlink(init_file_name + ext)
            support.rmtree(test_package_name)
            support.rmtree('__pycache__')