Python test.support.check_warnings() Examples

The following are 30 code examples of test.support.check_warnings(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module test.support , or try the search function .
Example #1
Source File: test_fileinput.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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
        t1 = None
        try:
            # try opening in universal newline mode
            t1 = writeTmp(1, [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"])
        finally:
            remove_tempfiles(t1) 
Example #2
Source File: test_test_support.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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)

    # Tests for change_cwd() 
Example #3
Source File: test_io.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_garbage_collection(self):
        # C TextIOWrapper objects are collected, and collecting them flushes
        # all data to disk.
        # The Python version has __del__, so it ends in gc.garbage instead.
        with support.check_warnings(('', ResourceWarning)):
            rawio = io.FileIO(support.TESTFN, "wb")
            b = self.BufferedWriter(rawio)
            t = self.TextIOWrapper(b, encoding="ascii")
            t.write("456def")
            t.x = t
            wr = weakref.ref(t)
            del t
            support.gc_collect()
        self.assertIsNone(wr(), wr)
        with self.open(support.TESTFN, "rb") as f:
            self.assertEqual(f.read(), b"456def") 
Example #4
Source File: test_io.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_destructor(self):
        record = []
        class MyFileIO(self.FileIO):
            def __del__(self):
                record.append(1)
                try:
                    f = super().__del__
                except AttributeError:
                    pass
                else:
                    f()
            def close(self):
                record.append(2)
                super().close()
            def flush(self):
                record.append(3)
                super().flush()
        with support.check_warnings(('', ResourceWarning)):
            f = MyFileIO(support.TESTFN, "wb")
            f.write(b"xxx")
            del f
            support.gc_collect()
            self.assertEqual(record, [1, 2, 3])
            with self.open(support.TESTFN, "rb") as f:
                self.assertEqual(f.read(), b"xxx") 
Example #5
Source File: test_test_support.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_temp_dir__existing_dir__quiet_true(self):
        """Test passing a directory that already exists with quiet=True."""
        path = tempfile.mkdtemp()
        path = os.path.realpath(path)

        try:
            with support.check_warnings() as recorder:
                with support.temp_dir(path, quiet=True) as temp_path:
                    self.assertEqual(path, temp_path)
                warnings = [str(w.message) for w in recorder.warnings]
            # Make sure temp_dir did not delete the original directory.
            self.assertTrue(os.path.isdir(path))
        finally:
            shutil.rmtree(path)

        expected = ['tests may fail, unable to create temp dir: ' + path]
        self.assertEqual(warnings, expected) 
Example #6
Source File: test_io.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_destructor(self):
        record = []
        class MyFileIO(self.FileIO):
            def __del__(self):
                record.append(1)
                try:
                    f = super().__del__
                except AttributeError:
                    pass
                else:
                    f()
            def close(self):
                record.append(2)
                super().close()
            def flush(self):
                record.append(3)
                super().flush()
        with support.check_warnings(('', ResourceWarning)):
            f = MyFileIO(support.TESTFN, "wb")
            f.write(b"xxx")
            del f
            support.gc_collect()
            self.assertEqual(record, [1, 2, 3])
            with self.open(support.TESTFN, "rb") as f:
                self.assertEqual(f.read(), b"xxx") 
Example #7
Source File: test_io.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_garbage_collection(self):
        # C TextIOWrapper objects are collected, and collecting them flushes
        # all data to disk.
        # The Python version has __del__, so it ends in gc.garbage instead.
        with support.check_warnings(('', ResourceWarning)):
            rawio = io.FileIO(support.TESTFN, "wb")
            b = self.BufferedWriter(rawio)
            t = self.TextIOWrapper(b, encoding="ascii")
            t.write("456def")
            t.x = t
            wr = weakref.ref(t)
            del t
            support.gc_collect()
        self.assertIsNone(wr(), wr)
        with self.open(support.TESTFN, "rb") as f:
            self.assertEqual(f.read(), b"456def") 
Example #8
Source File: test_builtin.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_exec(self):
        g = {}
        exec('z = 1', g)
        if '__builtins__' in g:
            del g['__builtins__']
        self.assertEqual(g, {'z': 1})

        exec('z = 1+1', g)
        if '__builtins__' in g:
            del g['__builtins__']
        self.assertEqual(g, {'z': 2})
        g = {}
        l = {}

        with check_warnings():
            warnings.filterwarnings("ignore", "global statement",
                    module="<string>")
            exec('global a; a = 1; b = 2', g, l)
        if '__builtins__' in g:
            del g['__builtins__']
        if '__builtins__' in l:
            del l['__builtins__']
        self.assertEqual((g, l), ({'a': 1}, {'b': 2})) 
Example #9
Source File: test_support.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_temp_dir__existing_dir__quiet_true(self):
        """Test passing a directory that already exists with quiet=True."""
        path = tempfile.mkdtemp()
        path = os.path.realpath(path)

        try:
            with support.check_warnings() as recorder:
                with support.temp_dir(path, quiet=True) as temp_path:
                    self.assertEqual(path, temp_path)
                warnings = [str(w.message) for w in recorder.warnings]
            # Make sure temp_dir did not delete the original directory.
            self.assertTrue(os.path.isdir(path))
        finally:
            shutil.rmtree(path)

        expected = ['tests may fail, unable to create temp dir: ' + path]
        self.assertEqual(warnings, expected)

    # Tests for change_cwd() 
Example #10
Source File: test_ntpath.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_splitunc(self):
        with self.assertWarns(DeprecationWarning):
            ntpath.splitunc('')
        with support.check_warnings(('', DeprecationWarning)):
            tester('ntpath.splitunc("c:\\foo\\bar")',
                   ('', 'c:\\foo\\bar'))
            tester('ntpath.splitunc("c:/foo/bar")',
                   ('', 'c:/foo/bar'))
            tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")',
                   ('\\\\conky\\mountpoint', '\\foo\\bar'))
            tester('ntpath.splitunc("//conky/mountpoint/foo/bar")',
                   ('//conky/mountpoint', '/foo/bar'))
            tester('ntpath.splitunc("\\\\\\conky\\mountpoint\\foo\\bar")',
                   ('', '\\\\\\conky\\mountpoint\\foo\\bar'))
            tester('ntpath.splitunc("///conky/mountpoint/foo/bar")',
                   ('', '///conky/mountpoint/foo/bar'))
            tester('ntpath.splitunc("\\\\conky\\\\mountpoint\\foo\\bar")',
                   ('', '\\\\conky\\\\mountpoint\\foo\\bar'))
            tester('ntpath.splitunc("//conky//mountpoint/foo/bar")',
                   ('', '//conky//mountpoint/foo/bar'))
            self.assertEqual(ntpath.splitunc('//conky/MOUNTPOÄ°NT/foo/bar'),
                             ('//conky/MOUNTPOÄ°NT', '/foo/bar')) 
Example #11
Source File: test_urllib.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def urlopen(url, data=None, proxies=None):
    """urlopen(url [, data]) -> open file-like object"""
    global _urlopener
    if proxies is not None:
        opener = urllib.request.FancyURLopener(proxies=proxies)
    elif not _urlopener:
        with support.check_warnings(
                ('FancyURLopener style of invoking requests is deprecated.',
                DeprecationWarning)):
            opener = urllib.request.FancyURLopener()
        _urlopener = opener
    else:
        opener = _urlopener
    if data is None:
        return opener.open(url)
    else:
        return opener.open(url, data) 
Example #12
Source File: test_unicode.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_resize(self):
        for length in range(1, 100, 7):
            # generate a fresh string (refcount=1)
            text = 'a' * length + 'b'

            with support.check_warnings(('unicode_internal codec has been '
                                         'deprecated', DeprecationWarning)):
                # fill wstr internal field
                abc = text.encode('unicode_internal')
                self.assertEqual(abc.decode('unicode_internal'), text)

                # resize text: wstr field must be cleared and then recomputed
                text += 'c'
                abcdef = text.encode('unicode_internal')
                self.assertNotEqual(abc, abcdef)
                self.assertEqual(abcdef.decode('unicode_internal'), text) 
Example #13
Source File: test_genericpath.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_relpath_errors(self):
        # Check relpath() raises friendly TypeErrors.
        with support.check_warnings(('', (BytesWarning, DeprecationWarning)),
                                    quiet=True):
            errmsg = "Can't mix strings and bytes in path components"
            with self.assertRaisesRegex(TypeError, errmsg):
                self.pathmodule.relpath(b'bytes', 'str')
            with self.assertRaisesRegex(TypeError, errmsg):
                self.pathmodule.relpath('str', b'bytes')
            errmsg = r'relpath\(\) argument must be str or bytes, not %r'
            with self.assertRaisesRegex(TypeError, errmsg % 'int'):
                self.pathmodule.relpath(42, 'str')
            with self.assertRaisesRegex(TypeError, errmsg % 'int'):
                self.pathmodule.relpath('str', 42)
            with self.assertRaisesRegex(TypeError, errmsg % 'bytearray'):
                self.pathmodule.relpath(bytearray(b'foo'), bytearray(b'bar')) 
Example #14
Source File: test_genericpath.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_join_errors(self):
        # Check join() raises friendly TypeErrors.
        with support.check_warnings(('', BytesWarning), quiet=True):
            errmsg = "Can't mix strings and bytes in path components"
            with self.assertRaisesRegex(TypeError, errmsg):
                self.pathmodule.join(b'bytes', 'str')
            with self.assertRaisesRegex(TypeError, errmsg):
                self.pathmodule.join('str', b'bytes')
            # regression, see #15377
            errmsg = r'join\(\) argument must be str or bytes, not %r'
            with self.assertRaisesRegex(TypeError, errmsg % 'int'):
                self.pathmodule.join(42, 'str')
            with self.assertRaisesRegex(TypeError, errmsg % 'int'):
                self.pathmodule.join('str', 42)
            with self.assertRaisesRegex(TypeError, errmsg % 'int'):
                self.pathmodule.join(42)
            with self.assertRaisesRegex(TypeError, errmsg % 'list'):
                self.pathmodule.join([])
            with self.assertRaisesRegex(TypeError, errmsg % 'bytearray'):
                self.pathmodule.join(bytearray(b'foo'), bytearray(b'bar')) 
Example #15
Source File: test_xml_etree.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, quiet=False):
        if sys.flags.optimize >= 2:
            # under -OO, doctests cannot be run and therefore not all warnings
            # will be emitted
            quiet = True
        deprecations = (
            # Search behaviour is broken if search path starts with "/".
            ("This search is broken in 1.3 and earlier, and will be fixed "
             "in a future version.  If you rely on the current behaviour, "
             "change it to '.+'", FutureWarning),
            # Element.getchildren() and Element.getiterator() are deprecated.
            ("This method will be removed in future versions.  "
             "Use .+ instead.", DeprecationWarning),
            ("This method will be removed in future versions.  "
             "Use .+ instead.", PendingDeprecationWarning))
        self.checkwarnings = support.check_warnings(*deprecations, quiet=quiet) 
Example #16
Source File: test_result.py    From jawfish with MIT License 5 votes vote down vote up
def assertOldResultWarning(self, test, failures):
        with support.check_warnings(("TestResult has no add.+ method,",
                                     RuntimeWarning)):
            result = OldResult()
            test.run(result)
            self.assertEqual(len(result.failures), failures) 
Example #17
Source File: test_cgi.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_deprecated_parse_qs(self):
        # this func is moved to urllib.parse, this is just a sanity check
        with check_warnings(('cgi.parse_qs is deprecated, use urllib.parse.'
                             'parse_qs instead', DeprecationWarning)):
            self.assertEqual({'a': ['A1'], 'B': ['B3'], 'b': ['B2']},
                             cgi.parse_qs('a=A1&b=B2&B=B3')) 
Example #18
Source File: test_pkgutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_iter_importers_avoids_emulation(self):
        with check_warnings() as w:
            for importer in pkgutil.iter_importers(): pass
            self.assertEqual(len(w.warnings), 0) 
Example #19
Source File: test_pkgutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_get_importer_avoids_emulation(self):
        # We use an illegal path so *none* of the path hooks should fire
        with check_warnings() as w:
            self.assertIsNone(pkgutil.get_importer("*??"))
            self.assertEqual(len(w.warnings), 0) 
