From 545d82a04d6ef37e74f292574ece9ef64e2c7d65 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Wed, 16 Sep 2015 22:37:25 +0200 Subject: [PATCH] utils.debug: Allow passing logger to log_time. --- qutebrowser/utils/debug.py | 5 ++++- tests/unit/utils/test_debug.py | 36 ++++++++++++++++++++++------------ 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/qutebrowser/utils/debug.py b/qutebrowser/utils/debug.py index 0939389c4..ba79a0341 100644 --- a/qutebrowser/utils/debug.py +++ b/qutebrowser/utils/debug.py @@ -21,6 +21,7 @@ import re import inspect +import logging import functools import datetime import contextlib @@ -229,9 +230,11 @@ def log_time(logger, action='operation'): """Log the time the operation in the with-block takes. Args: - logger: The logging.Logger to use for logging. + logger: The logging.Logger to use for logging, or a logger name. action: A description of what's being done. """ + if isinstance(logger, str): + logger = logging.getLogger(logger) started = datetime.datetime.now() try: yield diff --git a/tests/unit/utils/test_debug.py b/tests/unit/utils/test_debug.py index 72392e8dd..2b853140a 100644 --- a/tests/unit/utils/test_debug.py +++ b/tests/unit/utils/test_debug.py @@ -81,22 +81,34 @@ def test_log_signals(caplog, signal_obj): assert records[1].msg == "Signal in : signal2('foo', 'bar')" -def test_log_time(caplog): - logger_name = 'qt-tests' +class TestLogTime: - with caplog.atLevel(logging.DEBUG, logger_name): - with debug.log_time(logging.getLogger(logger_name), action='foobar'): - time.sleep(0.1) + def test_duration(self, caplog): + logger_name = 'qt-tests' - records = caplog.records() - assert len(records) == 1 + with caplog.atLevel(logging.DEBUG, logger_name): + with debug.log_time(logger_name, action='foobar'): + time.sleep(0.1) - pattern = re.compile(r'^Foobar took ([\d.]*) seconds\.$') - match = pattern.match(records[0].msg) - assert match + records = caplog.records() + assert len(records) == 1 - duration = float(match.group(1)) - assert 0 < duration < 5 + pattern = re.compile(r'^Foobar took ([\d.]*) seconds\.$') + match = pattern.match(records[0].msg) + assert match + + duration = float(match.group(1)) + assert 0 < duration < 5 + + def test_logger(self, caplog): + """Test with an explicit logger instead of a name.""" + logger_name = 'qt-tests' + + with caplog.atLevel(logging.DEBUG, logger_name): + with debug.log_time(logging.getLogger(logger_name)): + pass + + assert len(caplog.records()) == 1 class TestQEnumKey: