From 5c97ec16591af00aa383118d1241c0ff640d10c6 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Tue, 19 Apr 2016 09:50:53 +0200 Subject: [PATCH] Fix HeaderDict lint --- qutebrowser/config/configtypes.py | 48 +++++++++++++++---------------- 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/qutebrowser/config/configtypes.py b/qutebrowser/config/configtypes.py index 06da1bb06..da4ecf8d5 100644 --- a/qutebrowser/config/configtypes.py +++ b/qutebrowser/config/configtypes.py @@ -1428,6 +1428,27 @@ class HeaderDict(BaseType): """A JSON-like dictionary for custom HTTP headers.""" + def _validate_str(self, value, what): + """Check if the given thing is an ascii-only string. + + Raises ValidationError if not. + + Args: + value: The value to check. + what: Either 'key' or 'value'. + """ + if not isinstance(value, str): + msg = "Expected string for {} {!r} but got {}".format( + what, value, type(value)) + raise configexc.ValidationError(value, msg) + + try: + value.encode('ascii') + except UnicodeEncodeError as e: + msg = "{} {!r} contains non-ascii characters: {}".format( + what.capitalize(), value, e) + raise configexc.ValidationError(value, msg) + def validate(self, value): self._basic_validation(value) if not value: @@ -1441,7 +1462,6 @@ class HeaderDict(BaseType): if not isinstance(json_val, dict): raise configexc.ValidationError(value, "Expected json dict, but " "got {}".format(type(json_val))) - if not json_val: if self.none_ok: return @@ -1449,30 +1469,8 @@ class HeaderDict(BaseType): raise configexc.ValidationError(value, "may not be empty!") for key, val in json_val.items(): - if not isinstance(key, str): - msg = "Expected string for key {!r} but got {}".format( - key, type(key)) - raise configexc.ValidationError(value, msg) - - if not isinstance(val, str): - msg = "Expected string for value {!r} but got {}".format( - key, type(key)) - raise configexc.ValidationError(value, msg) - - try: - key.encode('ascii') - except UnicodeEncodeError as e: - msg = "Key {!r} contains non-ascii characters: {}".format( - key, e) - raise configexc.ValidationError(value, msg) - - try: - val.encode('ascii') - except UnicodeEncodeError as e: - msg = "Value {!r} contains non-ascii characters: {}".format( - val, e) - raise configexc.ValidationError(value, msg) - + self._validate_str(key, 'key') + self._validate_str(val, 'value') def transform(self, value): if not value: