def test_make_zipfile_no_zlib(self):
        patch(self, archive_util.zipfile, 'zlib', None)  # force zlib ImportError

        called = []
        zipfile_class = zipfile.ZipFile
        def fake_zipfile(*a, **kw):
            if kw.get('compression', None) == zipfile.ZIP_STORED:
                called.append((a, kw))
            return zipfile_class(*a, **kw)

        patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile)

        # create something to tar and compress
        tmpdir = self._create_files()
        base_name = os.path.join(self.mkdtemp(), 'archive')
        with change_cwd(tmpdir):
            make_zipfile(base_name, 'dist')

        tarball = base_name + '.zip'
        self.assertEqual(called,
                         [((tarball, "w"), {'compression': zipfile.ZIP_STORED})])
        self.assertTrue(os.path.exists(tarball))
        with zipfile.ZipFile(tarball) as zf:
            self.assertEqual(sorted(zf.namelist()),
                             ['dist/file1', 'dist/file2', 'dist/sub/file3'])
Пример #2
0
 def test_srcdir_independent_of_cwd(self):
     # srcdir should be independent of the current working directory
     # See Issues #15322, #15364.
     srcdir = sysconfig.get_config_var('srcdir')
     with change_cwd(os.pardir):
         srcdir2 = sysconfig.get_config_var('srcdir')
     self.assertEqual(srcdir, srcdir2)
Пример #3
0
    def test_realpath_resolve_before_normalizing(self):
        # Bug #990669: Symbolic links should be resolved before we
        # normalize the path. E.g.: if we have directories 'a', 'k' and 'y'
        # in the following hierarchy:
        # a/k/y
        #
        # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
        # then realpath("link-y/..") should return 'k', not 'a'.
        try:
            os.mkdir(ABSTFN)
            os.mkdir(ABSTFN + "/k")
            os.mkdir(ABSTFN + "/k/y")
            os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y")

            # Absolute path.
            self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
            # Relative path.
            with support.change_cwd(dirname(ABSTFN)):
                self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
                                 ABSTFN + "/k")
        finally:
            support.unlink(ABSTFN + "/link-y")
            safe_rmdir(ABSTFN + "/k/y")
            safe_rmdir(ABSTFN + "/k")
            safe_rmdir(ABSTFN)
Пример #4
0
    def test_ismount(self):
        self.assertTrue(ntpath.ismount("c:\\"))
        self.assertTrue(ntpath.ismount("C:\\"))
        self.assertTrue(ntpath.ismount("c:/"))
        self.assertTrue(ntpath.ismount("C:/"))
        self.assertTrue(ntpath.ismount("\\\\.\\c:\\"))
        self.assertTrue(ntpath.ismount("\\\\.\\C:\\"))

        self.assertTrue(ntpath.ismount(b"c:\\"))
        self.assertTrue(ntpath.ismount(b"C:\\"))
        self.assertTrue(ntpath.ismount(b"c:/"))
        self.assertTrue(ntpath.ismount(b"C:/"))
        self.assertTrue(ntpath.ismount(b"\\\\.\\c:\\"))
        self.assertTrue(ntpath.ismount(b"\\\\.\\C:\\"))

        with support.temp_dir() as d:
            self.assertFalse(ntpath.ismount(d))

        if sys.platform == "win32":
            #
            # Make sure the current folder isn't the root folder
            # (or any other volume root). The drive-relative
            # locations below cannot then refer to mount points
            #
            drive, path = ntpath.splitdrive(sys.executable)
            with support.change_cwd(os.path.dirname(sys.executable)):
                self.assertFalse(ntpath.ismount(drive.lower()))
                self.assertFalse(ntpath.ismount(drive.upper()))

            self.assertTrue(ntpath.ismount("\\\\localhost\\c$"))
            self.assertTrue(ntpath.ismount("\\\\localhost\\c$\\"))

            self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$"))
            self.assertTrue(ntpath.ismount(b"\\\\localhost\\c$\\"))
Пример #5
0
 def test_change_cwd__chdir_warning(self):
     """Check the warning message when os.chdir() fails."""
     path = TESTFN + '_does_not_exist'
     with support.check_warnings() as recorder:
         with support.change_cwd(path=path, quiet=True):
             pass
         messages = [str(w.message) for w in recorder.warnings]
     self.assertEqual(messages, ['tests may fail, unable to change CWD to: ' + path])
 def test_empty(self):
     # We need to make sure the child process starts in a directory
     # we're not about to delete. If we're running under -j, that
     # means the test harness provided directory isn't a safe option.
     # See http://bugs.python.org/issue15526 for more details
     with support.change_cwd(path.dirname(sys.executable)):
         empty = path.join(path.dirname(__file__), "empty.vbs")
         startfile(empty)
         startfile(empty, "open")
