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


Python support.check_warnings函数代码示例

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


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

示例1: test_check_warnings

    def test_check_warnings(self):
        # Explicit tests for the test.support convenience wrapper
        wmod = self.module
        if wmod is not sys.modules['warnings']:
            self.skipTest('module to test is not loaded warnings module')
        with support.check_warnings(quiet=False) as w:
            self.assertEqual(w.warnings, [])
            wmod.simplefilter("always")
            wmod.warn("foo")
            self.assertEqual(str(w.message), "foo")
            wmod.warn("bar")
            self.assertEqual(str(w.message), "bar")
            self.assertEqual(str(w.warnings[0].message), "foo")
            self.assertEqual(str(w.warnings[1].message), "bar")
            w.reset()
            self.assertEqual(w.warnings, [])

        with support.check_warnings():
            # defaults to quiet=True without argument
            pass
        with support.check_warnings(('foo', UserWarning)):
            wmod.warn("foo")

        with self.assertRaises(AssertionError):
            with support.check_warnings(('', RuntimeWarning)):
                # defaults to quiet=False with argument
                pass
        with self.assertRaises(AssertionError):
            with support.check_warnings(('foo', RuntimeWarning)):
                wmod.warn("foo")
开发者ID:ARK4579,项目名称:cpython,代码行数:30,代码来源:__init__.py

示例2: test_compress_deprecated

    def test_compress_deprecated(self):
        tmpdir, tmpdir2, base_name =  self._create_files()

        # using compress and testing the PendingDeprecationWarning
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress')
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar.Z'
        self.assertTrue(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)

        # same test with dry_run
        os.remove(tarball)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress',
                             dry_run=True)
        finally:
            os.chdir(old_dir)
        self.assertTrue(not os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)
开发者ID:pogigroo,项目名称:py3k-__format__,代码行数:29,代码来源:test_archive_util.py

示例3: test_issue3221

    def test_issue3221(self):
        # Regression test for http://bugs.python.org/issue3221.
        def check_absolute():
            exec("from os import path", ns)
        def check_relative():
            exec("from . import relimport", ns)

        # Check both OK with __package__ and __name__ correct
        ns = dict(__package__='test', __name__='test.notarealmodule')
        check_absolute()
        check_relative()

        # Check both OK with only __name__ wrong
        ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
        check_absolute()
        check_relative()

        # Check relative fails with only __package__ wrong
        ns = dict(__package__='foo', __name__='test.notarealmodule')
        with check_warnings(('.+foo', RuntimeWarning)):
            check_absolute()
        self.assertRaises(SystemError, check_relative)

        # Check relative fails with __package__ and __name__ wrong
        ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
        with check_warnings(('.+foo', RuntimeWarning)):
            check_absolute()
        self.assertRaises(SystemError, check_relative)

        # Check both fail with package set to a non-string
        ns = dict(__package__=object())
        self.assertRaises(ValueError, check_absolute)
        self.assertRaises(ValueError, check_relative)
开发者ID:isaiah,项目名称:jython3,代码行数:33,代码来源:test_import.py

示例4: test_opening_mode

 def test_opening_mode(self):
     try:
         # invalid mode, should raise ValueError
         fi = FileInput(mode="w")
         self.fail("FileInput should reject invalid mode argument")
     except ValueError:
         pass
     # try opening in universal newline mode
     t1 = self.writeTmp(b"A\nB\r\nC\rD", mode="wb")
     with check_warnings(('', DeprecationWarning)):
         fi = FileInput(files=t1, mode="U")
     with check_warnings(('', DeprecationWarning)):
         lines = list(fi)
     self.assertEqual(lines, ["A\n", "B\n", "C\n", "D"])
开发者ID:Apoorvadabhere,项目名称:cpython,代码行数:14,代码来源:test_fileinput.py

示例5: testWarnings

 def testWarnings(self):
     with check_warnings(quiet=True) as w:
         self.assertEqual(w.warnings, [])
         self.assertRaises(TypeError, self.FileIO, [])
         self.assertEqual(w.warnings, [])
         self.assertRaises(ValueError, self.FileIO, "/some/invalid/name", "rt")
         self.assertEqual(w.warnings, [])
开发者ID:ARK4579,项目名称:cpython,代码行数:7,代码来源:test_fileio.py

示例6: check_all

 def check_all(self, modname):
     names = {}
     with support.check_warnings(
         (".* (module|package)", DeprecationWarning),
         ("", ResourceWarning),
         quiet=True):
         try:
             exec("import %s" % modname, names)
         except:
             # Silent fail here seems the best route since some modules
             # may not be available or not initialize properly in all
             # environments.
             raise FailedImport(modname)
     if not hasattr(sys.modules[modname], "__all__"):
         raise NoAll(modname)
     names = {}
     with self.subTest(module=modname):
         try:
             exec("from %s import *" % modname, names)
         except Exception as e:
             # Include the module name in the exception string
             self.fail("__all__ failure in {}: {}: {}".format(
                       modname, e.__class__.__name__, e))
         if "__builtins__" in names:
             del names["__builtins__"]
         keys = set(names)
         all_list = sys.modules[modname].__all__
         all_set = set(all_list)
         self.assertCountEqual(all_set, all_list, "in module {}".format(modname))
         self.assertEqual(keys, all_set, "in module {}".format(modname))
开发者ID:Connor124,项目名称:Gran-Theft-Crop-Toe,代码行数:30,代码来源:test___all__.py

示例7: test_merge

 def test_merge(self):
     with support.check_warnings(('merge is deprecated',
                                  DeprecationWarning)):
         merge = self.interp.tk.merge
         call = self.interp.tk.call
         testcases = [
             ((), ''),
             (('a',), 'a'),
             ((2,), '2'),
             (('',), '{}'),
             ('{', '\\{'),
             (('a', 'b', 'c'), 'a b c'),
             ((' ', '\t', '\r', '\n'), '{ } {\t} {\r} {\n}'),
             (('a', ' ', 'c'), 'a { } c'),
             (('a', '€'), 'a €'),
             (('a', '\U000104a2'), 'a \U000104a2'),
             (('a', b'\xe2\x82\xac'), 'a €'),
             (('a', ('b', 'c')), 'a {b c}'),
             (('a', 2), 'a 2'),
             (('a', 3.4), 'a 3.4'),
             (('a', (2, 3.4)), 'a {2 3.4}'),
             ((), ''),
             ((call('list', 1, '2', (3.4,)),), '{1 2 3.4}'),
         ]
         if tcl_version >= (8, 5):
             testcases += [
                 ((call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)),),
                  '{12 € € 3.4}'),
             ]
         for args, res in testcases:
             self.assertEqual(merge(*args), res, msg=args)
         self.assertRaises(UnicodeDecodeError, merge, b'\x80')
         self.assertRaises(UnicodeEncodeError, merge, '\udc80')
开发者ID:IgnusIndia,项目名称:pythonexperiment,代码行数:33,代码来源:test_tcl.py

示例8: test_check_metadata_deprecated

 def test_check_metadata_deprecated(self):
     # makes sure make_metadata is deprecated
     cmd = self._get_cmd()
     with check_warnings() as w:
         warnings.simplefilter("always")
         cmd.check_metadata()
         self.assertEqual(len(w.warnings), 1)
开发者ID:ChowZenki,项目名称:kbengine,代码行数:7,代码来源:test_register.py

示例9: testFormat

    def testFormat(self):
        # delay importing ctypes until we know we're in CPython
        from ctypes import (pythonapi, create_string_buffer, sizeof, byref,
                            c_double)
        PyOS_ascii_formatd = pythonapi.PyOS_ascii_formatd
        buf = create_string_buffer(100)

        tests = [
            ('%f', 100.0),
            ('%g', 100.0),
            ('%#g', 100.0),
            ('%#.2g', 100.0),
            ('%#.2g', 123.4567),
            ('%#.2g', 1.234567e200),
            ('%e', 1.234567e200),
            ('%e', 1.234),
            ('%+e', 1.234),
            ('%-e', 1.234),
            ]

        with check_warnings():
            for format, val in tests:
                PyOS_ascii_formatd(byref(buf), sizeof(buf),
                                   bytes(format, 'ascii'),
                                   c_double(val))
                self.assertEqual(buf.value, bytes(format % val, 'ascii'))
开发者ID:Kanma,项目名称:Athena-Dependencies-Python,代码行数:26,代码来源:test_ascii_formatd.py

