Add an utils.Unreachable exception

This commit is contained in:
Florian Bruhin 2017-12-15 16:12:31 +01:00
parent 016fc0ebb1
commit f4ed31b295
16 changed files with 37 additions and 24 deletions

View File

@ -12,6 +12,7 @@ exclude_lines =
def __repr__ def __repr__
raise AssertionError raise AssertionError
raise NotImplementedError raise NotImplementedError
raise utils\.Unreachable
if __name__ == ["']__main__["']: if __name__ == ["']__main__["']:
[xml] [xml]

View File

@ -706,8 +706,8 @@ class AbstractTab(QWidget):
# This only gives us some mild protection against re-using events, but # This only gives us some mild protection against re-using events, but
# it's certainly better than a segfault. # it's certainly better than a segfault.
if getattr(evt, 'posted', False): if getattr(evt, 'posted', False):
raise AssertionError("Can't re-use an event which was already " raise utils.Unreachable("Can't re-use an event which was already "
"posted!") "posted!")
recipient = self.event_target() recipient = self.event_target()
evt.posted = True evt.posted = True
QApplication.postEvent(recipient, evt) QApplication.postEvent(recipient, evt)

View File

@ -22,7 +22,7 @@
import html import html
from qutebrowser.config import config from qutebrowser.config import config
from qutebrowser.utils import usertypes, message, log, objreg, jinja from qutebrowser.utils import usertypes, message, log, objreg, jinja, utils
from qutebrowser.mainwindow import mainwindow from qutebrowser.mainwindow import mainwindow
@ -182,7 +182,7 @@ def ignore_certificate_errors(url, errors, abort_on):
return False return False
else: else:
raise ValueError("Invalid ssl_strict value {!r}".format(ssl_strict)) raise ValueError("Invalid ssl_strict value {!r}".format(ssl_strict))
raise AssertionError("Not reached") raise utils.Unreachable
def feature_permission(url, option, msg, yes_action, no_action, abort_on): def feature_permission(url, option, msg, yes_action, no_action, abort_on):

View File

@ -153,8 +153,7 @@ class Completer(QObject):
"partitioned: {} '{}' {}".format(prefix, center, postfix)) "partitioned: {} '{}' {}".format(prefix, center, postfix))
return prefix, center, postfix return prefix, center, postfix
# We should always return above raise utils.Unreachable("Not all parts consumed: {}".format(parts))
assert False, parts
@pyqtSlot(str) @pyqtSlot(str)
def on_selection_changed(self, text): def on_selection_changed(self, text):

View File

@ -180,6 +180,7 @@ class CompletionView(QTreeView):
return self.model().last_item() return self.model().last_item()
else: else:
return self.model().first_item() return self.model().first_item()
while True: while True:
idx = self.indexAbove(idx) if upwards else self.indexBelow(idx) idx = self.indexAbove(idx) if upwards else self.indexBelow(idx)
# wrap around if we arrived at beginning/end # wrap around if we arrived at beginning/end
@ -193,6 +194,8 @@ class CompletionView(QTreeView):
# Item is a real item, not a category header -> success # Item is a real item, not a category header -> success
return idx return idx
raise utils.Unreachable
def _next_category_idx(self, upwards): def _next_category_idx(self, upwards):
"""Get the index of the previous/next category. """Get the index of the previous/next category.
@ -222,6 +225,8 @@ class CompletionView(QTreeView):
self.scrollTo(idx) self.scrollTo(idx)
return idx.child(0, 0) return idx.child(0, 0)
raise utils.Unreachable
@cmdutils.register(instance='completion', @cmdutils.register(instance='completion',
modes=[usertypes.KeyMode.command], scope='window') modes=[usertypes.KeyMode.command], scope='window')
@cmdutils.argument('which', choices=['next', 'prev', 'next-category', @cmdutils.argument('which', choices=['next', 'prev', 'next-category',

View File

@ -174,6 +174,7 @@ def _parse_yaml_backends(name, node):
elif isinstance(node, dict): elif isinstance(node, dict):
return _parse_yaml_backends_dict(name, node) return _parse_yaml_backends_dict(name, node)
_raise_invalid_node(name, 'backends', node) _raise_invalid_node(name, 'backends', node)
raise utils.Unreachable
def _read_yaml(yaml_data): def _read_yaml(yaml_data):

View File

@ -214,7 +214,7 @@ class BaseKeyParser(QObject):
elif match == self.Match.other: elif match == self.Match.other:
pass pass
else: else:
raise AssertionError("Invalid match value {!r}".format(match)) raise utils.Unreachable("Invalid match value {!r}".format(match))
return match return match
def _match_key(self, cmd_input): def _match_key(self, cmd_input):

View File

@ -26,7 +26,7 @@ from qutebrowser.keyinput import modeman, modeparsers
from qutebrowser.commands import cmdexc, cmdutils from qutebrowser.commands import cmdexc, cmdutils
from qutebrowser.misc import cmdhistory, editor from qutebrowser.misc import cmdhistory, editor
from qutebrowser.misc import miscwidgets as misc from qutebrowser.misc import miscwidgets as misc
from qutebrowser.utils import usertypes, log, objreg, message from qutebrowser.utils import usertypes, log, objreg, message, utils
from qutebrowser.config import config from qutebrowser.config import config
@ -221,8 +221,8 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
elif text[0] in modeparsers.STARTCHARS: elif text[0] in modeparsers.STARTCHARS:
super().set_prompt(text[0]) super().set_prompt(text[0])
else: else:
raise AssertionError("setText got called with invalid text " raise utils.Unreachable("setText got called with invalid text "
"'{}'!".format(text)) "'{}'!".format(text))
super().setText(text) super().setText(text)
def keyPressEvent(self, e): def keyPressEvent(self, e):

View File

@ -152,7 +152,7 @@ def _show_dialog(*args, **kwargs):
elif status == _Result.restart: elif status == _Result.restart:
quitter.restart() quitter.restart()
else: else:
assert False, status raise utils.Unreachable(status)
sys.exit(usertypes.Exit.err_init) sys.exit(usertypes.Exit.err_init)
@ -199,8 +199,7 @@ def _handle_nouveau_graphics():
buttons=[button], buttons=[button],
) )
# Should never be reached raise utils.Unreachable
assert False
def _handle_wayland(): def _handle_wayland():
@ -239,8 +238,7 @@ def _handle_wayland():
"(based on Chromium). " "(based on Chromium). "
) )
# Should never be reached raise utils.Unreachable
assert False
@attr.s @attr.s
@ -359,8 +357,7 @@ def _check_backend_modules():
html.escape(imports.webengine_error)) html.escape(imports.webengine_error))
) )
# Should never be reached raise utils.Unreachable
assert False
def init(): def init():