Пример #7
0
    def test_change_cwd(self):
        original_cwd = os.getcwd()

        with support.temp_dir() as temp_path:
            with support.change_cwd(temp_path) as new_cwd:
                self.assertEqual(new_cwd, temp_path)
                self.assertEqual(os.getcwd(), new_cwd)

        self.assertEqual(os.getcwd(), original_cwd)
    def test_recursive_glob(self):
        eq = self.assertSequencesEqual_noorder
        full = [('ZZZ',),
                ('a',), ('a', 'D'),
                ('a', 'bcd'),
                ('a', 'bcd', 'EF'),
                ('a', 'bcd', 'efg'),
                ('a', 'bcd', 'efg', 'ha'),
                ('aaa',), ('aaa', 'zzzF'),
                ('aab',), ('aab', 'F'),
               ]
        if can_symlink():
            full += [('sym1',), ('sym2',),
                     ('sym3',),
                     ('sym3', 'EF'),
                     ('sym3', 'efg'),
                     ('sym3', 'efg', 'ha'),
                    ]
        eq(self.rglob('**'), self.joins(('',), *full))
        eq(self.rglob('.', '**'), self.joins(('.',''),
            *(('.',) + i for i in full)))
        dirs = [('a', ''), ('a', 'bcd', ''), ('a', 'bcd', 'efg', ''),
                ('aaa', ''), ('aab', '')]
        if can_symlink():
            dirs += [('sym3', ''), ('sym3', 'efg', '')]
        eq(self.rglob('**', ''), self.joins(('',), *dirs))

        eq(self.rglob('a', '**'), self.joins(
            ('a', ''), ('a', 'D'), ('a', 'bcd'), ('a', 'bcd', 'EF'),
            ('a', 'bcd', 'efg'), ('a', 'bcd', 'efg', 'ha')))
        eq(self.rglob('a**'), self.joins(('a',), ('aaa',), ('aab',)))
        expect = [('a', 'bcd', 'EF')]
        if can_symlink():
            expect += [('sym3', 'EF')]
        eq(self.rglob('**', 'EF'), self.joins(*expect))
        expect = [('a', 'bcd', 'EF'), ('aaa', 'zzzF'), ('aab', 'F')]
        if can_symlink():
            expect += [('sym3', 'EF')]
        eq(self.rglob('**', '*F'), self.joins(*expect))
        eq(self.rglob('**', '*F', ''), [])
        eq(self.rglob('**', 'bcd', '*'), self.joins(
            ('a', 'bcd', 'EF'), ('a', 'bcd', 'efg')))
        eq(self.rglob('a', '**', 'bcd'), self.joins(('a', 'bcd')))

        with change_cwd(self.tempdir):
            join = os.path.join
            eq(glob.glob('**', recursive=True), [join(*i) for i in full])
            eq(glob.glob(join('**', ''), recursive=True),
                [join(*i) for i in dirs])
            eq(glob.glob(join('**','zz*F'), recursive=True),
                [join('aaa', 'zzzF')])
            eq(glob.glob('**zz*F', recursive=True), [])
            expect = [join('a', 'bcd', 'EF')]
            if can_symlink():
                expect += [join('sym3', 'EF')]
            eq(glob.glob(join('**', 'EF'), recursive=True), expect)
Пример #9
0
 def test_dash_m_bad_pyc(self):
     with support.temp_dir() as script_dir, support.change_cwd(path=script_dir):
         os.mkdir("test_pkg")
         # Create invalid *.pyc as empty file
         with open("test_pkg/__init__.pyc", "wb"):
             pass
         err = self.check_dash_m_failure("test_pkg")
         self.assertRegex(err, br"Error while finding spec.*" br"ImportError.*bad magic number")
         self.assertNotIn(b"is a package", err)
         self.assertNotIn(b"Traceback", err)
 def test_issue8202_dash_m_file_ignored(self):
     # Make sure a "-m" file in the current directory
     # does not alter the value of sys.path[0]
     with temp_dir() as script_dir:
         script_name = _make_test_script(script_dir, "other")
         with support.change_cwd(path=script_dir):
             with open("-m", "w") as f:
                 f.write("data")
                 rc, out, err = assert_python_ok("-m", "other", *example_args)
                 self._check_output(
                     script_name, rc, out, script_name, script_name, "", "", importlib.machinery.SourceFileLoader
                 )
 def test_issue8202_dash_c_file_ignored(self):
     # Make sure a "-c" file in the current directory
     # does not alter the value of sys.path[0]
     with temp_dir() as script_dir:
         with support.change_cwd(path=script_dir):
             with open("-c", "w") as f:
                 f.write("data")
                 rc, out, err = assert_python_ok("-c", 'import sys; print("sys.path[0]==%r" % sys.path[0])')
                 if verbose > 1:
                     print(out)
                 expected = "sys.path[0]==%r" % ""
                 self.assertIn(expected.encode("utf-8"), out)
 def test_dash_m_bad_pyc(self):
     with support.temp_dir() as script_dir, \
             support.change_cwd(path=script_dir):
         os.mkdir('test_pkg')
         # Create invalid *.pyc as empty file
         with open('test_pkg/__init__.pyc', 'wb'):
             pass
         err = self.check_dash_m_failure('test_pkg')
         self.assertRegex(err, br'Error while finding spec.*'
             br'ImportError.*bad magic number')
         self.assertNotIn(b'is a package', err)
         self.assertNotIn(b'Traceback', err)
