Python warnings.WarningMessage() Examples

The following are 30 code examples for showing how to use warnings.WarningMessage(). 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: plugin.video.emby   Author: MediaBrowser   File: _common.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __enter__(self, *args, **kwargs):
            rv = super(WarningTestMixin._AssertWarnsContext, self).__enter__(*args, **kwargs)

            if self._showwarning is not self._module.showwarning:
                super_showwarning = self._module.showwarning
            else:
                super_showwarning = None

            def showwarning(*args, **kwargs):
                if super_showwarning is not None:
                    super_showwarning(*args, **kwargs)

                self._warning_log.append(warnings.WarningMessage(*args, **kwargs))

            self._module.showwarning = showwarning
            return rv 
Example 2
Project: Conditional_Density_Estimation   Author: freelunchtheorem   File: BaseNNEstimator.py    License: MIT License 6 votes vote down vote up
def _add_l1_l2_regularization(self, core_network):
        if self.l1_reg > 0 or self.l2_reg > 0:

            # weight norm should not be combined with l1 / l2 regularization
            if self.weight_normalization is True:
                warnings.WarningMessage("l1 / l2 regularization has no effect when weigh normalization is used")

            weight_vector = tf.concat(
                [tf.reshape(param, (-1,)) for param in core_network.get_params_internal() if '/W' in param.name],
                axis=0)
            if self.l2_reg > 0:
                self.l2_reg_loss = self.l2_reg * tf.reduce_sum(weight_vector ** 2)
                tf.losses.add_loss(self.l2_reg_loss, tf.GraphKeys.REGULARIZATION_LOSSES)
            if self.l1_reg > 0:
                self.l1_reg_loss = self.l1_reg * tf.reduce_sum(tf.abs(weight_vector))
                tf.losses.add_loss(self.l1_reg_loss, tf.GraphKeys.REGULARIZATION_LOSSES) 
Example 3
Project: megaman   Author: mmp2   File: testing.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __enter__(self):
        clean_warning_registry()  # be safe and not propagate state + chaos
        warnings.simplefilter('always')
        if self._entered:
            raise RuntimeError("Cannot enter %r twice" % self)
        self._entered = True
        self._filters = self._module.filters
        self._module.filters = self._filters[:]
        self._showwarning = self._module.showwarning
        if self._record:
            self.log = []

            def showwarning(*args, **kwargs):
                self.log.append(warnings.WarningMessage(*args, **kwargs))
            self._module.showwarning = showwarning
            return self.log
        else:
            return None 
Example 4
Project: bazarr   Author: morpheus65535   File: _common.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __enter__(self, *args, **kwargs):
            rv = super(WarningTestMixin._AssertWarnsContext, self).__enter__(*args, **kwargs)

            if self._showwarning is not self._module.showwarning:
                super_showwarning = self._module.showwarning
            else:
                super_showwarning = None

            def showwarning(*args, **kwargs):
                if super_showwarning is not None:
                    super_showwarning(*args, **kwargs)

                self._warning_log.append(warnings.WarningMessage(*args, **kwargs))

            self._module.showwarning = showwarning
            return rv 
Example 5
Project: python-netsurv   Author: sofia-netsurv   File: warnings.py    License: MIT License 5 votes vote down vote up
def warning_record_to_str(warning_message):
    """Convert a warnings.WarningMessage to a string."""
    warn_msg = warning_message.message
    msg = warnings.formatwarning(
        warn_msg,
        warning_message.category,
        warning_message.filename,
        warning_message.lineno,
        warning_message.line,
    )
    return msg 
Example 6
Project: python-netsurv   Author: sofia-netsurv   File: warnings.py    License: MIT License 5 votes vote down vote up
def warning_record_to_str(warning_message):
    """Convert a warnings.WarningMessage to a string."""
    warn_msg = warning_message.message
    msg = warnings.formatwarning(
        warn_msg,
        warning_message.category,
        warning_message.filename,
        warning_message.lineno,
        warning_message.line,
    )
    return msg 
Example 7
Project: pytest   Author: pytest-dev   File: hookspec.py    License: MIT License 5 votes vote down vote up
def pytest_warning_captured(
    warning_message: "warnings.WarningMessage",
    when: "Literal['config', 'collect', 'runtest']",
    item: Optional["Item"],
    location: Optional[Tuple[str, int, str]],
) -> None:
    """(**Deprecated**) Process a warning captured by the internal pytest warnings plugin.

    .. deprecated:: 6.0

    This hook is considered deprecated and will be removed in a future pytest version.
    Use :func:`pytest_warning_recorded` instead.

    :param warnings.WarningMessage warning_message:
        The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
        the same attributes as the parameters of :py:func:`warnings.showwarning`.

    :param str when:
        Indicates when the warning was captured. Possible values:

        * ``"config"``: during pytest configuration/initialization stage.
        * ``"collect"``: during test collection.
        * ``"runtest"``: during test execution.

    :param pytest.Item|None item:
        The item being executed if ``when`` is ``"runtest"``, otherwise ``None``.

    :param tuple location:
        When available, holds information about the execution context of the captured
        warning (filename, linenumber, function). ``function`` evaluates to <module>
        when the execution context is at the module level.
    """ 
Example 8
Project: pytest   Author: pytest-dev   File: hookspec.py    License: MIT License 5 votes vote down vote up
def pytest_warning_recorded(
    warning_message: "warnings.WarningMessage",
    when: "Literal['config', 'collect', 'runtest']",
    nodeid: str,
    location: Optional[Tuple[str, int, str]],
) -> None:
    """
    Process a warning captured by the internal pytest warnings plugin.

    :param warnings.WarningMessage warning_message:
        The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
        the same attributes as the parameters of :py:func:`warnings.showwarning`.

    :param str when:
        Indicates when the warning was captured. Possible values:

        * ``"config"``: during pytest configuration/initialization stage.
        * ``"collect"``: during test collection.
        * ``"runtest"``: during test execution.

    :param str nodeid: full id of the item

    :param tuple|None location:
        When available, holds information about the execution context of the captured
        warning (filename, linenumber, function). ``function`` evaluates to <module>
        when the execution context is at the module level.

    .. versionadded:: 6.0
    """


# -------------------------------------------------------------------------
# error handling and internal debugging hooks
# ------------------------------------------------------------------------- 
Example 9
Project: pytest   Author: pytest-dev   File: terminal.py    License: MIT License 5 votes vote down vote up
def pytest_warning_recorded(
        self, warning_message: warnings.WarningMessage, nodeid: str,
    ) -> None:
        from _pytest.warnings import warning_record_to_str

        fslocation = warning_message.filename, warning_message.lineno
        message = warning_record_to_str(warning_message)

        warning_report = WarningReport(
            fslocation=fslocation, message=message, nodeid=nodeid
        )
        self._add_stats("warnings", [warning_report]) 
Example 10
Project: pytest   Author: pytest-dev   File: warnings.py    License: MIT License 5 votes vote down vote up
def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:
    """Convert a warnings.WarningMessage to a string."""
    warn_msg = warning_message.message
    msg = warnings.formatwarning(
        str(warn_msg),
        warning_message.category,
        warning_message.filename,
        warning_message.lineno,
        warning_message.line,
    )
    return msg 
Example 11
Project: pytest   Author: pytest-dev   File: recwarn.py    License: MIT License 5 votes vote down vote up
def deprecated_call(  # noqa: F811
    func: Optional[Callable] = None, *args: Any, **kwargs: Any
) -> Union["WarningsRecorder", Any]:
    """Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning``.

    This function can be used as a context manager::

        >>> import warnings
        >>> def api_call_v2():
        ...     warnings.warn('use v3 of this api', DeprecationWarning)
        ...     return 200

        >>> with deprecated_call():
        ...    assert api_call_v2() == 200

    It can also be used by passing a function and ``*args`` and ``**kwargs``,
    in which case it will ensure calling ``func(*args, **kwargs)`` produces one of
    the warnings types above. The return value is the return value of the function.

    In the context manager form you may use the keyword argument ``match`` to assert
    that the warning matches a text or regex.

    The context manager produces a list of :class:`warnings.WarningMessage` objects,
    one for each warning raised.
    """
    __tracebackhide__ = True
    if func is not None:
        args = (func,) + args
    return warns((DeprecationWarning, PendingDeprecationWarning), *args, **kwargs) 
