Simplify message_mock usage and assert more things.

This commit is contained in:
Florian Bruhin 2015-08-19 09:44:31 +02:00
parent 685bbaae6d
commit 086c6c81a1
4 changed files with 28 additions and 25 deletions

View File

@ -43,8 +43,11 @@ class MessageMock:
Message: A namedtuple representing a message. Message: A namedtuple representing a message.
messages: A list of Message tuples. messages: A list of Message tuples.
caplog: The pytest-capturelog fixture. caplog: The pytest-capturelog fixture.
Level: The Level type for easier usage as a fixture.
""" """
Level = Level
def __init__(self, monkeypatch, caplog): def __init__(self, monkeypatch, caplog):
self._monkeypatch = monkeypatch self._monkeypatch = monkeypatch
self._caplog = caplog self._caplog = caplog
@ -72,15 +75,25 @@ class MessageMock:
def _handle_warning(self, *args, **kwargs): def _handle_warning(self, *args, **kwargs):
self._handle(Level.warning, *args, **kwargs) self._handle(Level.warning, *args, **kwargs)
def getmsg(self): def getmsg(self, level=None, *, win_id=0, immediate=False):
"""Get the only message in self.messages. """Get the only message in self.messages.
Raises ValueError if there are multiple or no messages. Raises ValueError if there are multiple or no messages.
Args:
level: The message level to check against, or None.
win_id: The window id to check against.
immediate: If the message has the immediate flag set.
""" """
if len(self.messages) != 1: assert len(self.messages) == 1
raise ValueError("Got {} messages but expected a single " msg = self.messages[0]
"one.".format(len(self.messages)))
return self.messages[0] if level is not None:
assert msg.level == level
assert msg.win_id == win_id
assert msg.immediate == immediate
return msg
def patch(self, module_path): def patch(self, module_path):
"""Patch message.* in the given module (as a string).""" """Patch message.* in the given module (as a string)."""

View File

@ -26,7 +26,6 @@ from unittest import mock
from PyQt5.QtCore import QProcess from PyQt5.QtCore import QProcess
import pytest import pytest
from helpers import messagemock
from qutebrowser.misc import editor as editormod from qutebrowser.misc import editor as editormod
@ -116,8 +115,7 @@ class TestFileHandling:
os.chmod(filename, 0o077) os.chmod(filename, 0o077)
editor._proc.finished.emit(0, QProcess.NormalExit) editor._proc.finished.emit(0, QProcess.NormalExit)
assert not os.path.exists(filename) assert not os.path.exists(filename)
msg = message_mock.getmsg() msg = message_mock.getmsg(message_mock.Level.error)
assert msg.level == messagemock.Level.error
assert msg.text.startswith("Failed to read back edited file: ") assert msg.text.startswith("Failed to read back edited file: ")
def test_unwritable(self, monkeypatch, message_mock, editor, tmpdir): def test_unwritable(self, monkeypatch, message_mock, editor, tmpdir):
@ -126,8 +124,7 @@ class TestFileHandling:
monkeypatch.setattr('qutebrowser.misc.editor.tempfile.tempdir', monkeypatch.setattr('qutebrowser.misc.editor.tempfile.tempdir',
str(tmpdir)) str(tmpdir))
editor.edit("") editor.edit("")
msg = message_mock.getmsg() msg = message_mock.getmsg(message_mock.Level.error)
assert msg.level == messagemock.Level.error
assert msg.text.startswith("Failed to create initial file: ") assert msg.text.startswith("Failed to create initial file: ")
assert editor._proc is None assert editor._proc is None

View File