Пример #13
0
    def test_make_zipfile(self):
        # creating something to tar
        tmpdir = self._create_files()
        base_name = os.path.join(self.mkdtemp(), 'archive')
        with change_cwd(tmpdir):
            make_zipfile(base_name, 'dist')

        # check if the compressed tarball was created
        tarball = base_name + '.zip'
        self.assertTrue(os.path.exists(tarball))
        with zipfile.ZipFile(tarball) as zf:
            self.assertEqual(sorted(zf.namelist()), self._zip_created_files)
 def test_dash_m_error_code_is_one(self):
     # If a module is invoked with the -m command line flag
     # and results in an error that the return code to the
     # shell is '1'
     with temp_dir() as script_dir:
         with support.change_cwd(path=script_dir):
             pkg_dir = os.path.join(script_dir, "test_pkg")
             make_pkg(pkg_dir)
             script_name = _make_test_script(pkg_dir, "other", "if __name__ == '__main__': raise ValueError")
             rc, out, err = assert_python_failure("-m", "test_pkg.other", *example_args)
             if verbose > 1:
                 print(out)
             self.assertEqual(rc, 1)
Пример #15
0
    def test_change_cwd__non_existent_dir__quiet_true(self):
        """Test passing a non-existent directory with quiet=True."""
        original_cwd = os.getcwd()

        with support.temp_dir() as parent_dir:
            bad_dir = os.path.join(parent_dir, 'does_not_exist')
            with support.check_warnings() as recorder:
                with support.change_cwd(bad_dir, quiet=True) as new_cwd:
                    self.assertEqual(new_cwd, original_cwd)
                    self.assertEqual(os.getcwd(), new_cwd)
                warnings = [str(w.message) for w in recorder.warnings]

        expected = ['tests may fail, unable to change CWD to: ' + bad_dir]
        self.assertEqual(warnings, expected)
Пример #16
0
    def test_change_cwd__chdir_warning(self):
        """Check the warning message when os.chdir() fails."""
        path = TESTFN + '_does_not_exist'
        with support.check_warnings() as recorder:
            with support.change_cwd(path=path, quiet=True):
                pass
            messages = [str(w.message) for w in recorder.warnings]

        self.assertEqual(len(messages), 1, messages)
        msg = messages[0]
        self.assertTrue(msg.startswith(f'tests may fail, unable to change '
                                       f'the current working directory '
                                       f'to {path!r}: '),
                        msg)
Пример #17
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)
    def _make_tarball(self, tmpdir, target_name, suffix, **kwargs):
        tmpdir2 = self.mkdtemp()
        unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
                            "source and target should be on same drive")

        base_name = os.path.join(tmpdir2, target_name)

        # working with relative paths to avoid tar warnings
        with change_cwd(tmpdir):
            make_tarball(splitdrive(base_name)[1], 'dist', **kwargs)

        # check if the compressed tarball was created
        tarball = base_name + suffix
        self.assertTrue(os.path.exists(tarball))
        self.assertEqual(self._tarinfo(tarball), self._created_files)
Пример #19
0
    def test_abs_paths(self):
        # Make sure all imported modules have their __file__ and __cached__
        # attributes as absolute paths.  Arranging to put the Lib directory on
        # PYTHONPATH would cause the os module to have a relative path for
        # __file__ if abs_paths() does not get run.  sys and builtins (the
        # only other modules imported before site.py runs) do not have
        # __file__ or __cached__ because they are built-in.
        try:
            parent = os.path.relpath(os.path.dirname(os.__file__))
            cwd = os.getcwd()
        except ValueError:
            # Failure to get relpath probably means we need to chdir
            # to the same drive.
            cwd, parent = os.path.split(os.path.dirname(os.__file__))
        with change_cwd(cwd):
            env = os.environ.copy()
            env['PYTHONPATH'] = parent
            code = ('import os, sys',
                # use ASCII to avoid locale issues with non-ASCII directories
                'os_file = os.__file__.encode("ascii", "backslashreplace")',
                r'sys.stdout.buffer.write(os_file + b"\n")',
                'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
                r'sys.stdout.buffer.write(os_cached + b"\n")')
            command = '\n'.join(code)
            # First, prove that with -S (no 'import site'), the paths are
            # relative.
            proc = subprocess.Popen([sys.executable, '-S', '-c', command],
                                    env=env,
                                    stdout=subprocess.PIPE)
            stdout, stderr = proc.communicate()

            self.assertEqual(proc.returncode, 0)
            os__file__, os__cached__ = stdout.splitlines()[:2]
            self.assertFalse(os.path.isabs(os__file__))
            self.assertFalse(os.path.isabs(os__cached__))
            # Now, with 'import site', it works.
            proc = subprocess.Popen([sys.executable, '-c', command],
                                    env=env,
                                    stdout=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            self.assertEqual(proc.returncode, 0)
            os__file__, os__cached__ = stdout.splitlines()[:2]
            self.assertTrue(os.path.isabs(os__file__),
                            "expected absolute path, got {}"
                            .format(os__file__.decode('ascii')))
            self.assertTrue(os.path.isabs(os__cached__),
                            "expected absolute path, got {}"
                            .format(os__cached__.decode('ascii')))
 def test_issue8202(self):
     # Make sure package __init__ modules see "-m" in sys.argv0 while
     # searching for the module to execute
     with temp_dir() as script_dir:
         with support.change_cwd(path=script_dir):
             pkg_dir = os.path.join(script_dir, "test_pkg")
             make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
             script_name = _make_test_script(pkg_dir, "script")
             rc, out, err = assert_python_ok("-m", "test_pkg.script", *example_args)
             if verbose > 1:
                 print(out)
             expected = "init_argv0==%r" % "-m"
             self.assertIn(expected.encode("utf-8"), out)
             self._check_output(
                 script_name, rc, out, script_name, script_name, "", "test_pkg", importlib.machinery.SourceFileLoader
             )
Пример #21
0
    def test_realpath_resolve_first(self):
        # Bug #1213894: The first component of the path, if not absolute,
        # must be resolved too.

        try:
            os.mkdir(ABSTFN)
            os.mkdir(ABSTFN + "/k")
            os.symlink(ABSTFN, ABSTFN + "link")
            with support.change_cwd(dirname(ABSTFN)):
                base = basename(ABSTFN)
                self.assertEqual(realpath(base + "link"), ABSTFN)
                self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
        finally:
            support.unlink(ABSTFN + "link")
            safe_rmdir(ABSTFN + "/k")
            safe_rmdir(ABSTFN)
 def test_issue8202(self):
     # Make sure package __init__ modules see "-m" in sys.argv0 while
     # searching for the module to execute
     with support.temp_dir() as script_dir:
         with support.change_cwd(path=script_dir):
             pkg_dir = os.path.join(script_dir, 'test_pkg')
             make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
             script_name = _make_test_script(pkg_dir, 'script')
             rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args, __isolated=False)
             if verbose > 1:
                 print(repr(out))
             expected = "init_argv0==%r" % '-m'
             self.assertIn(expected.encode('utf-8'), out)
             self._check_output(script_name, rc, out,
                                script_name, script_name, '', 'test_pkg',
                                importlib.machinery.SourceFileLoader)