Example #20
Source File: test_pkgutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_find_loader_avoids_emulation(self):
        with check_warnings() as w:
            self.assertIsNotNone(pkgutil.find_loader("sys"))
            self.assertIsNotNone(pkgutil.find_loader("os"))
            self.assertIsNotNone(pkgutil.find_loader("test.support"))
            self.assertEqual(len(w.warnings), 0) 
Example #21
Source File: test_archive_util.py    From Imogen with MIT License 5 votes vote down vote up
def test_compress_deprecated(self):
        tmpdir =  self._create_files()
        base_name = os.path.join(self.mkdtemp(), 'archive')

        # 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.assertFalse(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1) 
Example #22
Source File: test_pkgutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_get_loader_handles_missing_loader_attribute(self):
        global __loader__
        this_loader = __loader__
        del __loader__
        try:
            with check_warnings() as w:
                self.assertIsNotNone(pkgutil.get_loader(__name__))
                self.assertEqual(len(w.warnings), 0)
        finally:
            __loader__ = this_loader 
Example #23
Source File: test_pkgutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def check_deprecated(self):
        return check_warnings(
            ("This emulation is deprecated, use 'importlib' instead",
             DeprecationWarning)) 
Example #24
Source File: test_fileio.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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, []) 
Example #25
Source File: test_codecs.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bad_encode_args(self):
        for encoding in all_unicode_encodings:
            encoder = codecs.getencoder(encoding)
            with support.check_warnings():
                # unicode-internal has been deprecated
                self.assertRaises(TypeError, encoder) 
