From 46961eda674fc854d8ece30b90ba447a1406d04e Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Mon, 8 Jun 2015 21:16:13 -0300 Subject: [PATCH] Context manager to disable logging #56 --- pytestqt/_tests/test_logging.py | 32 ++++++++++++++++++++++++++++++++ pytestqt/plugin.py | 25 +++++++++++++++++++++---- 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/pytestqt/_tests/test_logging.py b/pytestqt/_tests/test_logging.py index 96922e63..22edef59 100644 --- a/pytestqt/_tests/test_logging.py +++ b/pytestqt/_tests/test_logging.py @@ -87,6 +87,38 @@ def test_types(qtlog): res.stdout.fnmatch_lines('*1 passed*') +@pytest.mark.parametrize('use_context_manager', [True, False]) +def test_disable_qtlog_context_manager(testdir, use_context_manager): + """ + Test qtlog.disabled() context manager. + + :type testdir: _pytest.pytester.TmpTestdir + """ + testdir.makeini( + """ + [pytest] + qt_log_level_fail = CRITICAL + """ + ) + + if use_context_manager: + code = 'with qtlog.disabled():' + else: + code = 'if 1:' + + testdir.makepyfile( + """ + from pytestqt.qt_compat import qCritical + def test_1(qtlog): + {code} + qCritical('message') + """.format(code=code) + ) + res = testdir.inline_run() + passed = 1 if use_context_manager else 0 + res.assertoutcome(passed=passed, failed=int(not passed)) + + def test_logging_formatting(testdir): """ Test custom formatting for logging messages. diff --git a/pytestqt/plugin.py b/pytestqt/plugin.py index 44999bfe..8d386bfe 100644 --- a/pytestqt/plugin.py +++ b/pytestqt/plugin.py @@ -637,8 +637,7 @@ def pytest_runtest_setup(self, item): else: ignore_regexes = self.config.getini('qt_log_ignore') item.qt_log_capture = _QtMessageCapture(ignore_regexes) - previous_handler = qInstallMsgHandler(item.qt_log_capture._handle) - item.qt_previous_handler = previous_handler + item.qt_log_capture._start() @pytest.mark.hookwrapper def pytest_runtest_makereport(self, item, call): @@ -682,8 +681,7 @@ def pytest_runtest_makereport(self, item, call): long_repr.addsection('Captured Qt messages', '\n'.join(lines)) - qInstallMsgHandler(item.qt_previous_handler) - del item.qt_previous_handler + item.qt_log_capture._stop() del item.qt_log_capture @@ -700,6 +698,25 @@ class _QtMessageCapture(object): def __init__(self, ignore_regexes): self._records = [] self._ignore_regexes = ignore_regexes or [] + self._previous_handler = None + + def _start(self): + self._previous_handler = qInstallMsgHandler(self._handle) + + def _stop(self): + qInstallMsgHandler(self._previous_handler) + + @contextmanager + def disabled(self): + """ + Context manager that temporarily disables logging capture while + inside it. + """ + self._stop() + try: + yield + finally: + self._start() _Context = namedtuple('_Context', 'file function line')