tests: Switch from pytest-capturelog to catchlog.

This commit is contained in:
Florian Bruhin 2015-11-11 19:57:03 +01:00
parent a5efbe7412
commit 416cfaf002
20 changed files with 118 additions and 152 deletions

View File

@ -33,7 +33,7 @@ import pytest
import helpers.stubs as stubsmod import helpers.stubs as stubsmod
from helpers import logfail from helpers import logfail
from helpers.logfail import fail_on_logging, caplog_bug_workaround from helpers.logfail import fail_on_logging
from helpers.messagemock import message_mock from helpers.messagemock import message_mock
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.utils import objreg from qutebrowser.utils import objreg

View File

@ -24,7 +24,7 @@ import logging
import pytest import pytest
try: try:
import pytest_capturelog as caplog_mod import pytest_catchlog as catchlog_mod
except ImportError: except ImportError:
# When using pytest for pyflakes/pep8/..., the plugin won't be available # When using pytest for pyflakes/pep8/..., the plugin won't be available
# but conftest.py will still be loaded. # but conftest.py will still be loaded.
@ -47,18 +47,18 @@ class LogFailHandler(logging.Handler):
root_logger = logging.getLogger() root_logger = logging.getLogger()
for h in root_logger.handlers: for h in root_logger.handlers:
if isinstance(h, caplog_mod.CaptureLogHandler): if isinstance(h, catchlog_mod.LogCaptureHandler):
caplog_handler = h catchlog_handler = h
break break
else: else:
# The CaptureLogHandler is not available anymore during fixture # The LogCaptureHandler is not available anymore during fixture
# teardown, so we ignore logging messages emitted there.. # teardown, so we ignore logging messages emitted there..
return return
if (logger.level == record.levelno or if (logger.level == record.levelno or
caplog_handler.level == record.levelno): catchlog_handler.level == record.levelno):
# caplog.atLevel(...) was used with the level of this message, i.e. # caplog.at_level(...) was used with the level of this message,
# it was expected. # i.e. it was expected.
return return
if record.levelno < self._min_level: if record.levelno < self._min_level:
return return
@ -74,25 +74,3 @@ def fail_on_logging():
yield yield
logging.getLogger().removeHandler(handler) logging.getLogger().removeHandler(handler)
handler.close() handler.close()
@pytest.yield_fixture(autouse=True)
def caplog_bug_workaround(request):
"""WORKAROUND for pytest-capturelog bug.
https://bitbucket.org/memedough/pytest-capturelog/issues/7/
This would lead to LogFailHandler failing after skipped tests as there are
multiple CaptureLogHandlers.
"""
yield
if caplog_mod is None:
return
root_logger = logging.getLogger()
caplog_handlers = [h for h in root_logger.handlers
if isinstance(h, caplog_mod.CaptureLogHandler)]
for h in caplog_handlers:
root_logger.removeHandler(h)
h.close()

View File

@ -61,7 +61,7 @@ class MessageMock:
} }
log_level = log_levels[level] log_level = log_levels[level]
with self._caplog.atLevel(log_level): # needed so we don't fail with self._caplog.at_level(log_level): # needed so we don't fail
logging.getLogger('message').log(log_level, text) logging.getLogger('message').log(log_level, text)
self.messages.append(Message(level, win_id, text, immediately)) self.messages.append(Message(level, win_id, text, immediately))

View File

@ -23,7 +23,7 @@
import logging import logging
import pytest import pytest
import pytest_capturelog # pylint: disable=import-error import pytest_catchlog # pylint: disable=import-error
def test_log_debug(): def test_log_debug():
@ -36,33 +36,33 @@ def test_log_warning():
def test_log_expected(caplog): def test_log_expected(caplog):
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
logging.error('foo') logging.error('foo')
def test_log_expected_logger(caplog): def test_log_expected_logger(caplog):
logger = 'logfail_test_logger' logger = 'logfail_test_logger'
with caplog.atLevel(logging.ERROR, logger): with caplog.at_level(logging.ERROR, logger):
logging.getLogger(logger).error('foo') logging.getLogger(logger).error('foo')
def test_log_expected_wrong_level(caplog): def test_log_expected_wrong_level(caplog):
with pytest.raises(pytest.fail.Exception): with pytest.raises(pytest.fail.Exception):
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
logging.critical('foo') logging.critical('foo')
def test_log_expected_logger_wrong_level(caplog): def test_log_expected_logger_wrong_level(caplog):
logger = 'logfail_test_logger' logger = 'logfail_test_logger'
with pytest.raises(pytest.fail.Exception): with pytest.raises(pytest.fail.Exception):
with caplog.atLevel(logging.ERROR, logger): with caplog.at_level(logging.ERROR, logger):
logging.getLogger(logger).critical('foo') logging.getLogger(logger).critical('foo')
def test_log_expected_wrong_logger(caplog): def test_log_expected_wrong_logger(caplog):
logger = 'logfail_test_logger' logger = 'logfail_test_logger'
with pytest.raises(pytest.fail.Exception): with pytest.raises(pytest.fail.Exception):
with caplog.atLevel(logging.ERROR, logger): with caplog.at_level(logging.ERROR, logger):
logging.error('foo') logging.error('foo')
@ -82,6 +82,6 @@ def test_caplog_bug_workaround_2():
""" """
caplog_handler = None caplog_handler = None
for h in logging.getLogger().handlers: for h in logging.getLogger().handlers:
if isinstance(h, pytest_capturelog.CaptureLogHandler): if isinstance(h, pytest_catchlog.LogCaptureHandler):
assert caplog_handler is None assert caplog_handler is None
caplog_handler = h caplog_handler = h

