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

Python support.swap_attr函数代码示例

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

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



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

示例1: test_no_files_left_behind

    def test_no_files_left_behind(self):
        # use a private empty directory
        with tempfile.TemporaryDirectory() as our_temp_directory:
            # force _get_default_tempdir() to consider our empty directory
            def our_candidate_list():
                return [our_temp_directory]

            with support.swap_attr(tempfile, "_candidate_tempdir_list", our_candidate_list):
                # verify our directory is empty after _get_default_tempdir()
                tempfile._get_default_tempdir()
                self.assertEqual(os.listdir(our_temp_directory), [])

                def raise_OSError(*args, **kwargs):
                    raise OSError()

                with support.swap_attr(io, "open", raise_OSError):
                    # test again with failing io.open()
                    with self.assertRaises(FileNotFoundError):
                        tempfile._get_default_tempdir()
                    self.assertEqual(os.listdir(our_temp_directory), [])

                open = io.open

                def bad_writer(*args, **kwargs):
                    fp = open(*args, **kwargs)
                    fp.write = raise_OSError
                    return fp

                with support.swap_attr(io, "open", bad_writer):
                    # test again with failing write()
                    with self.assertRaises(FileNotFoundError):
                        tempfile._get_default_tempdir()
                    self.assertEqual(os.listdir(our_temp_directory), [])
开发者ID:LesyaMazurevich,项目名称:python-1,代码行数:33,代码来源:test_tempfile.py


示例2: test_non_ascii

    def test_non_ascii(self):
        # Issues #8663, #34421: test that non-encodable text is escaped with
        # backslashreplace error handler and encodable non-ASCII text is
        # output as is.
        for errors in ('strict', 'backslashreplace', 'surrogateescape',
                       'replace', 'ignore'):
            with self.subTest(errors=errors):
                stdout = io.TextIOWrapper(io.BytesIO(),
                                          encoding='cp437', errors=errors)
                stderr = io.TextIOWrapper(io.BytesIO(),
                                          encoding='cp437', errors=errors)
                old_threshold = log.set_threshold(log.DEBUG)
                try:
                    with swap_attr(sys, 'stdout', stdout), \
                         swap_attr(sys, 'stderr', stderr):
                        log.debug('Dεbug\tMėssãge')
                        log.fatal('Fαtal\tÈrrōr')
                finally:
                    log.set_threshold(old_threshold)

                stdout.seek(0)
                self.assertEqual(stdout.read().rstrip(),
                        'Dεbug\tM?ss?ge' if errors == 'replace' else
                        'Dεbug\tMssge' if errors == 'ignore' else
                        'Dεbug\tM\\u0117ss\\xe3ge')
                stderr.seek(0)
                self.assertEqual(stderr.read().rstrip(),
                        'Fαtal\t?rr?r' if errors == 'replace' else
                        'Fαtal\trrr' if errors == 'ignore' else
                        'Fαtal\t\\xc8rr\\u014dr')
开发者ID:BombShen,项目名称:kbengine,代码行数:30,代码来源:test_log.py


示例3: test_initialization_no_master

 def test_initialization_no_master(self):
     # no master passing
     with swap_attr(tkinter, '_default_root', None), \
          swap_attr(tkinter, '_support_default_root', True):
         try:
             x = ttk.LabeledScale()
             self.assertIsNotNone(tkinter._default_root)
             self.assertEqual(x.master, tkinter._default_root)
             self.assertEqual(x.tk, tkinter._default_root.tk)
             x.destroy()
         finally:
             destroy_default_root()
开发者ID:0jpq0,项目名称:kbengine,代码行数:12,代码来源:test_extensions.py


示例4: test_memoryerror

    def test_memoryerror(self):
        lines = linecache.getlines(FILENAME)
        self.assertTrue(lines)
        def raise_memoryerror(*args, **kwargs):
            raise MemoryError
        with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
            lines2 = linecache.getlines(FILENAME)
        self.assertEqual(lines2, lines)

        linecache.clearcache()
        with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
            lines3 = linecache.getlines(FILENAME)
        self.assertEqual(lines3, [])
        self.assertEqual(linecache.getlines(FILENAME), lines)
