Skip to content

Commit 46961ed

Browse files
committed
Context manager to disable logging
#56
1 parent b04367f commit 46961ed

File tree

2 files changed

+53
-4
lines changed

2 files changed

+53
-4
lines changed

pytestqt/_tests/test_logging.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,38 @@ def test_types(qtlog):
8787
res.stdout.fnmatch_lines('*1 passed*')
8888

8989

90+
@pytest.mark.parametrize('use_context_manager', [True, False])
91+
def test_disable_qtlog_context_manager(testdir, use_context_manager):
92+
"""
93+
Test qtlog.disabled() context manager.
94+
95+
:type testdir: _pytest.pytester.TmpTestdir
96+
"""
97+
testdir.makeini(
98+
"""
99+
[pytest]
100+
qt_log_level_fail = CRITICAL
101+
"""
102+
)
103+
104+
if use_context_manager:
105+
code = 'with qtlog.disabled():'
106+
else:
107+
code = 'if 1:'
108+
109+
testdir.makepyfile(
110+
"""
111+
from pytestqt.qt_compat import qCritical
112+
def test_1(qtlog):
113+
{code}
114+
qCritical('message')
115+
""".format(code=code)
116+
)
117+
res = testdir.inline_run()
118+
passed = 1 if use_context_manager else 0
119+
res.assertoutcome(passed=passed, failed=int(not passed))
120+
121+
90122
def test_logging_formatting(testdir):
91123
"""
92124
Test custom formatting for logging messages.

pytestqt/plugin.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -637,8 +637,7 @@ def pytest_runtest_setup(self, item):
637637
else:
638638
ignore_regexes = self.config.getini('qt_log_ignore')
639639
item.qt_log_capture = _QtMessageCapture(ignore_regexes)
640-
previous_handler = qInstallMsgHandler(item.qt_log_capture._handle)
641-
item.qt_previous_handler = previous_handler
640+
item.qt_log_capture._start()
642641

643642
@pytest.mark.hookwrapper
644643
def pytest_runtest_makereport(self, item, call):
@@ -682,8 +681,7 @@ def pytest_runtest_makereport(self, item, call):
682681
long_repr.addsection('Captured Qt messages',
683682
'\n'.join(lines))
684683

685-
qInstallMsgHandler(item.qt_previous_handler)
686-
del item.qt_previous_handler
684+
item.qt_log_capture._stop()
687685
del item.qt_log_capture
688686

689687

@@ -700,6 +698,25 @@ class _QtMessageCapture(object):
700698
def __init__(self, ignore_regexes):
701699
self._records = []
702700
self._ignore_regexes = ignore_regexes or []
701+
self._previous_handler = None
702+
703+
def _start(self):
704+
self._previous_handler = qInstallMsgHandler(self._handle)
705+
706+
def _stop(self):
707+
qInstallMsgHandler(self._previous_handler)
708+
709+
@contextmanager
710+
def disabled(self):
711+
"""
712+
Context manager that temporarily disables logging capture while
713+
inside it.
714+
"""
715+
self._stop()
716+
try:
717+
yield
718+
finally:
719+
self._start()
703720

704721
_Context = namedtuple('_Context', 'file function line')
705722

0 commit comments

Comments
 (0)