Example 12
Project: pytest   Author: pytest-dev   File: recwarn.py    License: MIT License 5 votes vote down vote up
def __init__(self) -> None:
        # Type ignored due to the way typeshed handles warnings.catch_warnings.
        super().__init__(record=True)  # type: ignore[call-arg] # noqa: F821
        self._entered = False
        self._list = []  # type: List[warnings.WarningMessage] 
Example 13
Project: pytest   Author: pytest-dev   File: recwarn.py    License: MIT License 5 votes vote down vote up
def list(self) -> List["warnings.WarningMessage"]:
        """The list of recorded warnings."""
        return self._list 
Example 14
Project: pytest   Author: pytest-dev   File: recwarn.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, i: int) -> "warnings.WarningMessage":
        """Get a recorded warning by index."""
        return self._list[i] 
Example 15
Project: pytest   Author: pytest-dev   File: recwarn.py    License: MIT License 5 votes vote down vote up
def __iter__(self) -> Iterator["warnings.WarningMessage"]:
        """Iterate through the recorded warnings."""
        return iter(self._list) 
Example 16
Project: pytest   Author: pytest-dev   File: recwarn.py    License: MIT License 5 votes vote down vote up
def pop(self, cls: "Type[Warning]" = Warning) -> "warnings.WarningMessage":
        """Pop the first recorded warning, raise exception if not exists."""
        for i, w in enumerate(self._list):
            if issubclass(w.category, cls):
                return self._list.pop(i)
        __tracebackhide__ = True
        raise AssertionError("%r not found in warning list" % cls) 
Example 17
Project: pytest-xdist   Author: pytest-dev   File: workermanage.py    License: MIT License 5 votes vote down vote up
def unserialize_warning_message(data):
    import warnings
    import importlib

    if data["message_module"]:
        mod = importlib.import_module(data["message_module"])
        cls = getattr(mod, data["message_class_name"])
        message = None
        if data["message_args"] is not None:
            try:
                message = cls(*data["message_args"])
            except TypeError:
                pass
        if message is None:
            # could not recreate the original warning instance;
            # create a generic Warning instance with the original
            # message at least
            message_text = "{mod}.{cls}: {msg}".format(
                mod=data["message_module"],
                cls=data["message_class_name"],
                msg=data["message_str"],
            )
            message = Warning(message_text)
    else:
        message = data["message_str"]

    if data["category_module"]:
        mod = importlib.import_module(data["category_module"])
        category = getattr(mod, data["category_class_name"])
    else:
        category = None

    kwargs = {"message": message, "category": category}
    # access private _WARNING_DETAILS because the attributes vary between Python versions
    for attr_name in warnings.WarningMessage._WARNING_DETAILS:
        if attr_name in ("message", "category"):
            continue
        kwargs[attr_name] = data[attr_name]

    return warnings.WarningMessage(**kwargs) 