开发者ID:chidea,项目名称:GoPythonDLLWrapper,代码行数:14,代码来源:test_linecache.py


示例5: test_home_not_set

    def test_home_not_set(self):
        fake_home = support.TESTFN
        os.mkdir(fake_home)
        self.addCleanup(support.rmtree, fake_home)
        fake_netrc_path = os.path.join(fake_home, '.netrc')
        with open(fake_netrc_path, 'w') as f:
            f.write('machine foo.domain.com login bar password pass')
        os.chmod(fake_netrc_path, 0o600)

        orig_expanduser = os.path.expanduser
        called = []

        def fake_expanduser(s):
            called.append(s)
            with support.EnvironmentVarGuard() as environ:
                environ.set('HOME', fake_home)
                result = orig_expanduser(s)
                return result

        with support.swap_attr(os.path, 'expanduser', fake_expanduser):
            nrc = netrc.netrc()
            login, account, password = nrc.authenticators('foo.domain.com')
            self.assertEqual(login, 'bar')

        self.assertTrue(called)
开发者ID:Eyepea,项目名称:cpython,代码行数:25,代码来源:test_netrc.py


示例6: test_format_exception

    def test_format_exception(self):
        try:
            self.last_raises5()
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        # [1:-1] to exclude "Traceback (...)" header and
        # exception type and value
        def extract(**kwargs):
            return traceback.format_exception(exc_type, exc_value, tb, **kwargs)[1:-1]

        with support.swap_attr(sys, 'tracebacklimit', 1000):
            nolim = extract()
            self.assertEqual(len(nolim), 5+1)
            self.assertEqual(extract(limit=2), nolim[:2])
            self.assertEqual(extract(limit=10), nolim)
            self.assertEqual(extract(limit=-2), nolim[-2:])
            self.assertEqual(extract(limit=-10), nolim)
            self.assertEqual(extract(limit=0), [])
            del sys.tracebacklimit
            self.assertEqual(extract(), nolim)
            sys.tracebacklimit = 2
            self.assertEqual(extract(), nolim[:2])
            self.assertEqual(extract(limit=3), nolim[:3])
            self.assertEqual(extract(limit=-3), nolim[-3:])
            sys.tracebacklimit = 0
            self.assertEqual(extract(), [])
            sys.tracebacklimit = -1
            self.assertEqual(extract(), [])
开发者ID:invisiblek,项目名称:android_external_python,代码行数:28,代码来源:test_traceback.py


示例7: test_collision_with_existing_directory

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


示例8: test_extract_stack

    def test_extract_stack(self):
        frame = self.last_returns_frame5()
        def extract(**kwargs):
            return traceback.extract_stack(frame, **kwargs)
        def assertEqualExcept(actual, expected, ignore):
            self.assertEqual(actual[:ignore], expected[:ignore])
            self.assertEqual(actual[ignore+1:], expected[ignore+1:])
            self.assertEqual(len(actual), len(expected))

        with support.swap_attr(sys, 'tracebacklimit', 1000):
            nolim = extract()
            self.assertGreater(len(nolim), 5)
            self.assertEqual(extract(limit=2), nolim[-2:])
            assertEqualExcept(extract(limit=100), nolim[-100:], -5-1)
            self.assertEqual(extract(limit=-2), nolim[:2])
            assertEqualExcept(extract(limit=-100), nolim[:100], len(nolim)-5-1)
            self.assertEqual(extract(limit=0), [])
            del sys.tracebacklimit
            assertEqualExcept(extract(), nolim, -5-1)
            sys.tracebacklimit = 2
            self.assertEqual(extract(), nolim[-2:])
            self.assertEqual(extract(limit=3), nolim[-3:])
            self.assertEqual(extract(limit=-3), nolim[:3])
            sys.tracebacklimit = 0
            self.assertEqual(extract(), [])
            sys.tracebacklimit = -1
            self.assertEqual(extract(), [])
开发者ID:invisiblek,项目名称:android_external_python,代码行数:27,代码来源:test_traceback.py