Example #26
Source File: test_codecs.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_encode_length(self):
        with support.check_warnings(('unicode_internal codec has been '
                                     'deprecated', DeprecationWarning)):
            # Issue 3739
            encoder = codecs.getencoder("unicode_internal")
            self.assertEqual(encoder("a")[1], 1)
            self.assertEqual(encoder("\xe9\u0142")[1], 2)

            self.assertEqual(codecs.escape_encode(br'\x00')[1], 4)

# From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html 
Example #27
Source File: test_codecs.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_decode_error_attributes(self):
        try:
            with support.check_warnings(('unicode_internal codec has been '
                                         'deprecated', DeprecationWarning)):
                b"\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal")
        except UnicodeDecodeError as ex:
            self.assertEqual("unicode_internal", ex.encoding)
            self.assertEqual(b"\x00\x00\x00\x00\x00\x11\x11\x00", ex.object)
            self.assertEqual(4, ex.start)
            self.assertEqual(8, ex.end)
        else:
            self.fail() 
Example #28
Source File: test_codecs.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_bug691291(self):
        # Files are always opened in binary mode, even if no binary mode was
        # specified.  This means that no automatic conversion of '\n' is done
        # on reading and writing.
        s1 = 'Hello\r\nworld\r\n'

        s = s1.encode(self.encoding)
        self.addCleanup(support.unlink, support.TESTFN)
        with open(support.TESTFN, 'wb') as fp:
            fp.write(s)
        with support.check_warnings(('', DeprecationWarning)):
            reader = codecs.open(support.TESTFN, 'U', encoding=self.encoding)
        with reader:
            self.assertEqual(reader.read(), s1) 
Example #29
Source File: test_warnings.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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") 
Example #30
Source File: test_ftplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_storlines(self):
        f = io.BytesIO(RETR_DATA.replace('\r\n', '\n').encode('ascii'))
        self.client.storlines('stor', f)
        self.check_data(self.server.handler_instance.last_received_data, RETR_DATA)
        # test new callback arg
        flag = []
        f.seek(0)
        self.client.storlines('stor foo', f, callback=lambda x: flag.append(None))
        self.assertTrue(flag)

        f = io.StringIO(RETR_DATA.replace('\r\n', '\n'))
        # storlines() expects a binary file, not a text file
        with support.check_warnings(('', BytesWarning), quiet=True):
            self.assertRaises(TypeError, self.client.storlines, 'stor foo', f)