Skip to content

Commit 72c3200

Browse files
committed
Fix best_match's type matching when it's an array.
Closes: #973
1 parent 8819f46 commit 72c3200

File tree

3 files changed

+42
-3
lines changed

3 files changed

+42
-3
lines changed

CHANGELOG.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
v4.7.2
2+
------
3+
4+
* Also have ``best_match`` handle cases where the ``type`` validator is an
5+
array.
6+
17
v4.7.1
28
------
39

jsonschema/exceptions.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,11 +143,17 @@ def _contents(self):
143143

144144
def _matches_type(self):
145145
try:
146-
expected_type = self.schema["type"]
146+
expected = self.schema["type"]
147147
except (KeyError, TypeError):
148148
return False
149-
else:
150-
return self._type_checker.is_type(self.instance, expected_type)
149+
150+
if isinstance(expected, str):
151+
return self._type_checker.is_type(self.instance, expected)
152+
153+
return any(
154+
self._type_checker.is_type(self.instance, expected_type)
155+
for expected_type in expected
156+
)
151157

152158

153159
class ValidationError(_Error):

jsonschema/tests/test_exceptions.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,33 @@ def test_it_prioritizes_matching_types(self):
158158
best = self.best_match_of(instance={"foo": "bar"}, schema=reordered)
159159
self.assertEqual(best.validator, "minLength")
160160

161+
def test_it_prioritizes_matching_union_types(self):
162+
schema = {
163+
"properties": {
164+
"foo": {
165+
"anyOf": [
166+
{"type": ["array", "object"], "minItems": 2},
167+
{"type": ["integer", "string"], "minLength": 10},
168+
],
169+
},
170+
},
171+
}
172+
best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
173+
self.assertEqual(best.validator, "minLength")
174+
175+
reordered = {
176+
"properties": {
177+
"foo": {
178+
"anyOf": [
179+
{"type": "string", "minLength": 10},
180+
{"type": "array", "minItems": 2},
181+
],
182+
},
183+
},
184+
}
185+
best = self.best_match_of(instance={"foo": "bar"}, schema=reordered)
186+
self.assertEqual(best.validator, "minLength")
187+
161188
def test_boolean_schemas(self):
162189
schema = {"properties": {"foo": False}}
163190
best = self.best_match_of(instance={"foo": "bar"}, schema=schema)

0 commit comments

Comments
 (0)