@ -28,13 +28,9 @@ import logging
import pytest import pytest
from PyQt5.QtCore import QProcess, QIODevice from PyQt5.QtCore import QProcess, QIODevice
from helpers import messagemock # pylint: disable=import-error
from qutebrowser.misc import guiprocess from qutebrowser.misc import guiprocess
# FIXME check statusbar messages
def _py_proc(code): def _py_proc(code):
"""Get a python executable and args list which executes the given code.""" """Get a python executable and args list which executes the given code."""
return (sys.executable, ['-c', textwrap.dedent(code.strip('\n'))]) return (sys.executable, ['-c', textwrap.dedent(code.strip('\n'))])
@ -92,8 +88,8 @@ def test_start_verbose(proc, qtbot, guiprocess_message_mock):
proc.start(*argv) proc.start(*argv)
msgs = guiprocess_message_mock.messages msgs = guiprocess_message_mock.messages
assert msgs[0].level == messagemock.Level.info assert msgs[0].level == guiprocess_message_mock.Level.info
assert msgs[1].level == messagemock.Level.info assert msgs[1].level == guiprocess_message_mock.Level.info
assert msgs[0].text.startswith("Executing:") assert msgs[0].text.startswith("Executing:")
assert msgs[1].text == "Testprocess exited successfully." assert msgs[1].text == "Testprocess exited successfully."
assert bytes(proc._proc.readAll()).rstrip() == b'test' assert bytes(proc._proc.readAll()).rstrip() == b'test'
@ -151,8 +147,8 @@ def test_start_detached_error(fake_proc, guiprocess_message_mock):
fake_proc._proc.startDetached.return_value = (False, 0) fake_proc._proc.startDetached.return_value = (False, 0)
fake_proc._proc.error.return_value = "Error message" fake_proc._proc.error.return_value = "Error message"
fake_proc.start_detached(*argv) fake_proc.start_detached(*argv)
msg = guiprocess_message_mock.getmsg() msg = guiprocess_message_mock.getmsg(guiprocess_message_mock.Level.error,
assert msg.level == messagemock.Level.error immediate=True)
assert msg.text == "Error while spawning testprocess: Error message." assert msg.text == "Error while spawning testprocess: Error message."
@ -193,8 +189,8 @@ def test_error(qtbot, proc, caplog, guiprocess_message_mock):
with qtbot.waitSignal(proc.error, raising=True): with qtbot.waitSignal(proc.error, raising=True):
proc.start('this_does_not_exist_either', []) proc.start('this_does_not_exist_either', [])
msg = guiprocess_message_mock.getmsg() msg = guiprocess_message_mock.getmsg(guiprocess_message_mock.Level.error,
assert msg.level == messagemock.Level.error immediate=True)
expected_msg = ("Error while spawning testprocess: The process failed to " expected_msg = ("Error while spawning testprocess: The process failed to "
"start.") "start.")
assert msg.text == expected_msg assert msg.text == expected_msg
@ -205,6 +201,5 @@ def test_exit_unsuccessful(qtbot, proc, guiprocess_message_mock):
with qtbot.waitSignal(proc.finished, raising=True, timeout=10000): with qtbot.waitSignal(proc.finished, raising=True, timeout=10000):
proc.start(*_py_proc('import sys; sys.exit(1)')) proc.start(*_py_proc('import sys; sys.exit(1)'))
msg = guiprocess_message_mock.getmsg() msg = guiprocess_message_mock.getmsg(guiprocess_message_mock.Level.error)
assert msg.level == messagemock.Level.error
assert msg.text == "Testprocess exited with status 1." assert msg.text == "Testprocess exited with status 1."

View File

@ -384,9 +384,7 @@ def test_invalid_url_error(urlutils_message_mock, url, valid, has_err_string):
assert bool(qurl.errorString()) == has_err_string assert bool(qurl.errorString()) == has_err_string
urlutils.invalid_url_error(0, qurl, 'frozzle') urlutils.invalid_url_error(0, qurl, 'frozzle')
msg = urlutils_message_mock.getmsg() msg = urlutils_message_mock.getmsg(urlutils_message_mock.Level.error)
assert msg.win_id == 0
assert not msg.immediate
if has_err_string: if has_err_string:
expected_text = ("Trying to frozzle with invalid URL - " + expected_text = ("Trying to frozzle with invalid URL - " +
qurl.errorString()) qurl.errorString())