Python warnings.resetwarnings() Examples

The following are 30 code examples for showing how to use warnings.resetwarnings(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module warnings , or try the search function .

Example 1
Project: python-control   Author: python-control   File: statefbk_array_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ctrb_siso_deprecated(self):
        A = np.array([[1., 2.], [3., 4.]])
        B = np.array([[5.], [7.]])
        
        # Check that default using np.matrix generates a warning
        # TODO: remove this check with matrix type is deprecated
        warnings.resetwarnings()
        with warnings.catch_warnings(record=True) as w:
            use_numpy_matrix(True)
            self.assertTrue(issubclass(w[-1].category, UserWarning))
            
            Wc = ctrb(A, B)
            self.assertTrue(isinstance(Wc, np.matrix))
            self.assertTrue(issubclass(w[-1].category,
                                       PendingDeprecationWarning))
            use_numpy_matrix(False) 
Example 2
Project: mysql_utils   Author: pinterest   File: mysql_lib.py    License: GNU General Public License v2.0 6 votes vote down vote up
def create_db(instance, db):
    """ Create a database if it does not already exist

    Args:
    instance - a hostAddr object
    db - the name of the db to be created
    """
    conn = connect_mysql(instance)
    cursor = conn.cursor()

    sql = ('CREATE DATABASE IF NOT EXISTS `{}`'.format(db))
    log.info(sql)

    # We don't care if the db already exists and this was a no-op
    warnings.filterwarnings('ignore', category=MySQLdb.Warning)
    cursor.execute(sql)
    warnings.resetwarnings() 
Example 3
Project: mysql_utils   Author: pinterest   File: mysql_lib.py    License: GNU General Public License v2.0 6 votes vote down vote up
def drop_db(instance, db):
    """ Drop a database, if it exists.

    Args:
    instance - a hostAddr object
    db - the name of the db to be dropped
    """
    conn = connect_mysql(instance)
    cursor = conn.cursor()

    sql = ('DROP DATABASE IF EXISTS `{}`'.format(db))
    log.info(sql)

    # If the DB isn't there, we'd throw a warning, but we don't
    # actually care; this will be a no-op.
    warnings.filterwarnings('ignore', category=MySQLdb.Warning)
    cursor.execute(sql)
    warnings.resetwarnings() 
Example 4
Project: mysql_utils   Author: pinterest   File: mysql_lib.py    License: GNU General Public License v2.0 6 votes vote down vote up
def start_event_scheduler(instance):
    """ Enable the event scheduler on a given MySQL server.

    Args:
        instance: The hostAddr object to act upon.
    """
    cmd = 'SET GLOBAL event_scheduler=ON'

    # We don't use the event scheduler in many places, but if we're
    # not able to start it when we want to, that could be a big deal.
    try:
        conn = connect_mysql(instance)
        cursor = conn.cursor()
        warnings.filterwarnings('ignore', category=MySQLdb.Warning)
        log.info(cmd)
        cursor.execute(cmd)
    except Exception as e:
        log.error('Unable to start event scheduler: {}'.format(e))
        raise
    finally:
        warnings.resetwarnings() 
Example 5
Project: mysql_utils   Author: pinterest   File: mysql_lib.py    License: GNU General Public License v2.0 6 votes vote down vote up
def stop_event_scheduler(instance):
    """ Disable the event scheduler on a given MySQL server.

    Args:
        instance: The hostAddr object to act upon.
    """
    cmd = 'SET GLOBAL event_scheduler=OFF'

    # If for some reason we're unable to disable the event scheduler,
    # that isn't likely to be a big deal, so we'll just pass after
    # logging the exception.
    try:
        conn = connect_mysql(instance)
        cursor = conn.cursor()
        warnings.filterwarnings('ignore', category=MySQLdb.Warning)
        log.info(cmd)
        cursor.execute(cmd)
    except Exception as e:
        log.error('Unable to stop event scheduler: {}'.format(e))
        pass
    finally:
        warnings.resetwarnings() 
Example 6
Project: ironpython2   Author: IronLanguages   File: test_pep352.py    License: Apache License 2.0 6 votes vote down vote up
def test_catch_string(self):
        # Catching a string should trigger a DeprecationWarning.
        with warnings.catch_warnings():
            warnings.resetwarnings()
            warnings.filterwarnings("error")
            str_exc = "spam"
            with self.assertRaises(DeprecationWarning):
                try:
                    raise StandardError
                except str_exc:
                    pass

            # Make sure that even if the string exception is listed in a tuple
            # that a warning is raised.
            with self.assertRaises(DeprecationWarning):
                try:
                    raise StandardError
                except (AssertionError, str_exc):
                    pass 
Example 7
Project: BinderFilter   Author: dxwu   File: test_pep352.py    License: MIT License 6 votes vote down vote up
def test_catch_string(self):
        # Catching a string should trigger a DeprecationWarning.
        with warnings.catch_warnings():
            warnings.resetwarnings()
            warnings.filterwarnings("error")
            str_exc = "spam"
            with self.assertRaises(DeprecationWarning):
                try:
                    raise StandardError
                except str_exc:
                    pass

            # Make sure that even if the string exception is listed in a tuple
            # that a warning is raised.
            with self.assertRaises(DeprecationWarning):
                try:
                    raise StandardError
                except (AssertionError, str_exc):
                    pass 
Example 8
Project: oss-ftp   Author: aliyun   File: test_functional.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        self.server = self.server_class()
        self.server.start()
        self.client = self.client_class(timeout=TIMEOUT)
        self.client.encoding = 'utf8'  # PY3 only
        self.client.connect(self.server.host, self.server.port)
        self.client.login(USER, PASSWD)
        if PY3:
            safe_mkdir(bytes(TESTFN_UNICODE, 'utf8'))
            touch(bytes(TESTFN_UNICODE_2, 'utf8'))
            self.utf8fs = TESTFN_UNICODE in os.listdir('.')
        else:
            warnings.filterwarnings("ignore")
            safe_mkdir(TESTFN_UNICODE)
            touch(TESTFN_UNICODE_2)
            self.utf8fs = unicode(TESTFN_UNICODE, 'utf8') in os.listdir(u('.'))
            warnings.resetwarnings() 
Example 9
Project: oss-ftp   Author: aliyun   File: test_functional.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        self.server = self.server_class()
        self.server.start()
        self.client = self.client_class(timeout=TIMEOUT)
        self.client.encoding = 'utf8'  # PY3 only
        self.client.connect(self.server.host, self.server.port)
        self.client.login(USER, PASSWD)
        if PY3:
            safe_mkdir(bytes(TESTFN_UNICODE, 'utf8'))
            touch(bytes(TESTFN_UNICODE_2, 'utf8'))
            self.utf8fs = TESTFN_UNICODE in os.listdir('.')
        else:
            warnings.filterwarnings("ignore")
            safe_mkdir(TESTFN_UNICODE)
            touch(TESTFN_UNICODE_2)
            self.utf8fs = unicode(TESTFN_UNICODE, 'utf8') in os.listdir(u('.'))
            warnings.resetwarnings() 
Example 10
Project: oss-ftp   Author: aliyun   File: test_pep352.py    License: MIT License 6 votes vote down vote up
def test_catch_string(self):
        # Catching a string should trigger a DeprecationWarning.
        with warnings.catch_warnings():
            warnings.resetwarnings()
            warnings.filterwarnings("error")
            str_exc = "spam"
            with self.assertRaises(DeprecationWarning):
                try:
                    raise StandardError
                except str_exc:
                    pass

            # Make sure that even if the string exception is listed in a tuple
            # that a warning is raised.
            with self.assertRaises(DeprecationWarning):
                try:
                    raise StandardError
                except (AssertionError, str_exc):
                    pass 
Example 11
def _run_generated_code(self, code, globs, locs,
                            fails_under_py3k=True,
                           ):
        import warnings
        from zope.interface._compat import PYTHON3
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            if not PYTHON3:
                exec(code, globs, locs)
                self.assertEqual(len(log), 0) # no longer warn
                return True
            else:
                try:
                    exec(code, globs, locs)
                except TypeError:
                    return False
                else:
                    if fails_under_py3k:
                        self.fail("Didn't raise TypeError") 
Example 12
def test_called_from_function(self):
        import warnings
        from zope.interface.declarations import implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'implements': implements, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'def foo():',
            '    implements(IFoo)'
            ])
        if self._run_generated_code(CODE, globs, locs, False):
            foo = locs['foo']
            with warnings.catch_warnings(record=True) as log:
                warnings.resetwarnings()
                self.assertRaises(TypeError, foo)
                self.assertEqual(len(log), 0) # no longer warn 