示例9: test_no_home_directory

    def test_no_home_directory(self):
        # bpo-10496: getuserbase() and getusersitepackages() must not fail if
        # the current user has no home directory (if expanduser() returns the
        # path unchanged).
        site.USER_SITE = None
        site.USER_BASE = None

        with EnvironmentVarGuard() as environ, \
             mock.patch('os.path.expanduser', lambda path: path):

            del environ['PYTHONUSERBASE']
            del environ['APPDATA']

            user_base = site.getuserbase()
            self.assertTrue(user_base.startswith('~' + os.sep),
                            user_base)

            user_site = site.getusersitepackages()
            self.assertTrue(user_site.startswith(user_base), user_site)

        with mock.patch('os.path.isdir', return_value=False) as mock_isdir, \
             mock.patch.object(site, 'addsitedir') as mock_addsitedir, \
             support.swap_attr(site, 'ENABLE_USER_SITE', True):

            # addusersitepackages() must not add user_site to sys.path
            # if it is not an existing directory
            known_paths = set()
            site.addusersitepackages(known_paths)

            mock_isdir.assert_called_once_with(user_site)
            mock_addsitedir.assert_not_called()
            self.assertFalse(known_paths)
开发者ID:Victor-Savu,项目名称:cpython,代码行数:32,代码来源:test_site.py


示例10: test_swap_attr

 def test_swap_attr(self):
     class Obj:
         pass
     obj = Obj()
     obj.x = 1
     with support.swap_attr(obj, "x", 5) as x:
         self.assertEqual(obj.x, 5)
         self.assertEqual(x, 1)
     self.assertEqual(obj.x, 1)
     with support.swap_attr(obj, "y", 5) as y:
         self.assertEqual(obj.y, 5)
         self.assertIsNone(y)
     self.assertFalse(hasattr(obj, 'y'))
     with support.swap_attr(obj, "y", 5):
         del obj.y
     self.assertFalse(hasattr(obj, 'y'))
开发者ID:CCNITSilchar,项目名称:cpython,代码行数:16,代码来源:test_support.py


示例11: test_non_directory

 def test_non_directory(self):
     with _inside_empty_temp_dir():
         tempdir = os.path.join(tempfile.tempdir, 'file')
         open(tempdir, 'wb').close()
         with support.swap_attr(tempfile, 'tempdir', tempdir):
             with self.assertRaises((NotADirectoryError, FileNotFoundError)):
                 self.make_temp()
开发者ID:chriszirkel,项目名称:tempcheck-pi,代码行数:7,代码来源:test_tempfile.py


示例12: test_swap_attr

 def test_swap_attr(self):
     class Obj:
         x = 1
     obj = Obj()
     with support.swap_attr(obj, "x", 5):
         self.assertEqual(obj.x, 5)
     self.assertEqual(obj.x, 1)
开发者ID:MYSHLIFE,项目名称:cpython-1,代码行数:7,代码来源:test_support.py


示例13: _inside_empty_temp_dir

def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, "tempdir", dir):
            yield
    finally:
        support.rmtree(dir)
开发者ID:LesyaMazurevich,项目名称:python-1,代码行数:7,代码来源:test_tempfile.py


示例14: test_extract_tb

    def test_extract_tb(self):
        try:
            self.last_raises5()
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        def extract(**kwargs):
            return traceback.extract_tb(tb, **kwargs)

        with support.swap_attr(sys, 'tracebacklimit', 1000):
            nolim = extract()
            self.assertEqual(len(nolim), 5+1)
            self.assertEqual(extract(limit=2), nolim[:2])
            self.assertEqual(extract(limit=10), nolim)
            self.assertEqual(extract(limit=-2), nolim[-2:])
            self.assertEqual(extract(limit=-10), nolim)
            self.assertEqual(extract(limit=0), [])
            del sys.tracebacklimit
            self.assertEqual(extract(), nolim)
            sys.tracebacklimit = 2
            self.assertEqual(extract(), nolim[:2])
            self.assertEqual(extract(limit=3), nolim[:3])
            self.assertEqual(extract(limit=-3), nolim[-3:])
            sys.tracebacklimit = 0
            self.assertEqual(extract(), [])
            sys.tracebacklimit = -1
            self.assertEqual(extract(), [])
