From 1cbb4ece4b791b35e1770a6f51dd94c14070f51c Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Thu, 15 Jun 2017 18:09:31 +0200 Subject: [PATCH] Force configtype.Dict keys to be strings --- qutebrowser/config/configtypes.py | 3 +++ tests/unit/config/test_configtypes.py | 20 ++++++++++++-------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/qutebrowser/config/configtypes.py b/qutebrowser/config/configtypes.py index 5efa6f2af..64e286c24 100644 --- a/qutebrowser/config/configtypes.py +++ b/qutebrowser/config/configtypes.py @@ -952,6 +952,9 @@ class Dict(BaseType): def __init__(self, keytype, valtype, *, fixed_keys=None, none_ok=False): super().__init__(none_ok) + # If the keytype is not a string, we'll get problems with showing it as + # json in to_str() as json converts keys to strings. + assert isinstance(keytype, String), keytype self.keytype = keytype self.valtype = valtype self.fixed_keys = fixed_keys diff --git a/tests/unit/config/test_configtypes.py b/tests/unit/config/test_configtypes.py index 6afd8bd12..05ee0211d 100644 --- a/tests/unit/config/test_configtypes.py +++ b/tests/unit/config/test_configtypes.py @@ -1370,9 +1370,9 @@ class TestDict: d.from_str(val) def test_from_str_int(self): - typ = configtypes.Dict(keytype=configtypes.Int(), + typ = configtypes.Dict(keytype=configtypes.String(), valtype=configtypes.Int()) - assert typ.from_str('{0: 0}') == {0: 0} + assert typ.from_str('{"answer": 42}') == {"answer": 42} @pytest.mark.parametrize('val', [ {"one": "1"}, # missing key @@ -1389,20 +1389,24 @@ class TestDict: else: d.from_py(val) - @hypothesis.given(val=strategies.dictionaries(strategies.booleans(), + @hypothesis.given(val=strategies.dictionaries(strategies.text(min_size=1), strategies.booleans())) def test_hypothesis(self, klass, val): - d = klass(keytype=configtypes.Bool(), + d = klass(keytype=configtypes.String(), valtype=configtypes.Bool(), none_ok=True) - converted = d.from_py(val) - assert d.from_str(d.to_str(converted)) == converted + try: + converted = d.from_py(val) + assert d.from_str(d.to_str(converted)) == converted + except configexc.ValidationError: + # Invalid unicode in the string, etc... + hypothesis.assume(False) - @hypothesis.given(val=strategies.dictionaries(strategies.booleans(), + @hypothesis.given(val=strategies.dictionaries(strategies.text(min_size=1), strategies.booleans())) def test_hypothesis_text(self, klass, val): text = json.dumps(val) - d = klass(keytype=configtypes.Bool(), valtype=configtypes.Bool()) + d = klass(keytype=configtypes.String(), valtype=configtypes.Bool()) try: converted = d.from_str(text) except configexc.ValidationError: