当前位置: 首页>>代码示例>>Python>>正文


Python test_support.swap_attr方法代码示例

本文整理汇总了Python中test.test_support.swap_attr方法的典型用法代码示例。如果您正苦于以下问题:Python test_support.swap_attr方法的具体用法?Python test_support.swap_attr怎么用?Python test_support.swap_attr使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在test.test_support的用法示例。


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

示例1: test_check_environ_getpwuid

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_check_environ_getpwuid(self):
        util._environ_checked = 0
        os.environ.pop('HOME', None)

        import pwd

        # only set pw_dir field, other fields are not used
        def mock_getpwuid(uid):
            return pwd.struct_passwd((None, None, None, None, None,
                                      '/home/distutils', None))

        with swap_attr(pwd, 'getpwuid', mock_getpwuid):
            check_environ()
            self.assertEqual(os.environ['HOME'], '/home/distutils')

        util._environ_checked = 0
        os.environ.pop('HOME', None)

        # bpo-10496: Catch pwd.getpwuid() error
        def getpwuid_err(uid):
            raise KeyError
        with swap_attr(pwd, 'getpwuid', getpwuid_err):
            check_environ()
            self.assertNotIn('HOME', os.environ) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:26,代码来源:test_util.py

示例2: run_script

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def run_script(self, input="", args=("-",), substfile="xx yy\n"):
        substfilename = test_support.TESTFN + ".subst"
        with open(substfilename, "w") as file:
            file.write(substfile)
        self.addCleanup(test_support.unlink, substfilename)

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

示例3: test_windows_colon

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_windows_colon(self):
        import SimpleHTTPServer
        with test_support.swap_attr(SimpleHTTPServer.os, 'path', ntpath):
            path = self.handler.translate_path('c:c:c:foo/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('\\c:../filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('c:\\c:..\\foo/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:20,代码来源:test_httpservers.py

示例4: test_stopped

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_stopped(self):
        """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
        args = [sys.executable, '-c', 'pass']
        proc = subprocess.Popen(args)

        # Wait until the real process completes to avoid zombie process
        pid = proc.pid
        pid, status = os.waitpid(pid, 0)
        self.assertEqual(status, 0)

        status = _testcapi.W_STOPCODE(3)

        def mock_waitpid(pid, flags):
            return (pid, status)

        with test_support.swap_attr(os, 'waitpid', mock_waitpid):
            returncode = proc.wait()

        self.assertEqual(returncode, -3) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:21,代码来源:test_subprocess.py

示例5: test_illegal_encoder

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_illegal_encoder(self):
        # bpo-31271: A TypeError should be raised in case the return value of
        # encoder's encode() is invalid.
        class BadEncoder:
            def encode(self, dummy):
                return u'spam'
        def get_bad_encoder(dummy):
            return BadEncoder()
        rot13 = codecs.lookup("rot13")
        with support.swap_attr(rot13, '_is_text_encoding', True), \
             support.swap_attr(rot13, 'incrementalencoder', get_bad_encoder):
            t = io.TextIOWrapper(io.BytesIO(b'foo'), encoding="rot13")
        with self.assertRaises(TypeError):
            t.write('bar')
            t.flush() 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:17,代码来源:test_io.py

示例6: test_issue31411

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
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 test_support.swap_attr(wmod, 'onceregistry', None):
                with self.assertRaises(TypeError):
                    wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:11,代码来源:test_warnings.py

示例7: test_expanduser_pwd

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_expanduser_pwd(self):
        pwd = support.import_module('pwd')

        self.assertIsInstance(posixpath.expanduser("~/"), str)

        # if home directory == root directory, this test makes no sense
        if posixpath.expanduser("~") != '/':
            self.assertEqual(
                posixpath.expanduser("~") + "/",
                posixpath.expanduser("~/")
            )
        self.assertIsInstance(posixpath.expanduser("~root/"), str)
        self.assertIsInstance(posixpath.expanduser("~foo/"), str)

        with support.EnvironmentVarGuard() as env:
            # expanduser should fall back to using the password database
            del env['HOME']

            home = pwd.getpwuid(os.getuid()).pw_dir
            # $HOME can end with a trailing /, so strip it (see #17809)
            home = home.rstrip("/") or '/'
            self.assertEqual(posixpath.expanduser("~"), home)

            # bpo-10496: If the HOME environment variable is not set and the
            # user (current identifier or name in the path) doesn't exist in
            # the password database (pwd.getuid() or pwd.getpwnam() fail),
            # expanduser() must return the path unchanged.
            def raise_keyerror(*args):
                raise KeyError

            with support.swap_attr(pwd, 'getpwuid', raise_keyerror), \
                 support.swap_attr(pwd, 'getpwnam', raise_keyerror):
                for path in ('~', '~/.local', '~vstinner/'):
                    self.assertEqual(posixpath.expanduser(path), path) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:36,代码来源:test_posixpath.py

示例8: test_no_files_left_behind

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_no_files_left_behind(self):
        # use a private empty directory
        our_temp_directory = tempfile.mkdtemp()
        try:
            # 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(-1)

                with support.swap_attr(io, "open", raise_OSError):
                    # test again with failing io.open()
                    with self.assertRaises(IOError) as cm:
                        tempfile._get_default_tempdir()
                    self.assertEqual(cm.exception.errno, errno.ENOENT)
                    self.assertEqual(os.listdir(our_temp_directory), [])

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

                with support.swap_attr(io, "open", bad_writer) as orig_open:
                    # test again with failing write()
                    with self.assertRaises(IOError) as cm:
                        tempfile._get_default_tempdir()
                    self.assertEqual(cm.exception.errno, errno.ENOENT)
                    self.assertEqual(os.listdir(our_temp_directory), [])
        finally:
            shutil.rmtree(our_temp_directory) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:39,代码来源:test_tempfile.py

示例9: _inside_empty_temp_dir

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, 'tempdir', dir):
            yield
    finally:
        support.rmtree(dir) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:9,代码来源:test_tempfile.py

示例10: _mock_candidate_names

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def _mock_candidate_names(*names):
    return support.swap_attr(tempfile,
                             '_get_candidate_names',
                             lambda: iter(names)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:6,代码来源:test_tempfile.py

示例11: test_nonexisting_directory

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_nonexisting_directory(self):
        with _inside_empty_temp_dir():
            tempdir = os.path.join(tempfile.tempdir, 'nonexistent')
            with support.swap_attr(tempfile, 'tempdir', tempdir):
                with self.assertRaises(OSError) as cm:
                    self.make_temp()
                self.assertEqual(cm.exception.errno, errno.ENOENT) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:9,代码来源:test_tempfile.py

示例12: test_linetoolong

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_linetoolong(self):
        maxline = 10

        class TooLongHandler(SimpleIMAPHandler):
            def handle(self):
                # Send a very long response line
                self.wfile.write('* OK ' + maxline * 'x' + '\r\n')

        with self.reaped_server(TooLongHandler) as server, \
                 support.swap_attr(imaplib, '_MAXLINE', maxline):
            with self.assertRaisesRegexp(imaplib.IMAP4.error,
                    'got more than 10 bytes'):
                self.imap_class(*server.server_address) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:15,代码来源:test_imaplib.py

示例13: test_apop_REDOS

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
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:IronLanguages,项目名称:ironpython2,代码行数:11,代码来源:test_poplib.py

示例14: test_recursive_repr

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_recursive_repr(self):
        # Issue #25455
        e = ET.Element('foo')
        with swap_attr(e, 'tag', e):
            with self.assertRaises(RuntimeError):
                repr(e)  # Should not crash 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:8,代码来源:test_xml_etree.py

示例15: test_find_mac

# 需要导入模块: from test import test_support [as 别名]
# 或者: from test.test_support import swap_attr [as 别名]
def test_find_mac(self):
        data = '''\

fake hwaddr
cscotun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
'''
        def mock_popen(cmd):
            if sys.platform == 'cli':
                return io.StringIO(data)
            return io.BytesIO(data)

        path = os.environ.get("PATH", os.defpath).split(os.pathsep)
        path.extend(('/sbin', '/usr/sbin'))
        for dir in path:
            executable = os.path.join(dir, 'ifconfig')
            if (os.path.exists(executable) and
                os.access(executable, os.F_OK | os.X_OK) and
                not os.path.isdir(executable)):
                break
        else:
            self.skipTest('requires ifconfig')

        with test_support.swap_attr(os, 'popen', mock_popen):
            mac = uuid._find_mac(
                command='ifconfig',
                args='',
                hw_identifiers=['hwaddr'],
                get_index=lambda x: x + 1,
            )
            self.assertEqual(mac, 0x1234567890ab) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:33,代码来源:test_uuid.py


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