Example 13
def test_called_twice_from_class(self):
        import warnings
        from zope.interface.declarations import implements
        from zope.interface.interface import InterfaceClass
        from zope.interface._compat import PYTHON3
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        globs = {'implements': implements, 'IFoo': IFoo, 'IBar': IBar}
        locs = {}
        CODE = "\n".join([
            'class Foo(object):',
            '    implements(IFoo)',
            '    implements(IBar)',
            ])
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            try:
                exec(CODE, globs, locs)
            except TypeError:
                if not PYTHON3:
                    self.assertEqual(len(log), 0) # no longer warn
            else:
                self.fail("Didn't raise TypeError") 
Example 14
def test_called_from_function(self):
        import warnings
        from zope.interface.declarations import classProvides
        from zope.interface.interface import InterfaceClass
        from zope.interface._compat import PYTHON3
        IFoo = InterfaceClass("IFoo")
        globs = {'classProvides': classProvides, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'def foo():',
            '    classProvides(IFoo)'
            ])
        exec(CODE, globs, locs)
        foo = locs['foo']
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            self.assertRaises(TypeError, foo)
            if not PYTHON3:
                self.assertEqual(len(log), 0) # no longer warn 
Example 15
Project: deepWordBug   Author: QData   File: test_core.py    License: Apache License 2.0 6 votes vote down vote up
def test_setupterm_singleton_issue33():
    "A warning is emitted if a new terminal ``kind`` is used per process."
    @as_subprocess
    def child():
        warnings.filterwarnings("error", category=UserWarning)

        # instantiate first terminal, of type xterm-256color
        term = TestTerminal(force_styling=True)

        try:
            # a second instantiation raises UserWarning
            term = TestTerminal(kind="vt220", force_styling=True)
        except UserWarning:
            err = sys.exc_info()[1]
            assert (err.args[0].startswith(
                    'A terminal of kind "vt220" has been requested')
                    ), err.args[0]
            assert ('a terminal of kind "xterm-256color" will '
                    'continue to be returned' in err.args[0]), err.args[0]
        else:
            # unless term is not a tty and setupterm() is not called
            assert not term.is_a_tty or False, 'Should have thrown exception'
        warnings.resetwarnings()

    child() 
Example 16
Project: deepWordBug   Author: QData   File: test_core.py    License: Apache License 2.0 6 votes vote down vote up
def test_setupterm_invalid_issue39():
    "A warning is emitted if TERM is invalid."
    # https://bugzilla.mozilla.org/show_bug.cgi?id=878089
    #
    # if TERM is unset, defaults to 'unknown', which should
    # fail to lookup and emit a warning on *some* systems.
    # freebsd actually has a termcap entry for 'unknown'
    @as_subprocess
    def child():
        warnings.filterwarnings("error", category=UserWarning)

        try:
            term = TestTerminal(kind='unknown', force_styling=True)
        except UserWarning:
            err = sys.exc_info()[1]
            assert err.args[0] == (
                "Failed to setupterm(kind='unknown'): "
                "setupterm: could not find terminal")
        else:
            if platform.system().lower() != 'freebsd':
                assert not term.is_a_tty and not term.does_styling, (
                    'Should have thrown exception')
        warnings.resetwarnings()

    child() 
Example 17
Project: deepWordBug   Author: QData   File: test_core.py    License: Apache License 2.0 6 votes vote down vote up
def test_setupterm_invalid_has_no_styling():
    "An unknown TERM type does not perform styling."
    # https://bugzilla.mozilla.org/show_bug.cgi?id=878089

    # if TERM is unset, defaults to 'unknown', which should
    # fail to lookup and emit a warning, only.
    @as_subprocess
    def child():
        warnings.filterwarnings("ignore", category=UserWarning)

        term = TestTerminal(kind='xxXunknownXxx', force_styling=True)
        assert term.kind is None
        assert not term.does_styling
        assert term.number_of_colors == 0
        warnings.resetwarnings()

    child() 
Example 18
Project: requests-aws4auth   Author: tedder   File: test_requests_aws4auth.py    License: MIT License 6 votes vote down vote up
def test_amz_date_warning(self):
        """
        Will be removed when deprecated amz_date attribute is removed

        """
        warnings.resetwarnings()
        with warnings.catch_warnings(record=True) as w:
            obj = AWS4SigningKey('secret_key', 'region', 'service')
            if PY2:
                warnings.simplefilter('always')
                obj.amz_date
                self.assertEqual(len(w), 1)
                self.assertEqual(w[-1].category, DeprecationWarning)
            else:
                warnings.simplefilter('ignore')
                self.assertWarns(DeprecationWarning, getattr, obj, 'amz_date') 
Example 19
Project: jams   Author: marl   File: test_jams.py    License: ISC License 6 votes vote down vote up
def test_deprecated():

    @jams.core.deprecated('old version', 'new version')
    def _foo():
        pass

    warnings.resetwarnings()
    warnings.simplefilter('always')
    with warnings.catch_warnings(record=True) as out:
        _foo()

        # And that the warning triggered
        assert len(out) > 0

        # And that the category is correct
        assert out[0].category is DeprecationWarning

        # And that it says the right thing (roughly)
        assert 'deprecated' in str(out[0].message).lower() 