View File

@ -55,7 +55,7 @@ class HeaderChecker:
"""Check if the passed header is ignored.""" """Check if the passed header is ignored."""
reply = self.stubs.FakeNetworkReply( reply = self.stubs.FakeNetworkReply(
headers={'Content-Disposition': header}) headers={'Content-Disposition': header})
with self.caplog.atLevel(logging.ERROR, 'rfc6266'): with self.caplog.at_level(logging.ERROR, 'rfc6266'):
# with self.assertLogs(log.rfc6266, logging.ERROR): # with self.assertLogs(log.rfc6266, logging.ERROR):
cd_inline, cd_filename = http.parse_content_disposition(reply) cd_inline, cd_filename = http.parse_content_disposition(reply)
assert cd_filename == DEFAULT_NAME assert cd_filename == DEFAULT_NAME

View File

@ -41,7 +41,7 @@ def test_parse_content_disposition(caplog, template, stubs, s):
"""Test parsing headers based on templates which hypothesis completes.""" """Test parsing headers based on templates which hypothesis completes."""
header = template.format(s) header = template.format(s)
reply = stubs.FakeNetworkReply(headers={'Content-Disposition': header}) reply = stubs.FakeNetworkReply(headers={'Content-Disposition': header})
with caplog.atLevel(logging.ERROR, 'rfc6266'): with caplog.at_level(logging.ERROR, 'rfc6266'):
http.parse_content_disposition(reply) http.parse_content_disposition(reply)

View File

@ -106,13 +106,12 @@ def test_logging(caplog, objects, tabbed_browser, index_of, verb):
tabbed_browser.current_index = 0 tabbed_browser.current_index = 0
tabbed_browser.index_of = index_of tabbed_browser.index_of = index_of
with caplog.atLevel(logging.DEBUG, logger='signals'): with caplog.at_level(logging.DEBUG, logger='signals'):
objects.signaller.signal.emit('foo') objects.signaller.signal.emit('foo')
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1
expected_msg = "{}: filtered_signal('foo') (tab {})".format(verb, index_of) expected_msg = "{}: filtered_signal('foo') (tab {})".format(verb, index_of)
assert records[0].msg == expected_msg assert caplog.records[0].msg == expected_msg
@pytest.mark.parametrize('index_of', [0, 1]) @pytest.mark.parametrize('index_of', [0, 1])
@ -120,10 +119,10 @@ def test_no_logging(caplog, objects, tabbed_browser, index_of):
tabbed_browser.current_index = 0 tabbed_browser.current_index = 0
tabbed_browser.index_of = index_of tabbed_browser.index_of = index_of
with caplog.atLevel(logging.DEBUG, logger='signals'): with caplog.at_level(logging.DEBUG, logger='signals'):
objects.signaller.statusbar_message.emit('foo') objects.signaller.statusbar_message.emit('foo')
assert not caplog.records() assert not caplog.records
def test_runtime_error(objects, tabbed_browser): def test_runtime_error(objects, tabbed_browser):

View File

@ -64,12 +64,11 @@ def test_set_register_stylesheet(delete, qtbot, config_stub, caplog):
config_stub.data = {'fonts': {'foo': 'bar'}, 'colors': {}} config_stub.data = {'fonts': {'foo': 'bar'}, 'colors': {}}
obj = Obj("{{ font['foo'] }}") obj = Obj("{{ font['foo'] }}")
with caplog.atLevel(9): # VDEBUG with caplog.at_level(9): # VDEBUG
style.set_register_stylesheet(obj) style.set_register_stylesheet(obj)
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1 assert caplog.records[0].message == 'stylesheet for Obj: bar'
assert records[0].message == 'stylesheet for Obj: bar'
assert obj.rendered_stylesheet == 'bar' assert obj.rendered_stylesheet == 'bar'
@ -104,11 +103,10 @@ class TestColorDict:
def test_key_error(self, caplog): def test_key_error(self, caplog):
d = style.ColorDict() d = style.ColorDict()
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
d['foo'] # pylint: disable=pointless-statement d['foo'] # pylint: disable=pointless-statement
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1 assert caplog.records[0].message == 'No color defined for foo!'
assert records[0].message == 'No color defined for foo!'
def test_qcolor(self): def test_qcolor(self):
d = style.ColorDict() d = style.ColorDict()