Example 18
Project: Tautulli   Author: Tautulli   File: test_states.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_safe_wait_INADDR_ANY(self):
        """
        Wait on INADDR_ANY should not raise IOError

        In cases where the loopback interface does not exist, CherryPy cannot
        effectively determine if a port binding to INADDR_ANY was effected.
        In this situation, CherryPy should assume that it failed to detect
        the binding (not that the binding failed) and only warn that it could
        not verify it.
        """
        # At such a time that CherryPy can reliably determine one or more
        #  viable IP addresses of the host, this test may be removed.

        # Simulate the behavior we observe when no loopback interface is
        #  present by: finding a port that's not occupied, then wait on it.

        free_port = portend.find_available_local_port()

        servers = cherrypy.process.servers

        inaddr_any = '0.0.0.0'

        # Wait on the free port that's unbound
        with warnings.catch_warnings(record=True) as w:
            with servers._safe_wait(inaddr_any, free_port):
                portend.occupied(inaddr_any, free_port, timeout=1)
            self.assertEqual(len(w), 1)
            self.assertTrue(isinstance(w[0], warnings.WarningMessage))
            self.assertTrue(
                'Unable to verify that the server is bound on ' in str(w[0]))

        # The wait should still raise an IO error if INADDR_ANY was
        #  not supplied.
        with pytest.raises(IOError):
            with servers._safe_wait('127.0.0.1', free_port):
                portend.occupied('127.0.0.1', free_port, timeout=1) 
Example 19
Project: recruit   Author: Frank-qlu   File: utils.py    License: Apache License 2.0 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                     *args, **kwargs):
        use_warnmsg = kwargs.pop("use_warnmsg", None)
        for cat, _, pattern, mod, rec in (
                self._suppressions + self._tmp_suppressions)[::-1]:
            if (issubclass(category, cat) and
                    pattern.match(message.args[0]) is not None):
                if mod is None:
                    # Message and category match, either recorded or ignored
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return
                # Use startswith, because warnings strips the c or o from
                # .pyc/.pyo files.
                elif mod.__file__.startswith(filename):
                    # The message and module (filename) match
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return

        # There is no filter in place, so pass to the outside handler
        # unless we should only pass it once
        if self._forwarding_rule == "always":
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno,
                                *args, **kwargs)
            else:
                self._orig_showmsg(use_warnmsg)
            return

        if self._forwarding_rule == "once":
            signature = (message.args, category)
        elif self._forwarding_rule == "module":
            signature = (message.args, category, filename)
        elif self._forwarding_rule == "location":
            signature = (message.args, category, filename, lineno)

        if signature in self._forwarded:
            return
        self._forwarded.add(signature)
        if use_warnmsg is None:
            self._orig_show(message, category, filename, lineno, *args,
                            **kwargs)
        else:
            self._orig_showmsg(use_warnmsg) 
Example 20
Project: python-netsurv   Author: sofia-netsurv   File: recwarn.py    License: MIT License 4 votes vote down vote up
def warns(expected_warning, *args, **kwargs):
    r"""Assert that code raises a particular class of warning.

    Specifically, the parameter ``expected_warning`` can be a warning class or
    sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or
    classes.

    This helper produces a list of :class:`warnings.WarningMessage` objects,
    one for each warning raised.

    This function can be used as a context manager, or any of the other ways
    ``pytest.raises`` can be used::

        >>> with warns(RuntimeWarning):
        ...    warnings.warn("my warning", RuntimeWarning)

    In the context manager form you may use the keyword argument ``match`` to assert
    that the exception matches a text or regex::

        >>> with warns(UserWarning, match='must be 0 or None'):
        ...     warnings.warn("value must be 0 or None", UserWarning)

        >>> with warns(UserWarning, match=r'must be \d+$'):
        ...     warnings.warn("value must be 42", UserWarning)

        >>> with warns(UserWarning, match=r'must be \d+$'):
        ...     warnings.warn("this is not here", UserWarning)
        Traceback (most recent call last):
          ...
        Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...

    """
    __tracebackhide__ = True
    if not args:
        match_expr = kwargs.pop("match", None)
        if kwargs:
            warnings.warn(
                PYTEST_WARNS_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=2
            )
        return WarningsChecker(expected_warning, match_expr=match_expr)
    elif isinstance(args[0], str):
        warnings.warn(WARNS_EXEC, stacklevel=2)
        code, = args
        assert isinstance(code, str)
        frame = sys._getframe(1)
        loc = frame.f_locals.copy()
        loc.update(kwargs)

        with WarningsChecker(expected_warning):
            code = _pytest._code.Source(code).compile()
            exec(code, frame.f_globals, loc)
    else:
        func = args[0]
        with WarningsChecker(expected_warning):
            return func(*args[1:], **kwargs) 