View File

@ -241,7 +241,7 @@ class WrapperLayout(QLayout):
self._widget = None self._widget = None
def addItem(self, _widget): def addItem(self, _widget):
raise AssertionError("Should never be called!") raise utils.Unreachable
def sizeHint(self): def sizeHint(self):
return self._widget.sizeHint() return self._widget.sizeHint()
@ -250,7 +250,7 @@ class WrapperLayout(QLayout):
return None return None
def takeAt(self, _index): def takeAt(self, _index):
raise AssertionError("Should never be called!") raise utils.Unreachable
def setGeometry(self, rect): def setGeometry(self, rect):
self._widget.setGeometry(rect) self._widget.setGeometry(rect)

View File

@ -21,7 +21,7 @@
import re import re
from qutebrowser.utils import log from qutebrowser.utils import log, utils
class ShellLexer: class ShellLexer:
@ -117,7 +117,8 @@ class ShellLexer:
else: else:
self.token += nextchar self.token += nextchar
else: else:
raise AssertionError("Invalid state {!r}!".format(self.state)) raise utils.Unreachable(
"Invalid state {!r}!".format(self.state))
if self.state in self.escape and not self.keep: if self.state in self.escape and not self.keep:
self.token += self.state self.token += self.state
if self.token or self.quoted: if self.token or self.quoted:

View File

@ -60,6 +60,11 @@ is_windows = sys.platform.startswith('win')
is_posix = os.name == 'posix' is_posix = os.name == 'posix'
class Unreachable(Exception):
"""Raised when there was unreachable code."""
class ClipboardError(Exception): class ClipboardError(Exception):
"""Raised if the clipboard contents are unavailable for some reason.""" """Raised if the clipboard contents are unavailable for some reason."""

View File

@ -404,6 +404,8 @@ class Process(QObject):
self._log("----> found it") self._log("----> found it")
return match return match
raise quteutils.Unreachable
def _wait_for_match(self, spy, kwargs): def _wait_for_match(self, spy, kwargs):
"""Try matching the kwargs with the given QSignalSpy.""" """Try matching the kwargs with the given QSignalSpy."""
for args in spy: for args in spy:

View File

@ -20,6 +20,7 @@
import pytest import pytest
from qutebrowser.browser import browsertab from qutebrowser.browser import browsertab
from qutebrowser.utils import utils
pytestmark = pytest.mark.usefixtures('redirect_webengine_data') pytestmark = pytest.mark.usefixtures('redirect_webengine_data')
@ -54,7 +55,7 @@ def tab(request, qtbot, tab_registry, cookiejar_and_cache, mode_manager):
'qutebrowser.browser.webengine.webenginetab') 'qutebrowser.browser.webengine.webenginetab')
tab_class = webenginetab.WebEngineTab tab_class = webenginetab.WebEngineTab
else: else:
assert False raise utils.Unreachable
t = tab_class(win_id=0, mode_manager=mode_manager) t = tab_class(win_id=0, mode_manager=mode_manager)
qtbot.add_widget(t) qtbot.add_widget(t)
@ -67,7 +68,7 @@ class Zoom(browsertab.AbstractZoom):
pass pass
def factor(self): def factor(self):
assert False raise utils.Unreachable
class Tab(browsertab.AbstractTab): class Tab(browsertab.AbstractTab):

View File

@ -64,6 +64,7 @@ def runner(request, runtime_tmpdir):
if (not utils.is_posix and if (not utils.is_posix and
request.param is userscripts._POSIXUserscriptRunner): request.param is userscripts._POSIXUserscriptRunner):
pytest.skip("Requires a POSIX os") pytest.skip("Requires a POSIX os")
raise utils.Unreachable
else: else:
return request.param() return request.param()

View File

@ -795,7 +795,7 @@ class FakeQSslSocket:
def sslLibraryVersionString(self): def sslLibraryVersionString(self):
"""Fake for QSslSocket::sslLibraryVersionString().""" """Fake for QSslSocket::sslLibraryVersionString()."""
if self._version is None: if self._version is None:
raise AssertionError("Got called with version None!") raise utils.Unreachable("Got called with version None!")
return self._version return self._version