View File

@ -74,14 +74,14 @@ class TestDebugLog:
def test_log(self, keyparser, caplog): def test_log(self, keyparser, caplog):
keyparser._debug_log('foo') keyparser._debug_log('foo')
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
record = caplog.records()[0] record = caplog.records[0]
assert record.message == 'foo' assert record.message == 'foo'
def test_no_log(self, keyparser, caplog): def test_no_log(self, keyparser, caplog):
keyparser.do_log = False keyparser.do_log = False
keyparser._debug_log('foo') keyparser._debug_log('foo')
assert not caplog.records() assert not caplog.records
@pytest.mark.parametrize('input_key, supports_count, expected', [ @pytest.mark.parametrize('input_key, supports_count, expected', [
@ -161,10 +161,10 @@ class TestReadConfig:
0, supports_count=False, supports_chains=False) 0, supports_count=False, supports_chains=False)
kp._warn_on_keychains = warn_on_keychains kp._warn_on_keychains = warn_on_keychains
with caplog.atLevel(logging.WARNING): with caplog.at_level(logging.WARNING):
kp.read_config('normal') kp.read_config('normal')
assert bool(caplog.records()) == warn_on_keychains assert bool(caplog.records) == warn_on_keychains
class TestSpecialKeys: class TestSpecialKeys:

View File

@ -174,16 +174,16 @@ def test_start_logging(fake_proc, caplog):
"""Make sure that starting logs the executed commandline.""" """Make sure that starting logs the executed commandline."""
cmd = 'does_not_exist' cmd = 'does_not_exist'
args = ['arg', 'arg with spaces'] args = ['arg', 'arg with spaces']
with caplog.atLevel(logging.DEBUG): with caplog.at_level(logging.DEBUG):
fake_proc.start(cmd, args) fake_proc.start(cmd, args)
msgs = [e.msg for e in caplog.records()] msgs = [e.msg for e in caplog.records]
assert msgs == ["Starting process.", assert msgs == ["Starting process.",
"Executing: does_not_exist arg 'arg with spaces'"] "Executing: does_not_exist arg 'arg with spaces'"]
def test_error(qtbot, proc, caplog, guiprocess_message_mock): def test_error(qtbot, proc, caplog, guiprocess_message_mock):
"""Test the process emitting an error.""" """Test the process emitting an error."""
with caplog.atLevel(logging.ERROR, 'message'): with caplog.at_level(logging.ERROR, 'message'):
with qtbot.waitSignal(proc.error, raising=True, timeout=5000): with qtbot.waitSignal(proc.error, raising=True, timeout=5000):
proc.start('this_does_not_exist_either', []) proc.start('this_does_not_exist_either', [])

View File

@ -358,11 +358,10 @@ class TestListen:
@pytest.mark.posix @pytest.mark.posix
def test_atime_update_no_name(self, qtbot, caplog, ipc_server): def test_atime_update_no_name(self, qtbot, caplog, ipc_server):
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
ipc_server.update_atime() ipc_server.update_atime()
records = caplog.records() assert caplog.records[-1].msg == "In update_atime with no server path!"
assert records[-1].msg == "In update_atime with no server path!"
@pytest.mark.posix @pytest.mark.posix
def test_atime_shutdown_typeerror(self, qtbot, ipc_server): def test_atime_shutdown_typeerror(self, qtbot, ipc_server):
@ -408,22 +407,21 @@ class TestHandleConnection:
def test_no_connection(self, ipc_server, caplog): def test_no_connection(self, ipc_server, caplog):
ipc_server.handle_connection() ipc_server.handle_connection()
record = caplog.records()[-1] assert caplog.records[-1].message == "No new connection to handle."
assert record.message == "No new connection to handle."
def test_double_connection(self, qlocalsocket, ipc_server, caplog): def test_double_connection(self, qlocalsocket, ipc_server, caplog):
ipc_server._socket = qlocalsocket ipc_server._socket = qlocalsocket
ipc_server.handle_connection() ipc_server.handle_connection()
message = ("Got new connection but ignoring it because we're still " message = ("Got new connection but ignoring it because we're still "
"handling another one.") "handling another one.")
assert message in [rec.message for rec in caplog.records()] assert message in [rec.message for rec in caplog.records]
def test_disconnected_immediately(self, ipc_server, caplog): def test_disconnected_immediately(self, ipc_server, caplog):
socket = FakeSocket(state=QLocalSocket.UnconnectedState) socket = FakeSocket(state=QLocalSocket.UnconnectedState)
ipc_server._server = FakeServer(socket) ipc_server._server = FakeServer(socket)
ipc_server.handle_connection() ipc_server.handle_connection()
msg = "Socket was disconnected immediately." msg = "Socket was disconnected immediately."
all_msgs = [r.message for r in caplog.records()] all_msgs = [r.message for r in caplog.records]
assert msg in all_msgs assert msg in all_msgs
def test_error_immediately(self, ipc_server, caplog): def test_error_immediately(self, ipc_server, caplog):
@ -436,7 +434,7 @@ class TestHandleConnection:
exc_msg = 'Error while handling IPC connection: Error string (error 7)' exc_msg = 'Error while handling IPC connection: Error string (error 7)'
assert str(excinfo.value) == exc_msg assert str(excinfo.value) == exc_msg
msg = "We got an error immediately." msg = "We got an error immediately."
all_msgs = [r.message for r in caplog.records()] all_msgs = [r.message for r in caplog.records]
assert msg in all_msgs assert msg in all_msgs
def test_read_line_immediately(self, qtbot, ipc_server, caplog): def test_read_line_immediately(self, qtbot, ipc_server, caplog):
@ -454,7 +452,7 @@ class TestHandleConnection:
assert spy[0][0] == ['foo'] assert spy[0][0] == ['foo']
assert spy[0][1] == 'tab' assert spy[0][1] == 'tab'
all_msgs = [r.message for r in caplog.records()] all_msgs = [r.message for r in caplog.records]
assert "We can read a line immediately." in all_msgs assert "We can read a line immediately." in all_msgs
@ -505,11 +503,11 @@ def test_invalid_data(qtbot, ipc_server, connected_socket, caplog, data, msg):
got_args_spy = QSignalSpy(ipc_server.got_args) got_args_spy = QSignalSpy(ipc_server.got_args)
signals = [ipc_server.got_invalid_data, connected_socket.disconnected] signals = [ipc_server.got_invalid_data, connected_socket.disconnected]
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
with qtbot.waitSignals(signals, raising=True): with qtbot.waitSignals(signals, raising=True):
connected_socket.write(data) connected_socket.write(data)
messages = [r.message for r in caplog.records()] messages = [r.message for r in caplog.records]
assert messages[-1] == 'Ignoring invalid IPC data.' assert messages[-1] == 'Ignoring invalid IPC data.'
assert messages[-2].startswith(msg) assert messages[-2].startswith(msg)
assert not got_args_spy assert not got_args_spy
@ -542,7 +540,7 @@ class TestSendToRunningInstance:
def test_no_server(self, caplog): def test_no_server(self, caplog):
sent = ipc.send_to_running_instance('qute-test', [], None) sent = ipc.send_to_running_instance('qute-test', [], None)
assert not sent assert not sent
msg = caplog.records()[-1].message msg = caplog.records[-1].message
assert msg == "No existing instance present (error 2)" assert msg == "No existing instance present (error 2)"
@pytest.mark.parametrize('has_cwd', [True, False]) @pytest.mark.parametrize('has_cwd', [True, False])
@ -610,12 +608,12 @@ def test_timeout(qtbot, caplog, qlocalsocket, ipc_server):
with qtbot.waitSignal(ipc_server._server.newConnection, raising=True): with qtbot.waitSignal(ipc_server._server.newConnection, raising=True):
qlocalsocket.connectToServer('qute-test') qlocalsocket.connectToServer('qute-test')
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
with qtbot.waitSignal(qlocalsocket.disconnected, raising=True, with qtbot.waitSignal(qlocalsocket.disconnected, raising=True,
timeout=5000): timeout=5000):
pass pass
assert caplog.records()[-1].message == "IPC connection timed out." assert caplog.records[-1].message == "IPC connection timed out."
@pytest.mark.parametrize('method, args, is_warning', [ @pytest.mark.parametrize('method, args, is_warning', [
@ -628,13 +626,13 @@ def test_ipcserver_socket_none(ipc_server, caplog, method, args, is_warning):
assert ipc_server._socket is None assert ipc_server._socket is None
if is_warning: if is_warning:
with caplog.atLevel(logging.WARNING): with caplog.at_level(logging.WARNING):
func(*args) func(*args)
else: else:
func(*args) func(*args)
msg = "In {} with None socket!".format(method) msg = "In {} with None socket!".format(method)
assert msg in [r.message for r in caplog.records()] assert msg in [r.message for r in caplog.records]
class TestSendOrListen: class TestSendOrListen:
@ -683,7 +681,7 @@ class TestSendOrListen:
def test_normal_connection(self, caplog, qtbot, args): def test_normal_connection(self, caplog, qtbot, args):
ret_server = ipc.send_or_listen(args) ret_server = ipc.send_or_listen(args)
assert isinstance(ret_server, ipc.IPCServer) assert isinstance(ret_server, ipc.IPCServer)
msgs = [e.message for e in caplog.records()] msgs = [e.message for e in caplog.records]
assert "Starting IPC server..." in msgs assert "Starting IPC server..." in msgs
objreg_server = objreg.get('ipc-server') objreg_server = objreg.get('ipc-server')
assert objreg_server is ret_server assert objreg_server is ret_server
@ -698,7 +696,7 @@ class TestSendOrListen:
with qtbot.waitSignal(legacy_server.got_args, raising=True): with qtbot.waitSignal(legacy_server.got_args, raising=True):
ret = ipc.send_or_listen(args) ret = ipc.send_or_listen(args)
assert ret is None assert ret is None
msgs = [e.message for e in caplog.records()] msgs = [e.message for e in caplog.records]
assert "Connecting to {}".format(legacy_server._socketname) in msgs assert "Connecting to {}".format(legacy_server._socketname) in msgs
@pytest.mark.posix(reason="Unneeded on Windows") @pytest.mark.posix(reason="Unneeded on Windows")
@ -775,7 +773,7 @@ class TestSendOrListen:
ret = ipc.send_or_listen(args) ret = ipc.send_or_listen(args)
assert ret is None assert ret is None
msgs = [e.message for e in caplog.records()] msgs = [e.message for e in caplog.records]
assert "Got AddressInUseError, trying again." in msgs assert "Got AddressInUseError, trying again." in msgs
@pytest.mark.parametrize('has_error, exc_name, exc_msg', [ @pytest.mark.parametrize('has_error, exc_name, exc_msg', [
@ -812,12 +810,11 @@ class TestSendOrListen:
QLocalSocket.ConnectionRefusedError, # error() gets called twice QLocalSocket.ConnectionRefusedError, # error() gets called twice
] ]
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
with pytest.raises(ipc.Error): with pytest.raises(ipc.Error):
ipc.send_or_listen(args) ipc.send_or_listen(args)
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1
error_msgs = [ error_msgs = [
'Handling fatal misc.ipc.{} with --no-err-windows!'.format( 'Handling fatal misc.ipc.{} with --no-err-windows!'.format(
@ -828,7 +825,7 @@ class TestSendOrListen:
'post_text: Maybe another instance is running but frozen?', 'post_text: Maybe another instance is running but frozen?',
'exception text: {}'.format(exc_msg), 'exception text: {}'.format(exc_msg),
] ]
assert records[0].msg == '\n'.join(error_msgs) assert caplog.records[0].msg == '\n'.join(error_msgs)
@pytest.mark.posix(reason="Flaky on Windows") @pytest.mark.posix(reason="Flaky on Windows")
def test_error_while_listening(self, qlocalserver_mock, caplog, args): def test_error_while_listening(self, qlocalserver_mock, caplog, args):
@ -837,12 +834,11 @@ class TestSendOrListen:
err = QAbstractSocket.SocketResourceError err = QAbstractSocket.SocketResourceError
qlocalserver_mock().serverError.return_value = err qlocalserver_mock().serverError.return_value = err
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
with pytest.raises(ipc.Error): with pytest.raises(ipc.Error):
ipc.send_or_listen(args) ipc.send_or_listen(args)
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1
error_msgs = [ error_msgs = [
'Handling fatal misc.ipc.ListenError with --no-err-windows!', 'Handling fatal misc.ipc.ListenError with --no-err-windows!',
@ -853,7 +849,7 @@ class TestSendOrListen:
'exception text: Error while listening to IPC server: Error ' 'exception text: Error while listening to IPC server: Error '
'string (error 4)', 'string (error 4)',
] ]
assert records[0].msg == '\n'.join(error_msgs) assert caplog.records[0].msg == '\n'.join(error_msgs)
@pytest.mark.windows @pytest.mark.windows

View File

@ -821,10 +821,9 @@ class TestSessionDelete:
tmpdir.chmod(0o555) # unwritable tmpdir.chmod(0o555) # unwritable
with pytest.raises(cmdexc.CommandError) as excinfo: with pytest.raises(cmdexc.CommandError) as excinfo:
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
sess_man.session_delete('foo') sess_man.session_delete('foo')
assert str(excinfo.value).startswith('Error while deleting session: ') assert str(excinfo.value).startswith('Error while deleting session: ')
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1 assert caplog.records[0].message == 'Error while deleting session!'
assert records[0].message == 'Error while deleting session!'

View File

@ -41,9 +41,8 @@ def test_log_events(qapp, caplog):
obj = EventObject() obj = EventObject()
qapp.postEvent(obj, QEvent(QEvent.User)) qapp.postEvent(obj, QEvent(QEvent.User))
qapp.processEvents() qapp.processEvents()
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1 assert caplog.records[0].msg == 'Event in test_debug.EventObject: User'
assert records[0].msg == 'Event in test_debug.EventObject: User'
class SignalObject(QObject): class SignalObject(QObject):
@ -75,10 +74,9 @@ def test_log_signals(caplog, signal_obj):
signal_obj.signal1.emit() signal_obj.signal1.emit()
signal_obj.signal2.emit('foo', 'bar') signal_obj.signal2.emit('foo', 'bar')
records = caplog.records() assert len(caplog.records) == 2
assert len(records) == 2 assert caplog.records[0].msg == 'Signal in <repr>: signal1()'
assert records[0].msg == 'Signal in <repr>: signal1()' assert caplog.records[1].msg == "Signal in <repr>: signal2('foo', 'bar')"
assert records[1].msg == "Signal in <repr>: signal2('foo', 'bar')"
class TestLogTime: class TestLogTime:
@ -86,15 +84,14 @@ class TestLogTime:
def test_duration(self, caplog): def test_duration(self, caplog):
logger_name = 'qt-tests' logger_name = 'qt-tests'
with caplog.atLevel(logging.DEBUG, logger_name): with caplog.at_level(logging.DEBUG, logger_name):
with debug.log_time(logger_name, action='foobar'): with debug.log_time(logger_name, action='foobar'):
time.sleep(0.1) time.sleep(0.1)
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1
pattern = re.compile(r'^Foobar took ([\d.]*) seconds\.$') pattern = re.compile(r'^Foobar took ([\d.]*) seconds\.$')
match = pattern.match(records[0].msg) match = pattern.match(caplog.records[0].msg)
assert match assert match
duration = float(match.group(1)) duration = float(match.group(1))
@ -104,11 +101,11 @@ class TestLogTime:
"""Test with an explicit logger instead of a name.""" """Test with an explicit logger instead of a name."""
logger_name = 'qt-tests' logger_name = 'qt-tests'
with caplog.atLevel(logging.DEBUG, logger_name): with caplog.at_level(logging.DEBUG, logger_name):
with debug.log_time(logging.getLogger(logger_name)): with debug.log_time(logging.getLogger(logger_name)):
pass pass
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
def test_decorator(self, caplog): def test_decorator(self, caplog):
logger_name = 'qt-tests' logger_name = 'qt-tests'
@ -118,12 +115,11 @@ class TestLogTime:
assert arg == 1 assert arg == 1
assert kwarg == 2 assert kwarg == 2
with caplog.atLevel(logging.DEBUG, logger_name): with caplog.at_level(logging.DEBUG, logger_name):
func(1, kwarg=2) func(1, kwarg=2)
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1 assert caplog.records[0].msg.startswith('Foo took')
assert records[0].msg.startswith('Foo took')
class TestQEnumKey: class TestQEnumKey:

View File

@ -52,12 +52,11 @@ def test_no_err_windows(caplog, exc, name, exc_text):
try: try:
raise exc raise exc
except Exception as e: except Exception as e:
with caplog.atLevel(logging.ERROR): with caplog.at_level(logging.ERROR):
error.handle_fatal_exc(e, Args(no_err_windows=True), 'title', error.handle_fatal_exc(e, Args(no_err_windows=True), 'title',
pre_text='pre', post_text='post') pre_text='pre', post_text='post')
records = caplog.records() assert len(caplog.records) == 1
assert len(records) == 1
expected = [ expected = [
'Handling fatal {} with --no-err-windows!'.format(name), 'Handling fatal {} with --no-err-windows!'.format(name),
@ -67,7 +66,7 @@ def test_no_err_windows(caplog, exc, name, exc_text):
'post_text: post', 'post_text: post',
'exception text: {}'.format(exc_text), 'exception text: {}'.format(exc_text),
] ]
assert records[0].msg == '\n'.join(expected) assert caplog.records[0].msg == '\n'.join(expected)
# This happens on Xvfb for some reason # This happens on Xvfb for some reason

View File

@ -25,7 +25,7 @@ import itertools
import sys import sys
import pytest import pytest
import pytest_capturelog # pylint: disable=import-error import pytest_catchlog # pylint: disable=import-error
from qutebrowser.utils import log from qutebrowser.utils import log
@ -60,10 +60,11 @@ def restore_loggers():
while root_logger.handlers: while root_logger.handlers:
h = root_logger.handlers[0] h = root_logger.handlers[0]
root_logger.removeHandler(h) root_logger.removeHandler(h)
if not isinstance(h, pytest_catchlog.LogCaptureHandler):
h.close() h.close()
root_logger.setLevel(original_logging_level) root_logger.setLevel(original_logging_level)
for h in root_handlers: for h in root_handlers:
if not isinstance(h, pytest_capturelog.CaptureLogHandler): if not isinstance(h, pytest_catchlog.LogCaptureHandler):
# https://github.com/The-Compiler/qutebrowser/issues/856 # https://github.com/The-Compiler/qutebrowser/issues/856
root_logger.addHandler(h) root_logger.addHandler(h)
logging._acquireLock() logging._acquireLock()
@ -238,30 +239,30 @@ class TestHideQtWarning:
def test_unfiltered(self, logger, caplog): def test_unfiltered(self, logger, caplog):
"""Test a message which is not filtered.""" """Test a message which is not filtered."""
with log.hide_qt_warning("World", 'qt-tests'): with log.hide_qt_warning("World", 'qt-tests'):
with caplog.atLevel(logging.WARNING, 'qt-tests'): with caplog.at_level(logging.WARNING, 'qt-tests'):
logger.warning("Hello World") logger.warning("Hello World")
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
record = caplog.records()[0] record = caplog.records[0]
assert record.levelname == 'WARNING' assert record.levelname == 'WARNING'
assert record.message == "Hello World" assert record.message == "Hello World"
def test_filtered_exact(self, logger, caplog): def test_filtered_exact(self, logger, caplog):
"""Test a message which is filtered (exact match).""" """Test a message which is filtered (exact match)."""
with log.hide_qt_warning("Hello", 'qt-tests'): with log.hide_qt_warning("Hello", 'qt-tests'):
with caplog.atLevel(logging.WARNING, 'qt-tests'): with caplog.at_level(logging.WARNING, 'qt-tests'):
logger.warning("Hello") logger.warning("Hello")
assert not caplog.records() assert not caplog.records
def test_filtered_start(self, logger, caplog): def test_filtered_start(self, logger, caplog):
"""Test a message which is filtered (match at line start).""" """Test a message which is filtered (match at line start)."""
with log.hide_qt_warning("Hello", 'qt-tests'): with log.hide_qt_warning("Hello", 'qt-tests'):
with caplog.atLevel(logging.WARNING, 'qt-tests'): with caplog.at_level(logging.WARNING, 'qt-tests'):
logger.warning("Hello World") logger.warning("Hello World")
assert not caplog.records() assert not caplog.records
def test_filtered_whitespace(self, logger, caplog): def test_filtered_whitespace(self, logger, caplog):
"""Test a message which is filtered (match with whitespace).""" """Test a message which is filtered (match with whitespace)."""
with log.hide_qt_warning("Hello", 'qt-tests'): with log.hide_qt_warning("Hello", 'qt-tests'):
with caplog.atLevel(logging.WARNING, 'qt-tests'): with caplog.at_level(logging.WARNING, 'qt-tests'):
logger.warning(" Hello World ") logger.warning(" Hello World ")
assert not caplog.records() assert not caplog.records

View File

@ -263,10 +263,10 @@ class TestInitCacheDirTag:
monkeypatch.setattr('qutebrowser.utils.standarddir.cache', monkeypatch.setattr('qutebrowser.utils.standarddir.cache',
lambda: str(tmpdir)) lambda: str(tmpdir))
mocker.patch('builtins.open', side_effect=OSError) mocker.patch('builtins.open', side_effect=OSError)
with caplog.atLevel(logging.ERROR, 'init'): with caplog.at_level(logging.ERROR, 'init'):
standarddir._init_cachedir_tag() standarddir._init_cachedir_tag()
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
assert caplog.records()[0].message == 'Failed to create CACHEDIR.TAG' assert caplog.records[0].message == 'Failed to create CACHEDIR.TAG'
assert not tmpdir.listdir() assert not tmpdir.listdir()

View File

@ -241,11 +241,11 @@ class TestActuteWarning:
mocker.patch('qutebrowser.utils.utils.open', side_effect=OSError, mocker.patch('qutebrowser.utils.utils.open', side_effect=OSError,
create=True) create=True)
with caplog.atLevel(logging.ERROR, 'init'): with caplog.at_level(logging.ERROR, 'init'):
utils.actute_warning() utils.actute_warning()
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
assert caplog.records()[0].message == 'Failed to read Compose file' assert caplog.records[0].message == 'Failed to read Compose file'
out, _err = capsys.readouterr() out, _err = capsys.readouterr()
assert not out assert not out
@ -669,12 +669,12 @@ class TestPreventExceptions:
def test_raising(self, caplog): def test_raising(self, caplog):
"""Test with a raising function.""" """Test with a raising function."""
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
ret = self.func_raising() ret = self.func_raising()
assert ret == 42 assert ret == 42
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
expected = 'Error in test_utils.TestPreventExceptions.func_raising' expected = 'Error in test_utils.TestPreventExceptions.func_raising'
actual = caplog.records()[0].message actual = caplog.records[0].message
assert actual == expected assert actual == expected
@utils.prevent_exceptions(42) @utils.prevent_exceptions(42)
@ -683,10 +683,10 @@ class TestPreventExceptions:
def test_not_raising(self, caplog): def test_not_raising(self, caplog):
"""Test with a non-raising function.""" """Test with a non-raising function."""
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
ret = self.func_not_raising() ret = self.func_not_raising()
assert ret == 23 assert ret == 23
assert not caplog.records() assert not caplog.records
@utils.prevent_exceptions(42, True) @utils.prevent_exceptions(42, True)
def func_predicate_true(self): def func_predicate_true(self):
@ -694,10 +694,10 @@ class TestPreventExceptions:
def test_predicate_true(self, caplog): def test_predicate_true(self, caplog):
"""Test with a True predicate.""" """Test with a True predicate."""
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
ret = self.func_predicate_true() ret = self.func_predicate_true()
assert ret == 42 assert ret == 42
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
@utils.prevent_exceptions(42, False) @utils.prevent_exceptions(42, False)
def func_predicate_false(self): def func_predicate_false(self):
@ -705,10 +705,10 @@ class TestPreventExceptions:
def test_predicate_false(self, caplog): def test_predicate_false(self, caplog):
"""Test with a False predicate.""" """Test with a False predicate."""
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
with pytest.raises(Exception): with pytest.raises(Exception):
self.func_predicate_false() self.func_predicate_false()
assert not caplog.records() assert not caplog.records
class Obj: class Obj:

View File

@ -108,7 +108,7 @@ class TestGitStr:
monkeypatch.setattr(qutebrowser.utils.version.sys, 'frozen', True, monkeypatch.setattr(qutebrowser.utils.version.sys, 'frozen', True,
raising=False) raising=False)
commit_file_mock.side_effect = OSError commit_file_mock.side_effect = OSError
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
assert version._git_str() is None assert version._git_str() is None
@pytest.mark.not_frozen @pytest.mark.not_frozen
@ -136,7 +136,7 @@ class TestGitStr:
m.path.join.side_effect = OSError m.path.join.side_effect = OSError
mocker.patch('qutebrowser.utils.version.utils.read_file', mocker.patch('qutebrowser.utils.version.utils.read_file',
side_effect=OSError) side_effect=OSError)
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
assert version._git_str() is None assert version._git_str() is None
@pytest.mark.not_frozen @pytest.mark.not_frozen
@ -145,10 +145,10 @@ class TestGitStr:
"""Test with undefined __file__ but available git-commit-id.""" """Test with undefined __file__ but available git-commit-id."""
monkeypatch.delattr('qutebrowser.utils.version.__file__') monkeypatch.delattr('qutebrowser.utils.version.__file__')
commit_file_mock.return_value = '0deadcode' commit_file_mock.return_value = '0deadcode'
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
assert version._git_str() == '0deadcode' assert version._git_str() == '0deadcode'
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
assert caplog.records()[0].message == "Error while getting git path" assert caplog.records[0].message == "Error while getting git path"
def _has_git(): def _has_git():
@ -294,11 +294,11 @@ def test_release_info(files, expected, caplog, monkeypatch):
fake = ReleaseInfoFake(files) fake = ReleaseInfoFake(files)
monkeypatch.setattr('qutebrowser.utils.version.glob.glob', fake.glob_fake) monkeypatch.setattr('qutebrowser.utils.version.glob.glob', fake.glob_fake)
monkeypatch.setattr(version, 'open', fake.open_fake, raising=False) monkeypatch.setattr(version, 'open', fake.open_fake, raising=False)
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
assert version._release_info() == expected assert version._release_info() == expected
if files is None: if files is None:
assert len(caplog.records()) == 1 assert len(caplog.records) == 1
assert caplog.records()[0].message == "Error while reading fake-file." assert caplog.records[0].message == "Error while reading fake-file."
class ImportFake: class ImportFake:

View File

@ -86,6 +86,6 @@ def test_abort_typeerror(question, qtbot, mocker, caplog):
"""Test Question.abort() with .emit() raising a TypeError.""" """Test Question.abort() with .emit() raising a TypeError."""
signal_mock = mocker.patch('qutebrowser.utils.usertypes.Question.aborted') signal_mock = mocker.patch('qutebrowser.utils.usertypes.Question.aborted')
signal_mock.emit.side_effect = TypeError signal_mock.emit.side_effect = TypeError
with caplog.atLevel(logging.ERROR, 'misc'): with caplog.at_level(logging.ERROR, 'misc'):
question.abort() question.abort()
assert caplog.records()[0].message == 'Error while aborting question' assert caplog.records[0].message == 'Error while aborting question'

View File

@ -28,7 +28,7 @@ deps =
py==1.4.30 py==1.4.30
pytest==2.7.3 # rq.filter: <2.8.0 pytest==2.7.3 # rq.filter: <2.8.0
pytest-bdd==2.15.0 pytest-bdd==2.15.0
pytest-capturelog==0.7 pytest-catchlog==1.2.0
pytest-cov==2.2.0 pytest-cov==2.2.0
pytest-faulthandler==1.0.1 pytest-faulthandler==1.0.1
pytest-html==1.7 pytest-html==1.7