Пример #23
0
    def test_realpath_deep_recursion(self):
        depth = 10
        try:
            os.mkdir(ABSTFN)
            for i in range(depth):
                os.symlink('/'.join(['%d' % i] * 10), ABSTFN + '/%d' % (i + 1))
            os.symlink('.', ABSTFN + '/0')
            self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN)

            # Test using relative path as well.
            with support.change_cwd(ABSTFN):
                self.assertEqual(realpath('%d' % depth), ABSTFN)
        finally:
            for i in range(depth + 1):
                support.unlink(ABSTFN + '/%d' % i)
            safe_rmdir(ABSTFN)
Пример #24
0
    def test_realpath_resolve_parents(self):
        # We also need to resolve any symlinks in the parents of a relative
        # path passed to realpath. E.g.: current working directory is
        # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call
        # realpath("a"). This should return /usr/share/doc/a/.
        try:
            os.mkdir(ABSTFN)
            os.mkdir(ABSTFN + "/y")
            os.symlink(ABSTFN + "/y", ABSTFN + "/k")

            with support.change_cwd(ABSTFN + "/k"):
                self.assertEqual(realpath("a"), ABSTFN + "/y/a")
        finally:
            support.unlink(ABSTFN + "/k")
            safe_rmdir(ABSTFN + "/y")
            safe_rmdir(ABSTFN)
Пример #25
0
    def test_change_cwd__non_existent_dir__quiet_true(self):
        """Test passing a non-existent directory with quiet=True."""
        original_cwd = os.getcwd()

        with support.temp_dir() as parent_dir:
            bad_dir = os.path.join(parent_dir, 'does_not_exist')
            with support.check_warnings() as recorder:
                with support.change_cwd(bad_dir, quiet=True) as new_cwd:
                    self.assertEqual(new_cwd, original_cwd)
                    self.assertEqual(os.getcwd(), new_cwd)
                warnings = [str(w.message) for w in recorder.warnings]

        self.assertEqual(len(warnings), 1, warnings)
        warn = warnings[0]
        self.assertTrue(warn.startswith(f'tests may fail, unable to change '
                                        f'the current working directory '
                                        f'to {bad_dir!r}: '),
                        warn)
Пример #26
0
    def test_selflink(self):
        tempdir = TESTFN + "_dir"
        os.makedirs(tempdir)
        self.addCleanup(shutil.rmtree, tempdir)
        with change_cwd(tempdir):
            os.makedirs("dir")
            create_empty_file(os.path.join("dir", "file"))
            os.symlink(os.curdir, os.path.join("dir", "link"))

            results = glob.glob("**", recursive=True)
            self.assertEqual(len(results), len(set(results)))
            results = set(results)
            depth = 0
            while results:
                path = os.path.join(*(["dir"] + ["link"] * depth))
                self.assertIn(path, results)
                results.remove(path)
                if not results:
                    break
                path = os.path.join(path, "file")
                self.assertIn(path, results)
                results.remove(path)
                depth += 1

            results = glob.glob(os.path.join("**", "file"), recursive=True)
            self.assertEqual(len(results), len(set(results)))
            results = set(results)
            depth = 0
            while results:
                path = os.path.join(*(["dir"] + ["link"] * depth + ["file"]))
                self.assertIn(path, results)
                results.remove(path)
                depth += 1

            results = glob.glob(os.path.join("**", ""), recursive=True)
            self.assertEqual(len(results), len(set(results)))
            results = set(results)
            depth = 0
            while results:
                path = os.path.join(*(["dir"] + ["link"] * depth + [""]))
                self.assertIn(path, results)
                results.remove(path)
                depth += 1
