From 64f208486e6244a543f94c42afb1481ec1b563e4 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Sat, 23 Jul 2016 13:04:45 +0200 Subject: [PATCH] Add log.ignore_py_warnings() --- qutebrowser/utils/log.py | 15 ++++++++++++++- tests/unit/utils/test_log.py | 13 +++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/qutebrowser/utils/log.py b/qutebrowser/utils/log.py index 76d8e0dc7..a1210caf0 100644 --- a/qutebrowser/utils/log.py +++ b/qutebrowser/utils/log.py @@ -167,9 +167,14 @@ def init_log(args): root.addHandler(ram) root.setLevel(logging.NOTSET) logging.captureWarnings(True) + _init_py_warnings() + QtCore.qInstallMessageHandler(qt_message_handler) + + +def _init_py_warnings(): + """Initialize Python warning handling.""" warnings.simplefilter('default') warnings.filterwarnings('ignore', module='pdb', category=ResourceWarning) - QtCore.qInstallMessageHandler(qt_message_handler) @contextlib.contextmanager @@ -182,6 +187,14 @@ def disable_qt_msghandler(): QtCore.qInstallMessageHandler(old_handler) +@contextlib.contextmanager +def ignore_py_warnings(**kwargs): + """Contextmanager to temporarily hke certain Python warnings.""" + warnings.filterwarnings('ignore', **kwargs) + yield + _init_py_warnings() + + def _init_handlers(level, color, force_color, json_logging, ram_capacity): """Init log handlers. diff --git a/tests/unit/utils/test_log.py b/tests/unit/utils/test_log.py index 5554717d9..4bf12c526 100644 --- a/tests/unit/utils/test_log.py +++ b/tests/unit/utils/test_log.py @@ -23,6 +23,7 @@ import logging import argparse import itertools import sys +import warnings import pytest import pytest_catchlog @@ -36,6 +37,7 @@ def restore_loggers(): Based on CPython's Lib/test/test_logging.py. """ + logging.captureWarnings(False) logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: @@ -278,3 +280,14 @@ def test_stub(caplog, suffix, expected): log.stub(suffix) assert len(caplog.records) == 1 assert caplog.records[0].message == expected + + +def test_ignore_py_warnings(caplog): + logging.captureWarnings(True) + with log.ignore_py_warnings(category=UserWarning): + warnings.warn("hidden", UserWarning) + with caplog.at_level(logging.WARNING): + warnings.warn("not hidden", UserWarning) + assert len(caplog.records) == 1 + msg = caplog.records[0].message.splitlines()[0] + assert msg.endswith("UserWarning: not hidden")