Python warnings.resetwarnings() Examples

The following are 30 code examples of warnings.resetwarnings(). 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 warnings , or try the search function .
Example #1
Source File: test_functional.py    From oss-ftp with 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 #2
Source File: test_sequences.py    From MARA_Framework with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_bna_parameter_emits_warning():
    """A fake capability without any digits emits a warning."""
    import warnings
    from blessed.sequences import _build_any_numeric_capability

    # given,
    warnings.filterwarnings("error", category=UserWarning)
    term = mock.Mock()
    fake_cap = lambda *args: 'NO-DIGIT'
    term.fake_cap = fake_cap

    # excersize,
    try:
        _build_any_numeric_capability(term, 'fake_cap')
    except UserWarning:
        err = sys.exc_info()[1]
        assert err.args[0].startswith('Missing numerics in ')
    else:
        assert False, 'Previous stmt should have raised exception.'
    warnings.resetwarnings() 
Example #3
Source File: test_optimizers.py    From lale with Apache License 2.0 6 votes vote down vote up
def test_with_concat_features2(self):
        import warnings
        warnings.filterwarnings("ignore")

        from sklearn.datasets import load_iris
        from lale.lib.lale import Hyperopt
        from sklearn.metrics import accuracy_score
        data = load_iris()
        X, y = data.data, data.target
        pca = PCA(n_components=3)
        nys = Nystroem(n_components=10)
        concat = ConcatFeatures()
        lr = LogisticRegression(random_state=42, C=0.1)
        from lale.operators import make_pipeline
        pipeline = make_pipeline(((((SimpleImputer() | NoOp()) >> pca) & nys) >> concat >> lr) | KNeighborsClassifier())
        clf = Hyperopt(estimator=pipeline, max_evals=1, handle_cv_failure=True)
        trained = clf.fit(X, y)
        predictions = trained.predict(X)
        print(accuracy_score(y, predictions))
        warnings.resetwarnings() 
Example #4
Source File: test_pep352.py    From gcblue with BSD 3-Clause "New" or "Revised" 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 #5
Source File: mysql_lib.py    From mysql_utils with 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
Source File: mysql_lib.py    From mysql_utils with 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 #7
Source File: mysql_lib.py    From mysql_utils with 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 #8
Source File: mysql_lib.py    From mysql_utils with 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 #9
Source File: test_declarations.py    From learn_python3_spider with 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 #10
Source File: statefbk_array_test.py    From python-control with 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 #11
Source File: test_sequences.py    From MARA_Framework with 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 #12
Source File: test_pep352.py    From BinderFilter with 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 #13
Source File: test_core.py    From MARA_Framework with 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 #14
Source File: test_core.py    From MARA_Framework with 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 #15
Source File: test_jams.py    From jams with 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 #16
Source File: test_core.py    From MARA_Framework with 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 #17
Source File: test_declarations.py    From learn_python3_spider with 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 #18
Source File: read_spec.py    From serval with 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 #19
Source File: test_functional.py    From oss-ftp with 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 #20
Source File: test_requests_aws4auth.py    From requests-aws4auth with 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 #21
Source File: test_pep352.py    From oss-ftp with 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 #22
Source File: test_declarations.py    From learn_python3_spider with 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 #23
Source File: test_declarations.py    From learn_python3_spider with 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 #24
Source File: test_declarations.py    From Safejumper-for-Desktop with GNU General Public License v2.0 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 #25
Source File: test_core.py    From deepWordBug with 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 #26
Source File: test_declarations.py    From Safejumper-for-Desktop with GNU General Public License v2.0 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 #27
Source File: test_declarations.py    From Safejumper-for-Desktop with GNU General Public License v2.0 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 #28
Source File: test_declarations.py    From Safejumper-for-Desktop with GNU General Public License v2.0 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 #29
Source File: test_core.py    From deepWordBug with 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 #30
Source File: test_core.py    From deepWordBug with 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()