Пример #27
0
    def test_selflink(self):
        tempdir = TESTFN + "_dir"
        os.makedirs(tempdir)
        self.addCleanup(shutil.rmtree, tempdir)
        with change_cwd(tempdir):
            os.makedirs('dir')
            create_empty_file(os.path.join('dir', 'file'))
            os.symlink(os.curdir, os.path.join('dir', 'link'))

            results = glob.glob('**', recursive=True)
            self.assertEqual(len(results), len(set(results)))
            results = set(results)
            depth = 0
            while results:
                path = os.path.join(*(['dir'] + ['link'] * depth))
                self.assertIn(path, results)
                results.remove(path)
                if not results:
                    break
                path = os.path.join(path, 'file')
                self.assertIn(path, results)
                results.remove(path)
                depth += 1

            results = glob.glob(os.path.join('**', 'file'), recursive=True)
            self.assertEqual(len(results), len(set(results)))
            results = set(results)
            depth = 0
            while results:
                path = os.path.join(*(['dir'] + ['link'] * depth + ['file']))
                self.assertIn(path, results)
                results.remove(path)
                depth += 1

            results = glob.glob(os.path.join('**', ''), recursive=True)
            self.assertEqual(len(results), len(set(results)))
            results = set(results)
            depth = 0
            while results:
                path = os.path.join(*(['dir'] + ['link'] * depth + ['']))
                self.assertIn(path, results)
                results.remove(path)
                depth += 1
Пример #28
0
    def test_realpath_symlink_loops(self):
        # Bug #930024, return the path unchanged if we get into an infinite
        # symlink loop.
        try:
            os.symlink(ABSTFN, ABSTFN)
            self.assertEqual(realpath(ABSTFN), ABSTFN)

            os.symlink(ABSTFN + "1", ABSTFN + "2")
            os.symlink(ABSTFN + "2", ABSTFN + "1")
            self.assertEqual(realpath(ABSTFN + "1"), ABSTFN + "1")
            self.assertEqual(realpath(ABSTFN + "2"), ABSTFN + "2")

            self.assertEqual(realpath(ABSTFN + "1/x"), ABSTFN + "1/x")
            self.assertEqual(realpath(ABSTFN + "1/.."), dirname(ABSTFN))
            self.assertEqual(realpath(ABSTFN + "1/../x"),
                             dirname(ABSTFN) + "/x")
            os.symlink(ABSTFN + "x", ABSTFN + "y")
            self.assertEqual(
                realpath(ABSTFN + "1/../" + basename(ABSTFN) + "y"),
                ABSTFN + "y")
            self.assertEqual(
                realpath(ABSTFN + "1/../" + basename(ABSTFN) + "1"),
                ABSTFN + "1")

            os.symlink(basename(ABSTFN) + "a/b", ABSTFN + "a")
            self.assertEqual(realpath(ABSTFN + "a"), ABSTFN + "a/b")

            os.symlink(
                "../" + basename(dirname(ABSTFN)) + "/" + basename(ABSTFN) +
                "c", ABSTFN + "c")
            self.assertEqual(realpath(ABSTFN + "c"), ABSTFN + "c")

            # Test using relative path as well.
            with support.change_cwd(dirname(ABSTFN)):
                self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
        finally:
            support.unlink(ABSTFN)
            support.unlink(ABSTFN + "1")
            support.unlink(ABSTFN + "2")
            support.unlink(ABSTFN + "y")
            support.unlink(ABSTFN + "c")
            support.unlink(ABSTFN + "a")
Пример #29
0
 def test_issue8202(self):
     # Make sure package __init__ modules see "-m" in sys.argv0 while
     # searching for the module to execute
     with support.temp_dir() as script_dir:
         with support.change_cwd(path=script_dir):
             pkg_dir = os.path.join(script_dir, 'test_pkg')
             make_pkg(pkg_dir,
                      "import sys; print('init_argv0==%r' % sys.argv[0])")
             script_name = _make_test_script(pkg_dir, 'script')
             rc, out, err = assert_python_ok('-m',
                                             'test_pkg.script',
                                             *example_args,
                                             __isolated=False)
             if verbose > 1:
                 print(repr(out))
             expected = "init_argv0==%r" % '-m'
             self.assertIn(expected.encode('utf-8'), out)
             self._check_output(script_name, rc, out, script_name,
                                script_name, script_dir, 'test_pkg',
                                importlib.machinery.SourceFileLoader)
Пример #30
0
 def test_issue8202_dash_m_file_ignored(self):
     # Make sure a "-m" file in the current directory
     # does not alter the value of sys.path[0]
     with support.temp_dir() as script_dir:
         script_name = _make_test_script(script_dir, 'other')
         with support.change_cwd(path=script_dir):
             with open("-m", "w") as f:
                 f.write("data")
                 rc, out, err = assert_python_ok('-m',
                                                 'other',
                                                 *example_args,
                                                 __isolated=False)
                 if sys.platform == 'OpenVMS':
                     script_name = script_name.replace(
                         '/tmp/', tmp_folder_real)
                     script_dir = script_dir.replace(
                         '/tmp/', tmp_folder_real)
                 self._check_output(script_name, rc, out, script_name,
                                    script_name, script_dir, '',
                                    importlib.machinery.SourceFileLoader)