Example 20
Project: python-monascaclient   Author: openstack   File: test_client.py    License: Apache License 2.0 6 votes vote down vote up
def test_should_override_insecure_with_negated_verify(self,
                                                          _,
                                                          get_auth,
                                                          __):
        api_version = mock.Mock()
        auth_val = mock.Mock()
        get_auth.return_value = auth_val

        for insecure in [True, False]:
            warnings.resetwarnings()
            with warnings.catch_warnings(record=True) as w:
                warnings.simplefilter('always')
                client.Client(api_version, insecure=insecure)

                self.assertEqual(1, len(w))
                self.assertEqual(DeprecationWarning, w[0].category)
                self.assertRegex(
                    str(w[0].message),
                    'Usage of insecure has been deprecated in favour of'
                )

            get_auth.assert_called_once_with({
                'verify': not insecure
            })
            get_auth.reset_mock() 
Example 21
Project: learn_python3_spider   Author: wistbean   File: test_declarations.py    License: MIT License 6 votes vote down vote up
def _run_generated_code(self, code, globs, locs,
                            fails_under_py3k=True,
                           ):
        import warnings
        from zope.interface._compat import PYTHON3
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            if not PYTHON3:
                exec(code, globs, locs)
                self.assertEqual(len(log), 0) # no longer warn
                return True
            else:
                try:
                    exec(code, globs, locs)
                except TypeError:
                    return False
                else:
                    if fails_under_py3k:
                        self.fail("Didn't raise TypeError") 
Example 22
Project: learn_python3_spider   Author: wistbean   File: test_declarations.py    License: MIT License 6 votes vote down vote up
def test_called_from_function(self):
        import warnings
        from zope.interface.declarations import implements
        from zope.interface.interface import InterfaceClass
        IFoo = InterfaceClass("IFoo")
        globs = {'implements': implements, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'def foo():',
            '    implements(IFoo)'
            ])
        if self._run_generated_code(CODE, globs, locs, False):
            foo = locs['foo']
            with warnings.catch_warnings(record=True) as log:
                warnings.resetwarnings()
                self.assertRaises(TypeError, foo)
                self.assertEqual(len(log), 0) # no longer warn 
Example 23
Project: learn_python3_spider   Author: wistbean   File: test_declarations.py    License: MIT License 6 votes vote down vote up
def test_called_twice_from_class(self):
        import warnings
        from zope.interface.declarations import implements
        from zope.interface.interface import InterfaceClass
        from zope.interface._compat import PYTHON3
        IFoo = InterfaceClass("IFoo")
        IBar = InterfaceClass("IBar")
        globs = {'implements': implements, 'IFoo': IFoo, 'IBar': IBar}
        locs = {}
        CODE = "\n".join([
            'class Foo(object):',
            '    implements(IFoo)',
            '    implements(IBar)',
            ])
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            try:
                exec(CODE, globs, locs)
            except TypeError:
                if not PYTHON3:
                    self.assertEqual(len(log), 0) # no longer warn
            else:
                self.fail("Didn't raise TypeError") 
Example 24
Project: learn_python3_spider   Author: wistbean   File: test_declarations.py    License: MIT License 6 votes vote down vote up
def test_called_from_function(self):
        import warnings
        from zope.interface.declarations import classProvides
        from zope.interface.interface import InterfaceClass
        from zope.interface._compat import PYTHON3
        IFoo = InterfaceClass("IFoo")
        globs = {'classProvides': classProvides, 'IFoo': IFoo}
        locs = {}
        CODE = "\n".join([
            'def foo():',
            '    classProvides(IFoo)'
            ])
        exec(CODE, globs, locs)
        foo = locs['foo']
        with warnings.catch_warnings(record=True) as log:
            warnings.resetwarnings()
            self.assertRaises(TypeError, foo)
            if not PYTHON3:
                self.assertEqual(len(log), 0) # no longer warn 
Example 25
Project: serval   Author: mzechmeister   File: read_spec.py    License: MIT License 6 votes vote down vote up
def write_res(filename, datas, extnames, header='', hdrref=None, clobber=False):
   if not header and hdrref: header = pyfits.getheader(hdrref)
   hdu = pyfits.PrimaryHDU(header=header)
   warnings.resetwarnings() # supress nasty overwrite warning http://pythonhosted.org/pyfits/users_guide/users_misc.html
   warnings.filterwarnings('ignore', category=UserWarning, append=True)
   hdu.writeto(filename, clobber=clobber, output_verify='fix')
   warnings.resetwarnings()
   warnings.filterwarnings('always', category=UserWarning, append=True)

   for i,extname in enumerate(extnames):
     data = datas[extname]
     if isinstance(data, np.ndarray):
        pyfits.append(filename, data)
     else:
        1/0

     pyfits.setval(filename, 'EXTNAME', value=extname, ext=i+1)
   #fitsio.write(filename, flux) 
