diff --git a/CHANGELOG.rst b/CHANGELOG.rst index b422124b9..996cb6261 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,3 +1,9 @@ +v4.7.2 +------ + +* Also have ``best_match`` handle cases where the ``type`` validator is an + array. + v4.7.1 ------ diff --git a/jsonschema/exceptions.py b/jsonschema/exceptions.py index 07beb2d6b..927468fc3 100644 --- a/jsonschema/exceptions.py +++ b/jsonschema/exceptions.py @@ -143,11 +143,17 @@ def _contents(self): def _matches_type(self): try: - expected_type = self.schema["type"] + expected = self.schema["type"] except (KeyError, TypeError): return False - else: - return self._type_checker.is_type(self.instance, expected_type) + + if isinstance(expected, str): + return self._type_checker.is_type(self.instance, expected) + + return any( + self._type_checker.is_type(self.instance, expected_type) + for expected_type in expected + ) class ValidationError(_Error): diff --git a/jsonschema/tests/test_exceptions.py b/jsonschema/tests/test_exceptions.py index c3c525583..d641ac56c 100644 --- a/jsonschema/tests/test_exceptions.py +++ b/jsonschema/tests/test_exceptions.py @@ -158,6 +158,33 @@ def test_it_prioritizes_matching_types(self): best = self.best_match_of(instance={"foo": "bar"}, schema=reordered) self.assertEqual(best.validator, "minLength") + def test_it_prioritizes_matching_union_types(self): + schema = { + "properties": { + "foo": { + "anyOf": [ + {"type": ["array", "object"], "minItems": 2}, + {"type": ["integer", "string"], "minLength": 10}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": "bar"}, schema=schema) + self.assertEqual(best.validator, "minLength") + + reordered = { + "properties": { + "foo": { + "anyOf": [ + {"type": "string", "minLength": 10}, + {"type": "array", "minItems": 2}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": "bar"}, schema=reordered) + self.assertEqual(best.validator, "minLength") + def test_boolean_schemas(self): schema = {"properties": {"foo": False}} best = self.best_match_of(instance={"foo": "bar"}, schema=schema)