Example 21
Project: python-netsurv   Author: sofia-netsurv   File: recwarn.py    License: MIT License 4 votes vote down vote up
def warns(expected_warning, *args, **kwargs):
    r"""Assert that code raises a particular class of warning.

    Specifically, the parameter ``expected_warning`` can be a warning class or
    sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or
    classes.

    This helper produces a list of :class:`warnings.WarningMessage` objects,
    one for each warning raised.

    This function can be used as a context manager, or any of the other ways
    ``pytest.raises`` can be used::

        >>> with warns(RuntimeWarning):
        ...    warnings.warn("my warning", RuntimeWarning)

    In the context manager form you may use the keyword argument ``match`` to assert
    that the exception matches a text or regex::

        >>> with warns(UserWarning, match='must be 0 or None'):
        ...     warnings.warn("value must be 0 or None", UserWarning)

        >>> with warns(UserWarning, match=r'must be \d+$'):
        ...     warnings.warn("value must be 42", UserWarning)

        >>> with warns(UserWarning, match=r'must be \d+$'):
        ...     warnings.warn("this is not here", UserWarning)
        Traceback (most recent call last):
          ...
        Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...

    """
    __tracebackhide__ = True
    if not args:
        match_expr = kwargs.pop("match", None)
        if kwargs:
            warnings.warn(
                PYTEST_WARNS_UNKNOWN_KWARGS.format(args=sorted(kwargs)), stacklevel=2
            )
        return WarningsChecker(expected_warning, match_expr=match_expr)
    elif isinstance(args[0], str):
        warnings.warn(WARNS_EXEC, stacklevel=2)
        code, = args
        assert isinstance(code, str)
        frame = sys._getframe(1)
        loc = frame.f_locals.copy()
        loc.update(kwargs)

        with WarningsChecker(expected_warning):
            code = _pytest._code.Source(code).compile()
            exec(code, frame.f_globals, loc)
    else:
        func = args[0]
        with WarningsChecker(expected_warning):
            return func(*args[1:], **kwargs) 
Example 22
Project: lambda-packs   Author: ryfeus   File: utils.py    License: MIT License 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                     *args, **kwargs):
        use_warnmsg = kwargs.pop("use_warnmsg", None)
        for cat, _, pattern, mod, rec in (
                self._suppressions + self._tmp_suppressions)[::-1]:
            if (issubclass(category, cat) and
                    pattern.match(message.args[0]) is not None):
                if mod is None:
                    # Message and category match, either recorded or ignored
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return
                # Use startswith, because warnings strips the c or o from
                # .pyc/.pyo files.
                elif mod.__file__.startswith(filename):
                    # The message and module (filename) match
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return

        # There is no filter in place, so pass to the outside handler
        # unless we should only pass it once
        if self._forwarding_rule == "always":
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno,
                                *args, **kwargs)
            else:
                self._orig_showmsg(use_warnmsg)
            return

        if self._forwarding_rule == "once":
            signature = (message.args, category)
        elif self._forwarding_rule == "module":
            signature = (message.args, category, filename)
        elif self._forwarding_rule == "location":
            signature = (message.args, category, filename, lineno)

        if signature in self._forwarded:
            return
        self._forwarded.add(signature)
        if use_warnmsg is None:
            self._orig_show(message, category, filename, lineno, *args,
                            **kwargs)
        else:
            self._orig_showmsg(use_warnmsg) 
Example 23
Project: lambda-packs   Author: ryfeus   File: _numpy_compat.py    License: MIT License 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                         *args, **kwargs):
            use_warnmsg = kwargs.pop("use_warnmsg", None)
            for cat, _, pattern, mod, rec in (
                    self._suppressions + self._tmp_suppressions)[::-1]:
                if (issubclass(category, cat) and
                        pattern.match(message.args[0]) is not None):
                    if mod is None:
                        # Message and category match, either recorded or ignored
                        if rec is not None:
                            msg = WarningMessage(message, category, filename,
                                                 lineno, **kwargs)
                            self.log.append(msg)
                            rec.append(msg)
                        return
                    # Use startswith, because warnings strips the c or o from
                    # .pyc/.pyo files.
                    elif mod.__file__.startswith(filename):
                        # The message and module (filename) match
                        if rec is not None:
                            msg = WarningMessage(message, category, filename,
                                                 lineno, **kwargs)
                            self.log.append(msg)
                            rec.append(msg)
                        return

            # There is no filter in place, so pass to the outside handler
            # unless we should only pass it once
            if self._forwarding_rule == "always":
                if use_warnmsg is None:
                    self._orig_show(message, category, filename, lineno,
                                    *args, **kwargs)
                else:
                    self._orig_showmsg(use_warnmsg)
                return

            if self._forwarding_rule == "once":
                signature = (message.args, category)
            elif self._forwarding_rule == "module":
                signature = (message.args, category, filename)
            elif self._forwarding_rule == "location":
                signature = (message.args, category, filename, lineno)

            if signature in self._forwarded:
                return
            self._forwarded.add(signature)
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno, *args,
                                **kwargs)
            else:
                self._orig_showmsg(use_warnmsg) 
Example 24
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: utils.py    License: MIT License 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                     *args, **kwargs):
        use_warnmsg = kwargs.pop("use_warnmsg", None)
        for cat, _, pattern, mod, rec in (
                self._suppressions + self._tmp_suppressions)[::-1]:
            if (issubclass(category, cat) and
                    pattern.match(message.args[0]) is not None):
                if mod is None:
                    # Message and category match, either recorded or ignored
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return
                # Use startswith, because warnings strips the c or o from
                # .pyc/.pyo files.
                elif mod.__file__.startswith(filename):
                    # The message and module (filename) match
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return

        # There is no filter in place, so pass to the outside handler
        # unless we should only pass it once
        if self._forwarding_rule == "always":
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno,
                                *args, **kwargs)
            else:
                self._orig_showmsg(use_warnmsg)
            return

        if self._forwarding_rule == "once":
            signature = (message.args, category)
        elif self._forwarding_rule == "module":
            signature = (message.args, category, filename)
        elif self._forwarding_rule == "location":
            signature = (message.args, category, filename, lineno)

        if signature in self._forwarded:
            return
        self._forwarded.add(signature)
        if use_warnmsg is None:
            self._orig_show(message, category, filename, lineno, *args,
                            **kwargs)
        else:
            self._orig_showmsg(use_warnmsg) 
Example 25
Project: GraphicDesignPatternByPython   Author: Relph1119   File: utils.py    License: MIT License 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                     *args, **kwargs):
        use_warnmsg = kwargs.pop("use_warnmsg", None)
        for cat, _, pattern, mod, rec in (
                self._suppressions + self._tmp_suppressions)[::-1]:
            if (issubclass(category, cat) and
                    pattern.match(message.args[0]) is not None):
                if mod is None:
                    # Message and category match, either recorded or ignored
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return
                # Use startswith, because warnings strips the c or o from
                # .pyc/.pyo files.
                elif mod.__file__.startswith(filename):
                    # The message and module (filename) match
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return

        # There is no filter in place, so pass to the outside handler
        # unless we should only pass it once
        if self._forwarding_rule == "always":
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno,
                                *args, **kwargs)
            else:
                self._orig_showmsg(use_warnmsg)
            return

        if self._forwarding_rule == "once":
            signature = (message.args, category)
        elif self._forwarding_rule == "module":
            signature = (message.args, category, filename)
        elif self._forwarding_rule == "location":
            signature = (message.args, category, filename, lineno)

        if signature in self._forwarded:
            return
        self._forwarded.add(signature)
        if use_warnmsg is None:
            self._orig_show(message, category, filename, lineno, *args,
                            **kwargs)
        else:
            self._orig_showmsg(use_warnmsg) 
Example 26
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _numpy_compat.py    License: MIT License 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                         *args, **kwargs):
            use_warnmsg = kwargs.pop("use_warnmsg", None)
            for cat, _, pattern, mod, rec in (
                    self._suppressions + self._tmp_suppressions)[::-1]:
                if (issubclass(category, cat) and
                        pattern.match(message.args[0]) is not None):
                    if mod is None:
                        # Message and category match, either recorded or ignored
                        if rec is not None:
                            msg = WarningMessage(message, category, filename,
                                                 lineno, **kwargs)
                            self.log.append(msg)
                            rec.append(msg)
                        return
                    # Use startswith, because warnings strips the c or o from
                    # .pyc/.pyo files.
                    elif mod.__file__.startswith(filename):
                        # The message and module (filename) match
                        if rec is not None:
                            msg = WarningMessage(message, category, filename,
                                                 lineno, **kwargs)
                            self.log.append(msg)
                            rec.append(msg)
                        return

            # There is no filter in place, so pass to the outside handler
            # unless we should only pass it once
            if self._forwarding_rule == "always":
                if use_warnmsg is None:
                    self._orig_show(message, category, filename, lineno,
                                    *args, **kwargs)
                else:
                    self._orig_showmsg(use_warnmsg)
                return

            if self._forwarding_rule == "once":
                signature = (message.args, category)
            elif self._forwarding_rule == "module":
                signature = (message.args, category, filename)
            elif self._forwarding_rule == "location":
                signature = (message.args, category, filename, lineno)

            if signature in self._forwarded:
                return
            self._forwarded.add(signature)
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno, *args,
                                **kwargs)
            else:
                self._orig_showmsg(use_warnmsg) 
Example 27
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: utils.py    License: Apache License 2.0 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                     *args, **kwargs):
        use_warnmsg = kwargs.pop("use_warnmsg", None)
        for cat, _, pattern, mod, rec in (
                self._suppressions + self._tmp_suppressions)[::-1]:
            if (issubclass(category, cat) and
                    pattern.match(message.args[0]) is not None):
                if mod is None:
                    # Message and category match, either recorded or ignored
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return
                # Use startswith, because warnings strips the c or o from
                # .pyc/.pyo files.
                elif mod.__file__.startswith(filename):
                    # The message and module (filename) match
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return

        # There is no filter in place, so pass to the outside handler
        # unless we should only pass it once
        if self._forwarding_rule == "always":
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno,
                                *args, **kwargs)
            else:
                self._orig_showmsg(use_warnmsg)
            return

        if self._forwarding_rule == "once":
            signature = (message.args, category)
        elif self._forwarding_rule == "module":
            signature = (message.args, category, filename)
        elif self._forwarding_rule == "location":
            signature = (message.args, category, filename, lineno)

        if signature in self._forwarded:
            return
        self._forwarded.add(signature)
        if use_warnmsg is None:
            self._orig_show(message, category, filename, lineno, *args,
                            **kwargs)
        else:
            self._orig_showmsg(use_warnmsg) 
Example 28
Project: pySINDy   Author: luckystarufo   File: utils.py    License: MIT License 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                     *args, **kwargs):
        use_warnmsg = kwargs.pop("use_warnmsg", None)
        for cat, _, pattern, mod, rec in (
                self._suppressions + self._tmp_suppressions)[::-1]:
            if (issubclass(category, cat) and
                    pattern.match(message.args[0]) is not None):
                if mod is None:
                    # Message and category match, either recorded or ignored
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return
                # Use startswith, because warnings strips the c or o from
                # .pyc/.pyo files.
                elif mod.__file__.startswith(filename):
                    # The message and module (filename) match
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return

        # There is no filter in place, so pass to the outside handler
        # unless we should only pass it once
        if self._forwarding_rule == "always":
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno,
                                *args, **kwargs)
            else:
                self._orig_showmsg(use_warnmsg)
            return

        if self._forwarding_rule == "once":
            signature = (message.args, category)
        elif self._forwarding_rule == "module":
            signature = (message.args, category, filename)
        elif self._forwarding_rule == "location":
            signature = (message.args, category, filename, lineno)

        if signature in self._forwarded:
            return
        self._forwarded.add(signature)
        if use_warnmsg is None:
            self._orig_show(message, category, filename, lineno, *args,
                            **kwargs)
        else:
            self._orig_showmsg(use_warnmsg) 