Example 26
Project: MARA_Framework   Author: xtiankisutsa   File: test_core.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_setupterm_singleton_issue33():
    "A warning is emitted if a new terminal ``kind`` is used per process."
    @as_subprocess
    def child():
        warnings.filterwarnings("error", category=UserWarning)

        # instantiate first terminal, of type xterm-256color
        term = TestTerminal(force_styling=True)

        try:
            # a second instantiation raises UserWarning
            term = TestTerminal(kind="vt220", force_styling=True)
        except UserWarning:
            err = sys.exc_info()[1]
            assert (err.args[0].startswith(
                    'A terminal of kind "vt220" has been requested')
                    ), err.args[0]
            assert ('a terminal of kind "xterm-256color" will '
                    'continue to be returned' in err.args[0]), err.args[0]
        else:
            # unless term is not a tty and setupterm() is not called
            assert not term.is_a_tty or False, 'Should have thrown exception'
        warnings.resetwarnings()

    child() 
Example 27
Project: MARA_Framework   Author: xtiankisutsa   File: test_core.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_setupterm_invalid_issue39():
    "A warning is emitted if TERM is invalid."
    # https://bugzilla.mozilla.org/show_bug.cgi?id=878089

    # if TERM is unset, defaults to 'unknown', which should
    # fail to lookup and emit a warning, only.
    @as_subprocess
    def child():
        warnings.filterwarnings("error", category=UserWarning)

        try:
            term = TestTerminal(kind='unknown', force_styling=True)
        except UserWarning:
            err = sys.exc_info()[1]
            assert err.args[0] == 'Failed to setupterm(kind=unknown)'
        else:
            assert not term.is_a_tty and not term.does_styling, (
                'Should have thrown exception')
        warnings.resetwarnings()

    child() 
Example 28
Project: MARA_Framework   Author: xtiankisutsa   File: test_core.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_setupterm_invalid_has_no_styling():
    "An unknown TERM type does not perform styling."
    # https://bugzilla.mozilla.org/show_bug.cgi?id=878089

    # if TERM is unset, defaults to 'unknown', which should
    # fail to lookup and emit a warning, only.
    @as_subprocess
    def child():
        warnings.filterwarnings("ignore", category=UserWarning)

        term = TestTerminal(kind='unknown', force_styling=True)
        assert term._kind is None
        assert term.does_styling is False
        assert term.number_of_colors == 0
        warnings.resetwarnings()

    child() 
Example 29
Project: MARA_Framework   Author: xtiankisutsa   File: test_sequences.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_emit_warnings_about_binpacked(unsupported_sequence_terminals):
    """Test known binary-packed terminals (kermit, avatar) emit a warning."""
    @as_subprocess
    def child(kind):
        import warnings
        from blessed.sequences import _BINTERM_UNSUPPORTED_MSG
        warnings.filterwarnings("error", category=RuntimeWarning)
        warnings.filterwarnings("error", category=UserWarning)

        try:
            TestTerminal(kind=kind, force_styling=True)
        except UserWarning:
            err = sys.exc_info()[1]
            assert (err.args[0] == _BINTERM_UNSUPPORTED_MSG or
                    err.args[0].startswith('Unknown parameter in ')
                    ), err
        else:
            assert 'warnings should have been emitted.'
        warnings.resetwarnings()

    child(unsupported_sequence_terminals) 
Example 30
Project: MARA_Framework   Author: xtiankisutsa   File: test_sequences.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_unit_binpacked_unittest(unsupported_sequence_terminals):
    """Unit Test known binary-packed terminals emit a warning (travis-safe)."""
    import warnings
    from blessed.sequences import (_BINTERM_UNSUPPORTED_MSG,
                                   init_sequence_patterns)
    warnings.filterwarnings("error", category=UserWarning)
    term = mock.Mock()
    term._kind = unsupported_sequence_terminals

    try:
        init_sequence_patterns(term)
    except UserWarning:
        err = sys.exc_info()[1]
        assert err.args[0] == _BINTERM_UNSUPPORTED_MSG
    else:
        assert False, 'Previous stmt should have raised exception.'
    warnings.resetwarnings()