diff --git a/voluptuous/error.py b/voluptuous/error.py index 2789880..992ba0d 100644 --- a/voluptuous/error.py +++ b/voluptuous/error.py @@ -19,7 +19,13 @@ class Invalid(Error): """ - def __init__(self, message: str, path: typing.Optional[typing.List[str]] = None, error_message: typing.Optional[str] = None, error_type: typing.Optional[str] = None) -> None: + def __init__( + self, + message: str, + path: typing.Optional[typing.List[typing.Hashable]] = None, + error_message: typing.Optional[str] = None, + error_type: typing.Optional[str] = None + ) -> None: Error.__init__(self, message) self._path = path or [] self._error_message = error_message or message @@ -30,7 +36,7 @@ def msg(self) -> str: return self.args[0] @property - def path(self) -> typing.List[str]: + def path(self) -> typing.List[typing.Hashable]: return self._path @property @@ -45,7 +51,7 @@ def __str__(self) -> str: output += ' for ' + self.error_type return output + path - def prepend(self, path: typing.List[str]) -> None: + def prepend(self, path: typing.List[typing.Hashable]) -> None: self._path = path + self.path @@ -61,7 +67,7 @@ def msg(self) -> str: return self.errors[0].msg @property - def path(self) -> typing.List[str]: + def path(self) -> typing.List[typing.Hashable]: return self.errors[0].path @property @@ -74,7 +80,7 @@ def add(self, error: Invalid) -> None: def __str__(self) -> str: return str(self.errors[0]) - def prepend(self, path: typing.List[str]) -> None: + def prepend(self, path: typing.List[typing.Hashable]) -> None: for error in self.errors: error.prepend(path) diff --git a/voluptuous/humanize.py b/voluptuous/humanize.py index 734f367..923f3d1 100644 --- a/voluptuous/humanize.py +++ b/voluptuous/humanize.py @@ -7,10 +7,7 @@ MAX_VALIDATION_ERROR_ITEM_LENGTH = 500 -IndexT = typing.TypeVar("IndexT") - - -def _nested_getitem(data: typing.Dict[IndexT, typing.Any], path: typing.List[IndexT]) -> typing.Optional[typing.Any]: +def _nested_getitem(data: typing.Any, path: typing.List[typing.Hashable]) -> typing.Optional[typing.Any]: for item_index in path: try: data = data[item_index] diff --git a/voluptuous/tests/tests.py b/voluptuous/tests/tests.py index abca5f8..e2c5a66 100644 --- a/voluptuous/tests/tests.py +++ b/voluptuous/tests/tests.py @@ -1329,6 +1329,76 @@ def test_match_error_has_path(): assert False, "Did not raise MatchInvalid" +def test_path_with_string(): + """Most common dict use with strings as keys""" + s = Schema({'string_key': int}) + + with pytest.raises(MultipleInvalid) as ctx: + s({'string_key': 'str'}) + assert ctx.value.errors[0].path == ['string_key'] + + +def test_path_with_list_index(): + """Position of the offending list index included in path as int""" + s = Schema({'string_key': [int]}) + + with pytest.raises(MultipleInvalid) as ctx: + s({'string_key': [123, 'should be int']}) + assert ctx.value.errors[0].path == ['string_key', 1] + + +def test_path_with_tuple_index(): + """Position of the offending tuple index included in path as int""" + s = Schema({'string_key': (int,)}) + + with pytest.raises(MultipleInvalid) as ctx: + s({'string_key': (123, 'should be int')}) + assert ctx.value.errors[0].path == ['string_key', 1] + + +def test_path_with_integer_dict_key(): + """Not obvious case with dict having not strings, but integers as keys""" + s = Schema({1337: int}) + + with pytest.raises(MultipleInvalid) as ctx: + s({1337: 'should be int'}) + assert ctx.value.errors[0].path == [1337] + + +def test_path_with_float_dict_key(): + """Not obvious case with dict having not strings, but floats as keys""" + s = Schema({13.37: int}) + + with pytest.raises(MultipleInvalid) as ctx: + s({13.37: 'should be int'}) + assert ctx.value.errors[0].path == [13.37] + + +def test_path_with_tuple_dict_key(): + """Not obvious case with dict having not strings, but tuples as keys""" + s = Schema({('fancy', 'key'): int}) + + with pytest.raises(MultipleInvalid) as ctx: + s({('fancy', 'key'): 'should be int'}) + assert ctx.value.errors[0].path == [('fancy', 'key')] + + +def test_path_with_arbitrary_hashable_dict_key(): + """Not obvious case with dict having not strings, but arbitrary hashable objects as keys""" + + class HashableObjectWhichWillBeKeyInDict: + def __hash__(self): + return 1337 # dummy hash, used only for illustration + + s = Schema({HashableObjectWhichWillBeKeyInDict: [int]}) + + hashable_obj_provided_in_input = HashableObjectWhichWillBeKeyInDict() + + with pytest.raises(MultipleInvalid) as ctx: + s({hashable_obj_provided_in_input: [0, 1, 'should be int']}) + assert ctx.value.errors[0].path == [hashable_obj_provided_in_input, 2] + + def test_self_any(): schema = Schema({"number": int, "follow": Any(Self, "stop")}) diff --git a/voluptuous/validators.py b/voluptuous/validators.py index 776adb8..6c02813 100644 --- a/voluptuous/validators.py +++ b/voluptuous/validators.py @@ -224,7 +224,7 @@ def __voluptuous_compile__(self, schema: Schema) -> typing.Callable: schema.required = old_required return self._run - def _run(self, path: typing.List[str], value): + def _run(self, path: typing.List[typing.Hashable], value): if self.discriminant is not None: self._compiled = [ self.schema._compile(v) @@ -243,7 +243,7 @@ def __repr__(self): self.msg ) - def _exec(self, funcs: typing.Iterable, v, path: typing.Optional[typing.List[str]] = None): + def _exec(self, funcs: typing.Iterable, v, path: typing.Optional[typing.List[typing.Hashable]] = None): raise NotImplementedError()