示例10: test_warnings_on_cleanup

    def test_warnings_on_cleanup(self) -> None:
        # Two kinds of warning on shutdown
        #   Issue 10888: may write to stderr if modules are nulled out
        #   ResourceWarning will be triggered by __del__
        with self.do_create() as dir:
            if os.sep != '\\':
                # Embed a backslash in order to make sure string escaping
                # in the displayed error message is dealt with correctly
                suffix = '\\check_backslash_handling'
            else:
                suffix = ''
            d = self.do_create(dir=dir, suf=suffix)

            #Check for the Issue 10888 message
            modules = [os, os.path]
            if has_stat:
                modules.append(stat)
            with support.captured_stderr() as err:
                with NulledModules(*modules):
                    d.cleanup()
            message = err.getvalue().replace('\\\\', '\\')
            self.assertIn("while cleaning up",  message)
            self.assertIn(d.name,  message)

            # Check for the resource warning
            with support.check_warnings(('Implicitly', ResourceWarning), quiet=False):
                warnings.filterwarnings("always", category=ResourceWarning)
                d.__del__()
            self.assertFalse(os.path.exists(d.name),
                        "TemporaryDirectory %s exists after __del__" % d.name)
开发者ID:FlorianLudwig,项目名称:mypy,代码行数:30,代码来源:test_tempfile.py

示例11: test_https_with_cadefault

 def test_https_with_cadefault(self):
     handler = self.start_https_server(certfile=CERT_localhost)
     # Self-signed cert should fail verification with system certificate store
     with support.check_warnings(('', DeprecationWarning)):
         with self.assertRaises(urllib.error.URLError) as cm:
             self.urlopen("https://localhost:%s/bizarre" % handler.port,
                          cadefault=True)
开发者ID:Eyepea,项目名称:cpython,代码行数:7,代码来源:test_urllib2_localnet.py

示例12: test_resource_warning

 def test_resource_warning(self):
     # Issue #11453
     fd = os.open(support.TESTFN, os.O_RDONLY)
     f = asyncore.file_wrapper(fd)
     with support.check_warnings(('', ResourceWarning)):
         f = None
         support.gc_collect()
开发者ID:macroscopicentric,项目名称:cpython,代码行数:7,代码来源:test_asyncore.py

示例13: test_extension_init

    def test_extension_init(self):
        # the first argument, which is the name, must be a string
        self.assertRaises(AssertionError, Extension, 1, [])
        ext = Extension('name', [])
        self.assertEqual(ext.name, 'name')

        # the second argument, which is the list of files, must
        # be a list of strings
        self.assertRaises(AssertionError, Extension, 'name', 'file')
        self.assertRaises(AssertionError, Extension, 'name', ['file', 1])
        ext = Extension('name', ['file1', 'file2'])
        self.assertEqual(ext.sources, ['file1', 'file2'])

        # others arguments have defaults
        for attr in ('include_dirs', 'define_macros', 'undef_macros',
                     'library_dirs', 'libraries', 'runtime_library_dirs',
                     'extra_objects', 'extra_compile_args', 'extra_link_args',
                     'export_symbols', 'swig_opts', 'depends'):
            self.assertEqual(getattr(ext, attr), [])

        self.assertEqual(ext.language, None)
        self.assertEqual(ext.optional, None)

        # if there are unknown keyword options, warn about them
        with check_warnings() as w:
            warnings.simplefilter('always')
            ext = Extension('name', ['file1', 'file2'], chic=True)

        self.assertEqual(len(w.warnings), 1)
        self.assertEqual(str(w.warnings[0].message),
                          "Unknown Extension options: 'chic'")
开发者ID:0jpq0,项目名称:kbengine,代码行数:31,代码来源:test_extension.py

示例14: test_default_values_for_zero

 def test_default_values_for_zero(self):
     # Make sure that using all zeros uses the proper default values.
     # No test for daylight savings since strftime() does not change output
     # based on its value.
     expected = "2000 01 01 00 00 00 1 001"
     with support.check_warnings():
         result = time.strftime("%Y %m %d %H %M %S %w %j", (0,)*9)
     self.assertEqual(expected, result)
开发者ID:Sherlockhlt,项目名称:pypy,代码行数:8,代码来源:test_time.py

示例15: setUp

 def setUp(self):
     # create empty file
     fp = open(support.TESTFN, 'w+')
     fp.close()
     self._warnings_manager = support.check_warnings()
     self._warnings_manager.__enter__()
     warnings.filterwarnings('ignore', '.* potential security risk .*',
                             RuntimeWarning)
开发者ID:vladistan,项目名称:py3k-__format__-sprint,代码行数:8,代码来源:test_posix.py


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