Example 29
Project: bazarr   Author: morpheus65535   File: test_states.py    License: GNU General Public License v3.0 4 votes vote down vote up
def test_wait_for_occupied_port_INADDR_ANY(self):
        """
        Wait on INADDR_ANY should not raise IOError

        In cases where the loopback interface does not exist, CherryPy cannot
        effectively determine if a port binding to INADDR_ANY was effected.
        In this situation, CherryPy should assume that it failed to detect
        the binding (not that the binding failed) and only warn that it could
        not verify it.
        """
        # At such a time that CherryPy can reliably determine one or more
        #  viable IP addresses of the host, this test may be removed.

        # Simulate the behavior we observe when no loopback interface is
        #  present by: finding a port that's not occupied, then wait on it.

        free_port = self.find_free_port()

        servers = cherrypy.process.servers

        def with_shorter_timeouts(func):
            """
            A context where occupied_port_timeout is much smaller to speed
            test runs.
            """
            # When we have Python 2.5, simplify using the with_statement.
            orig_timeout = servers.occupied_port_timeout
            servers.occupied_port_timeout = .07
            try:
                func()
            finally:
                servers.occupied_port_timeout = orig_timeout

        def do_waiting():
            # Wait on the free port that's unbound
            with warnings.catch_warnings(record=True) as w:
                servers.wait_for_occupied_port('0.0.0.0', free_port)
                self.assertEqual(len(w), 1)
                self.assertTrue(isinstance(w[0], warnings.WarningMessage))
                self.assertTrue(
                    'Unable to verify that the server is bound on ' in str(w[0]))

            # The wait should still raise an IO error if INADDR_ANY was
            #  not supplied.
            self.assertRaises(IOError, servers.wait_for_occupied_port,
                              '127.0.0.1', free_port)

        with_shorter_timeouts(do_waiting) 
Example 30
Project: coffeegrindsize   Author: jgagneastro   File: utils.py    License: MIT License 4 votes vote down vote up
def _showwarning(self, message, category, filename, lineno,
                     *args, **kwargs):
        use_warnmsg = kwargs.pop("use_warnmsg", None)
        for cat, _, pattern, mod, rec in (
                self._suppressions + self._tmp_suppressions)[::-1]:
            if (issubclass(category, cat) and
                    pattern.match(message.args[0]) is not None):
                if mod is None:
                    # Message and category match, either recorded or ignored
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return
                # Use startswith, because warnings strips the c or o from
                # .pyc/.pyo files.
                elif mod.__file__.startswith(filename):
                    # The message and module (filename) match
                    if rec is not None:
                        msg = WarningMessage(message, category, filename,
                                             lineno, **kwargs)
                        self.log.append(msg)
                        rec.append(msg)
                    return

        # There is no filter in place, so pass to the outside handler
        # unless we should only pass it once
        if self._forwarding_rule == "always":
            if use_warnmsg is None:
                self._orig_show(message, category, filename, lineno,
                                *args, **kwargs)
            else:
                self._orig_showmsg(use_warnmsg)
            return

        if self._forwarding_rule == "once":
            signature = (message.args, category)
        elif self._forwarding_rule == "module":
            signature = (message.args, category, filename)
        elif self._forwarding_rule == "location":
            signature = (message.args, category, filename, lineno)

        if signature in self._forwarded:
            return
        self._forwarded.add(signature)
        if use_warnmsg is None:
            self._orig_show(message, category, filename, lineno, *args,
                            **kwargs)
        else:
            self._orig_showmsg(use_warnmsg)