Пример #31
0
 def test_selflink(self):
     tempdir = TESTFN + '_dir'
     os.makedirs(tempdir)
     self.addCleanup(shutil.rmtree, tempdir)
     with change_cwd(tempdir):
         os.makedirs('dir')
         create_empty_file(os.path.join('dir', 'file'))
         os.symlink(os.curdir, os.path.join('dir', 'link'))
         results = glob.glob('**', recursive=True)
         self.assertEqual(len(results), len(set(results)))
         results = set(results)
         depth = 0
         while results:
             path = os.path.join(*(['dir'] + ['link'] * depth))
             self.assertIn(path, results)
             results.remove(path)
             if not results:
                 break
             path = os.path.join(path, 'file')
             self.assertIn(path, results)
             results.remove(path)
             depth += 1
         results = glob.glob(os.path.join('**', 'file'), recursive=True)
         self.assertEqual(len(results), len(set(results)))
         results = set(results)
         depth = 0
         while results:
             path = os.path.join(*(['dir'] + ['link'] * depth + ['file']))
             self.assertIn(path, results)
             results.remove(path)
             depth += 1
         results = glob.glob(os.path.join('**', ''), recursive=True)
         self.assertEqual(len(results), len(set(results)))
         results = set(results)
         depth = 0
         while results:
             path = os.path.join(*(['dir'] + ['link'] * depth + ['']))
             self.assertIn(path, results)
             results.remove(path)
             depth += 1
Пример #32
0
    def test_find_executable(self):
        with test_support.temp_dir() as tmp_dir:
            # use TESTFN to get a pseudo-unique filename
            program_noeext = test_support.TESTFN
            # Give the temporary program an ".exe" suffix for all.
            # It's needed on Windows and not harmful on other platforms.
            program = program_noeext + ".exe"

            filename = os.path.join(tmp_dir, program)
            with open(filename, "wb"):
                pass
            os.chmod(filename, stat.S_IXUSR)

            # test path parameter
            rv = find_executable(program, path=tmp_dir)
            self.assertEqual(rv, filename)

            if sys.platform == 'win32':
                # test without ".exe" extension
                rv = find_executable(program_noeext, path=tmp_dir)
                self.assertEqual(rv, filename)

            # test find in the current directory
            with test_support.change_cwd(tmp_dir):
                rv = find_executable(program)
                self.assertEqual(rv, program)

            # test non-existent program
            dont_exist_program = "dontexist_" + program
            rv = find_executable(dont_exist_program, path=tmp_dir)
            self.assertIsNone(rv)

            # test os.defpath: missing PATH environment variable
            with test_support.EnvironmentVarGuard() as env:
                from distutils import spawn
                with test_support.swap_attr(spawn.os, 'defpath', tmp_dir):
                    env.pop('PATH')

                    rv = find_executable(program)
                    self.assertEqual(rv, filename)
Пример #33
0
    def test_find_executable(self):
        with test_support.temp_dir() as tmp_dir:
            # use TESTFN to get a pseudo-unique filename
            program_noeext = test_support.TESTFN
            # Give the temporary program an ".exe" suffix for all.
            # It's needed on Windows and not harmful on other platforms.
            program = program_noeext + ".exe"

            filename = os.path.join(tmp_dir, program)
            with open(filename, "wb"):
                pass
            os.chmod(filename, stat.S_IXUSR)

            # test path parameter
            rv = find_executable(program, path=tmp_dir)
            self.assertEqual(rv, filename)

            if sys.platform == 'win32':
                # test without ".exe" extension
                rv = find_executable(program_noeext, path=tmp_dir)
                self.assertEqual(rv, filename)

            # test find in the current directory
            with test_support.change_cwd(tmp_dir):
                rv = find_executable(program)
                self.assertEqual(rv, program)

            # test non-existent program
            dont_exist_program = "dontexist_" + program
            rv = find_executable(dont_exist_program , path=tmp_dir)
            self.assertIsNone(rv)

            # test os.defpath: missing PATH environment variable
            with test_support.EnvironmentVarGuard() as env:
                with mock.patch('distutils.spawn.os.defpath', tmp_dir):
                    env.pop('PATH')

                    rv = find_executable(program)
                    self.assertEqual(rv, filename)
Пример #34
0
    def test_realpath_symlink_loops(self):
        # Bug #930024, return the path unchanged if we get into an infinite
        # symlink loop.
        try:
            os.symlink(ABSTFN, ABSTFN)
            self.assertEqual(realpath(ABSTFN), ABSTFN)

            os.symlink(ABSTFN+"1", ABSTFN+"2")
            os.symlink(ABSTFN+"2", ABSTFN+"1")
            self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1")
            self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2")

            self.assertEqual(realpath(ABSTFN+"1/x"), ABSTFN+"1/x")
            self.assertEqual(realpath(ABSTFN+"1/.."), dirname(ABSTFN))
            self.assertEqual(realpath(ABSTFN+"1/../x"), dirname(ABSTFN) + "/x")
            os.symlink(ABSTFN+"x", ABSTFN+"y")
            self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "y"),
                             ABSTFN + "y")
            self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "1"),
                             ABSTFN + "1")

            os.symlink(basename(ABSTFN) + "a/b", ABSTFN+"a")
            self.assertEqual(realpath(ABSTFN+"a"), ABSTFN+"a/b")

            os.symlink("../" + basename(dirname(ABSTFN)) + "/" +
                       basename(ABSTFN) + "c", ABSTFN+"c")
            self.assertEqual(realpath(ABSTFN+"c"), ABSTFN+"c")

            # Test using relative path as well.
            with support.change_cwd(dirname(ABSTFN)):
                self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
        finally:
            support.unlink(ABSTFN)
            support.unlink(ABSTFN+"1")
            support.unlink(ABSTFN+"2")
            support.unlink(ABSTFN+"y")
            support.unlink(ABSTFN+"c")
            support.unlink(ABSTFN+"a")
Пример #35
0
    def test_make_zipfile_no_zlib(self):
        patch(self, archive_util.zipfile, 'zlib', None)
        called = []
        zipfile_class = zipfile.ZipFile

        def fake_zipfile(*a, **kw):
            if kw.get('compression', None) == zipfile.ZIP_STORED:
                called.append((a, kw))
            return zipfile_class(*a, **kw)

        patch(self, archive_util.zipfile, 'ZipFile', fake_zipfile)
        tmpdir = self._create_files()
        base_name = os.path.join(self.mkdtemp(), 'archive')
        with change_cwd(tmpdir):
            make_zipfile(base_name, 'dist')
        tarball = base_name + '.zip'
        self.assertEqual(called, [((tarball, 'w'), {
            'compression': zipfile.ZIP_STORED
        })])
        self.assertTrue(os.path.exists(tarball))
        with zipfile.ZipFile(tarball) as zf:
            self.assertEqual(sorted(zf.namelist()),
                             ['dist/file1', 'dist/file2', 'dist/sub/file3'])
Пример #36
0
 def test_ismount(self):
     self.assertTrue(ntpath.ismount('c:\\'))
     self.assertTrue(ntpath.ismount('C:\\'))
     self.assertTrue(ntpath.ismount('c:/'))
     self.assertTrue(ntpath.ismount('C:/'))
     self.assertTrue(ntpath.ismount('\\\\.\\c:\\'))
     self.assertTrue(ntpath.ismount('\\\\.\\C:\\'))
     self.assertTrue(ntpath.ismount(b'c:\\'))
     self.assertTrue(ntpath.ismount(b'C:\\'))
     self.assertTrue(ntpath.ismount(b'c:/'))
     self.assertTrue(ntpath.ismount(b'C:/'))
     self.assertTrue(ntpath.ismount(b'\\\\.\\c:\\'))
     self.assertTrue(ntpath.ismount(b'\\\\.\\C:\\'))
     with support.temp_dir() as d:
         self.assertFalse(ntpath.ismount(d))
     if sys.platform == 'win32':
         drive, path = ntpath.splitdrive(sys.executable)
         with support.change_cwd(os.path.dirname(sys.executable)):
             self.assertFalse(ntpath.ismount(drive.lower()))
             self.assertFalse(ntpath.ismount(drive.upper()))
         self.assertTrue(ntpath.ismount('\\\\localhost\\c$'))
         self.assertTrue(ntpath.ismount('\\\\localhost\\c$\\'))
         self.assertTrue(ntpath.ismount(b'\\\\localhost\\c$'))
         self.assertTrue(ntpath.ismount(b'\\\\localhost\\c$\\'))
Пример #37
0
    def test_recursive_glob(self):
        eq = self.assertSequencesEqual_noorder
        full = [
            ('EF', ),
            ('ZZZ', ),
            ('a', ),
            ('a', 'D'),
            ('a', 'bcd'),
            ('a', 'bcd', 'EF'),
            ('a', 'bcd', 'efg'),
            ('a', 'bcd', 'efg', 'ha'),
            ('aaa', ),
            ('aaa', 'zzzF'),
            ('aab', ),
            ('aab', 'F'),
        ]
        if can_symlink():
            full += [
                ('sym1', ),
                ('sym2', ),
                ('sym3', ),
                ('sym3', 'EF'),
                ('sym3', 'efg'),
                ('sym3', 'efg', 'ha'),
            ]
        eq(self.rglob('**'), self.joins(('', ), *full))
        eq(self.rglob(os.curdir, '**'),
           self.joins((os.curdir, ''), *((os.curdir, ) + i for i in full)))
        dirs = [('a', ''), ('a', 'bcd', ''), ('a', 'bcd', 'efg', ''),
                ('aaa', ''), ('aab', '')]
        if can_symlink():
            dirs += [('sym3', ''), ('sym3', 'efg', '')]
        eq(self.rglob('**', ''), self.joins(('', ), *dirs))

        eq(
            self.rglob('a', '**'),
            self.joins(('a', ''), ('a', 'D'), ('a', 'bcd'), ('a', 'bcd', 'EF'),
                       ('a', 'bcd', 'efg'), ('a', 'bcd', 'efg', 'ha')))
        eq(self.rglob('a**'), self.joins(('a', ), ('aaa', ), ('aab', )))
        expect = [('a', 'bcd', 'EF'), ('EF', )]
        if can_symlink():
            expect += [('sym3', 'EF')]
        eq(self.rglob('**', 'EF'), self.joins(*expect))
        expect = [('a', 'bcd', 'EF'), ('aaa', 'zzzF'), ('aab', 'F'), ('EF', )]
        if can_symlink():
            expect += [('sym3', 'EF')]
        eq(self.rglob('**', '*F'), self.joins(*expect))
        eq(self.rglob('**', '*F', ''), [])
        eq(self.rglob('**', 'bcd', '*'),
           self.joins(('a', 'bcd', 'EF'), ('a', 'bcd', 'efg')))
        eq(self.rglob('a', '**', 'bcd'), self.joins(('a', 'bcd')))

        with change_cwd(self.tempdir):
            join = os.path.join
            eq(glob.glob('**', recursive=True), [join(*i) for i in full])
            eq(glob.glob(join('**', ''), recursive=True),
               [join(*i) for i in dirs])
            eq(glob.glob(join('**', '*'), recursive=True),
               [join(*i) for i in full])
            eq(glob.glob(join(os.curdir, '**'), recursive=True),
               [join(os.curdir, '')] + [join(os.curdir, *i) for i in full])
            eq(glob.glob(join(os.curdir, '**', ''), recursive=True),
               [join(os.curdir, '')] + [join(os.curdir, *i) for i in dirs])
            eq(glob.glob(join(os.curdir, '**', '*'), recursive=True),
               [join(os.curdir, *i) for i in full])
            eq(glob.glob(join('**', 'zz*F'), recursive=True),
               [join('aaa', 'zzzF')])
            eq(glob.glob('**zz*F', recursive=True), [])
            expect = [join('a', 'bcd', 'EF'), 'EF']
            if can_symlink():
                expect += [join('sym3', 'EF')]
            eq(glob.glob(join('**', 'EF'), recursive=True), expect)
