From 41dfa296483954e3f4eaf3285b9688b318211861 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Tue, 6 Mar 2018 06:29:03 +0100 Subject: [PATCH] Improve parsing of invalid keys This should handle "<>" and "\x1f" correctly. --- qutebrowser/keyinput/keyutils.py | 8 ++++---- tests/unit/keyinput/test_keyutils.py | 18 +++++++++++++----- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/qutebrowser/keyinput/keyutils.py b/qutebrowser/keyinput/keyutils.py index fd00cf5b5..91d6a36a3 100644 --- a/qutebrowser/keyinput/keyutils.py +++ b/qutebrowser/keyinput/keyutils.py @@ -413,12 +413,12 @@ class KeySequence: def _validate(self, keystr=None): for info in self: - assert Qt.Key_Space <= info.key <= Qt.Key_unknown, info.key - if info.key == Qt.Key_unknown: - raise KeyParseError(keystr, "Got unknown key!") + if info.key < Qt.Key_Space or info.key >= Qt.Key_unknown: + raise KeyParseError(keystr, "Got invalid key!") for seq in self._sequences: - assert seq + if not seq: + raise KeyParseError(keystr, "Got invalid key!") def matches(self, other): """Check whether the given KeySequence matches with this one. diff --git a/tests/unit/keyinput/test_keyutils.py b/tests/unit/keyinput/test_keyutils.py index 97c9da04c..11dd41b1f 100644 --- a/tests/unit/keyinput/test_keyutils.py +++ b/tests/unit/keyinput/test_keyutils.py @@ -19,6 +19,8 @@ import operator +import hypothesis +from hypothesis import strategies import pytest from PyQt5.QtCore import Qt, QEvent, pyqtSignal from PyQt5.QtGui import QKeyEvent, QKeySequence @@ -203,15 +205,11 @@ class TestKeySequence: seq = keyutils.KeySequence() assert not seq - @pytest.mark.parametrize('key', [Qt.Key_unknown, -1]) + @pytest.mark.parametrize('key', [Qt.Key_unknown, -1, '\x1f', 0]) def test_init_unknown(self, key): with pytest.raises(keyutils.KeyParseError): keyutils.KeySequence(key) - def test_init_invalid(self): - with pytest.raises(AssertionError): - keyutils.KeySequence(0) - @pytest.mark.parametrize('orig, normalized', [ ('', ''), ('', ''), @@ -410,6 +408,7 @@ class TestKeySequence: ('', keyutils.KeyParseError), ('>', keyutils.KeyParseError), ('', keyutils.KeyParseError), + ('<>', keyutils.KeyParseError), ('\U00010000', keyutils.KeyParseError), ]) def test_parse(self, keystr, expected): @@ -419,6 +418,15 @@ class TestKeySequence: else: assert keyutils.KeySequence.parse(keystr) == expected + @hypothesis.given(strategies.text()) + def test_parse_hypothesis(self, keystr): + try: + seq = keyutils.KeySequence.parse(keystr) + except keyutils.KeyParseError: + pass + else: + str(seq) + def test_key_info_from_event(): ev = QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.ShiftModifier, 'A')