开发者ID:invisiblek,项目名称:android_external_python,代码行数:26,代码来源:test_traceback.py


示例15: test_bad_timezone

    def test_bad_timezone(self):
        # Explicitly test possibility of bad timezone;
        # when time.tzname[0] == time.tzname[1] and time.daylight
        tz_name = time.tzname[0]
        if tz_name.upper() in ("UTC", "GMT"):
            self.skipTest('need non-UTC/GMT timezone')

        with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
             support.swap_attr(time, 'daylight', 1), \
             support.swap_attr(time, 'tzset', lambda: None):
            time.tzname = (tz_name, tz_name)
            time.daylight = 1
            tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
            self.assertEqual(tz_value, -1,
                    "%s lead to a timezone value of %s instead of -1 when "
                    "time.daylight set to %s and passing in %s" %
                    (time.tzname, tz_value, time.daylight, tz_name))
开发者ID:Dongese,项目名称:cpython,代码行数:17,代码来源:test_strptime.py


示例16: run_script

    def run_script(self, input="", *, args=("-",), substfile="xx yy\n"):
        substfilename = support.TESTFN + ".subst"
        with open(substfilename, "w") as file:
            file.write(substfile)
        self.addCleanup(support.unlink, substfilename)

        argv = ["fixcid.py", "-s", substfilename] + list(args)
        script = os.path.join(scriptsdir, "fixcid.py")
        with support.swap_attr(sys, "argv", argv), \
                support.swap_attr(sys, "stdin", StringIO(input)), \
                support.captured_stdout() as output, \
                support.captured_stderr():
            try:
                runpy.run_path(script, run_name="__main__")
            except SystemExit as exit:
                self.assertEqual(exit.code, 0)
        return output.getvalue()
开发者ID:1st1,项目名称:cpython,代码行数:17,代码来源:test_fixcid.py


示例17: test_issue31592

 def test_issue31592(self):
     # There shouldn't be an assertion failure in case of a bad
     # unicodedata.normalize().
     import unicodedata
     def bad_normalize(*args):
         return None
     with support.swap_attr(unicodedata, 'normalize', bad_normalize):
         self.assertRaises(TypeError, ast.parse, '\u03D5')
开发者ID:1st1,项目名称:cpython,代码行数:8,代码来源:test_ast.py


示例18: test_issue31411

 def test_issue31411(self):
     # warn_explicit() shouldn't raise a SystemError in case
     # warnings.onceregistry isn't a dictionary.
     wmod = self.module
     with original_warnings.catch_warnings(module=wmod):
         wmod.filterwarnings('once')
         with support.swap_attr(wmod, 'onceregistry', None):
             with self.assertRaises(TypeError):
                 wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
开发者ID:Apoorvadabhere,项目名称:cpython,代码行数:9,代码来源:__init__.py


示例19: test_apop_REDOS

 def test_apop_REDOS(self):
     # Replace welcome with very long evil welcome.
     # NB The upper bound on welcome length is currently 2048.
     # At this length, evil input makes each apop call take
     # on the order of milliseconds instead of microseconds.
     evil_welcome = b'+OK' + (b'<' * 1000000)
     with test_support.swap_attr(self.client, 'welcome', evil_welcome):
         # The evil welcome is invalid, so apop should throw.
         self.assertRaises(poplib.error_proto, self.client.apop, 'a', 'kb')
开发者ID:mkhren,项目名称:cpython,代码行数:9,代码来源:test_poplib.py


示例20: test_modify_builtins

    def test_modify_builtins(self):
        # Modify the builtins module directly.
        def foo():
            return len([1, 2, 3])
        self.configure_func(foo)

        self.assertEqual(foo(), 3)
        with swap_attr(builtins, "len", lambda x: 7):
            self.assertEqual(foo(), 7)
开发者ID:Connor124,项目名称:Gran-Theft-Crop-Toe,代码行数:9,代码来源:test_dynamic.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python support.swap_item函数代码示例发布时间:2022-05-27
下一篇:
Python support.strip_python_stderr函数代码示例发布时间: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