Пример #38
0
 def test_srcdir_independent_of_cwd(self):
     srcdir = sysconfig.get_config_var('srcdir')
     with change_cwd(os.pardir):
         srcdir2 = sysconfig.get_config_var('srcdir')
     self.assertEqual(srcdir, srcdir2)
Пример #39
0
 def call_change_cwd(path):
     with support.change_cwd(path) as new_cwd:
         raise Exception("should not get here")
Пример #40
0
 def test_empty(self):
     with support.change_cwd(path.dirname(sys.executable)):
         empty = path.join(path.dirname(__file__), 'empty.vbs')
         startfile(empty)
         startfile(empty, 'open')
Пример #41
0
 def test_cwd(self):
     with support.change_cwd(self.directory):
         py_compile.compile(os.path.basename(self.source_path),
                            os.path.basename(self.pyc_path))
     self.assertTrue(os.path.exists(self.pyc_path))
     self.assertFalse(os.path.exists(self.cache_path))
Пример #42
0
    def test_find_executable(self):
        with test_support.temp_dir() as tmp_dir:
            # use TESTFN to get a pseudo-unique filename
            program_noeext = test_support.TESTFN
            # Give the temporary program an ".exe" suffix for all.
            # It's needed on Windows and not harmful on other platforms.
            program = program_noeext + ".exe"

            filename = os.path.join(tmp_dir, program)
            with open(filename, "wb"):
                pass
            os.chmod(filename, stat.S_IXUSR)

            # test path parameter
            rv = find_executable(program, path=tmp_dir)
            self.assertEqual(rv, filename)

            if sys.platform == 'win32':
                # test without ".exe" extension
                rv = find_executable(program_noeext, path=tmp_dir)
                self.assertEqual(rv, filename)

            # test find in the current directory
            with test_support.change_cwd(tmp_dir):
                rv = find_executable(program)
                self.assertEqual(rv, program)

            # test non-existent program
            dont_exist_program = "dontexist_" + program
            rv = find_executable(dont_exist_program, path=tmp_dir)
            self.assertIsNone(rv)

            # PATH='': no match, except in the current directory
            with test_support.EnvironmentVarGuard() as env:
                env['PATH'] = ''
                with unittest.mock.patch('distutils.spawn.os.confstr',
                                         return_value=tmp_dir, create=True), \
                     unittest.mock.patch('distutils.spawn.os.defpath',
                                         tmp_dir):
                    rv = find_executable(program)
                    self.assertIsNone(rv)

                    # look in current directory
                    with test_support.change_cwd(tmp_dir):
                        rv = find_executable(program)
                        self.assertEqual(rv, program)

            # PATH=':': explicitly looks in the current directory
            with test_support.EnvironmentVarGuard() as env:
                env['PATH'] = os.pathsep
                with unittest.mock.patch('distutils.spawn.os.confstr',
                                         return_value='', create=True), \
                     unittest.mock.patch('distutils.spawn.os.defpath', ''):
                    rv = find_executable(program)
                    self.assertIsNone(rv)

                    # look in current directory
                    with test_support.change_cwd(tmp_dir):
                        rv = find_executable(program)
                        self.assertEqual(rv, program)

            # missing PATH: test os.confstr("CS_PATH") and os.defpath
            with test_support.EnvironmentVarGuard() as env:
                env.pop('PATH', None)

                # without confstr
                with unittest.mock.patch('distutils.spawn.os.confstr',
                                         side_effect=ValueError,
                                         create=True), \
                     unittest.mock.patch('distutils.spawn.os.defpath',
                                         tmp_dir):
                    rv = find_executable(program)
                    self.assertEqual(rv, filename)

                # with confstr
                with unittest.mock.patch('distutils.spawn.os.confstr',
                                         return_value=tmp_dir, create=True), \
                     unittest.mock.patch('distutils.spawn.os.defpath', ''):
                    rv = find_executable(program)
                    self.assertEqual(rv, filename)
Пример #43
0
 def setup_test_pkg(self, *args):
     with support.temp_dir() as script_dir, \
             support.change_cwd(path=script_dir):
         pkg_dir = os.path.join(script_dir, 'test_pkg')
         make_pkg(pkg_dir, *args)
         yield pkg_dir
Пример #44
0
 def call_change_cwd(path):
     with support.change_cwd(path) as new_cwd:
         raise Exception("should not get here")
Пример #45
0
def about_po(tmp_path):
    (tmp_path / "about.po").write_text(POText)
    with change_cwd(tmp_path):
        yield tmp_path