Skip to content

Commit

Permalink
Context manager to disable logging
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoddemus committed Jun 10, 2015
1 parent b04367f commit 46961ed
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 4 deletions.
32 changes: 32 additions & 0 deletions pytestqt/_tests/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
25 changes: 21 additions & 4 deletions pytestqt/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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


Expand All @@ -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')

Expand Down

0 comments on commit 46961ed

Please sign in to comment.