• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python support.change_cwd函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中test.support.change_cwd函数的典型用法代码示例。如果您正苦于以下问题:Python change_cwd函数的具体用法?Python change_cwd怎么用?Python change_cwd使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了change_cwd函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_realpath_resolve_before_normalizing

    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)
开发者ID:chidea,项目名称:GoPythonDLLWrapper,代码行数:25,代码来源:test_posixpath.py


示例2: test_srcdir_independent_of_cwd

 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)
开发者ID:chidea,项目名称:GoPythonDLLWrapper,代码行数:7,代码来源:test_sysconfig.py


示例3: test_make_zipfile_no_zlib

    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'])
开发者ID:Connor124,项目名称:Gran-Theft-Crop-Toe,代码行数:25,代码来源:test_archive_util.py


示例4: test_ismount

    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$\\"))
开发者ID:venkatanagineni,项目名称:cpython,代码行数:34,代码来源:test_ntpath.py


示例5: test_change_cwd__chdir_warning

 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])
开发者ID:MYSHLIFE,项目名称:cpython-1,代码行数:8,代码来源:test_support.py


示例6: test_empty

 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")
开发者ID:Connor124,项目名称:Gran-Theft-Crop-Toe,代码行数:9,代码来源:test_startfile.py


示例7: test_change_cwd

    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)
开发者ID:MYSHLIFE,项目名称:cpython-1,代码行数:9,代码来源:test_support.py


示例8: test_recursive_glob

    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)
开发者ID:invisiblek,项目名称:android_external_python,代码行数:56,代码来源:test_glob.py


示例9: test_dash_m_bad_pyc

 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)
开发者ID:wdv4758h,项目名称:cpython,代码行数:10,代码来源:test_cmd_line_script.py


示例10: test_issue8202_dash_m_file_ignored

 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
                 )
开发者ID:mshmoustafa,项目名称:static-python,代码行数:12,代码来源:test_cmd_line_script.py


示例11: test_issue8202_dash_c_file_ignored

 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)
开发者ID:mshmoustafa,项目名称:static-python,代码行数:12,代码来源:test_cmd_line_script.py


示例12: test_make_zipfile

    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)
开发者ID:BombShen,项目名称:kbengine,代码行数:12,代码来源:test_archive_util.py


示例13: test_dash_m_bad_pyc

 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)
开发者ID:CabbageHead-360,项目名称:cpython,代码行数:12,代码来源:test_cmd_line_script.py


示例14: test_dash_m_error_code_is_one

 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)
开发者ID:mshmoustafa,项目名称:static-python,代码行数:13,代码来源:test_cmd_line_script.py


示例15: test_change_cwd__chdir_warning

    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)
开发者ID:CCNITSilchar,项目名称:cpython,代码行数:14,代码来源:test_support.py


示例16: test_change_cwd__non_existent_dir__quiet_true

    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)
开发者ID:MYSHLIFE,项目名称:cpython-1,代码行数:14,代码来源:test_support.py


示例17: _do_directory

    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)
开发者ID:3lnc,项目名称:cpython,代码行数:15,代码来源:test_unicode_file.py


示例18: _make_tarball

    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)
开发者ID:Connor124,项目名称:Gran-Theft-Crop-Toe,代码行数:15,代码来源:test_archive_util.py


示例19: test_abs_paths

    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')))
开发者ID:funkyHat,项目名称:cpython,代码行数:48,代码来源:test_site.py


示例20: test_issue8202

 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)
开发者ID:CabbageHead-360,项目名称:cpython,代码行数:16,代码来源:test_cmd_line_script.py



注:本文中的test.support.change_cwd函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python support.check__all__函数代码示例发布时间:2022-05-27
下一篇:
Python support.captured_stdout函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap