Skip to content

Commit

Permalink
Fix best_match's type matching when it's an array.
Browse files Browse the repository at this point in the history
Closes: #973
  • Loading branch information
Julian committed Jul 12, 2022
1 parent 8819f46 commit 72c3200
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
v4.7.2
------

* Also have ``best_match`` handle cases where the ``type`` validator is an
array.

v4.7.1
------

Expand Down
12 changes: 9 additions & 3 deletions jsonschema/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
27 changes: 27 additions & 0 deletions jsonschema/tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 72c3200

Please sign in to comment.