Skip to content

Commit 17fb9cb

Browse files
committed
Make validate use best_match.
This function is essentially meant to be the 'dead simple', newbie friendly entry into validation. Making it use best_match means even friendlier initial errors, so we switch to using that. Users who care about potential small effects this has on performance should already likely be using an explicitly constructed validator class, and choosing themselves whether to call best_match or not. Closes: #498
1 parent b234ae8 commit 17fb9cb

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

jsonschema/tests/test_validators.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -358,13 +358,12 @@ def test_multiple_type_failure(self):
358358
def test_object_without_title_type_failure(self):
359359
type = {u"type": [{u"minimum": 3}]}
360360
message = self.message_for(instance=1, schema={u"type": [type]})
361-
self.assertEqual(message, "1 is not of type %r" % (type,))
361+
self.assertEqual(message, "1 is less than the minimum of 3")
362362

363-
def test_object_with_name_type_failure(self):
364-
name = "Foo"
365-
schema = {u"type": [{u"name": name, u"minimum": 3}]}
363+
def test_object_with_named_type_failure(self):
364+
schema = {u"type": [{u"name": "Foo", u"minimum": 3}]}
366365
message = self.message_for(instance=1, schema=schema)
367-
self.assertEqual(message, "1 is not of type %r" % (name,))
366+
self.assertEqual(message, "1 is less than the minimum of 3")
368367

369368
def test_minimum(self):
370369
message = self.message_for(instance=1, schema={"minimum": 2})
@@ -1324,6 +1323,13 @@ def test_schema_error_message(self):
13241323
"(?s)Failed validating u?'.*' in metaschema.*On schema",
13251324
)
13261325

1326+
def test_it_uses_best_match(self):
1327+
# This is a schema that best_match will recurse into
1328+
schema = {"oneOf": [{"type": "string"}, {"type": "array"}]}
1329+
with self.assertRaises(exceptions.ValidationError) as e:
1330+
validators.validate(12, schema)
1331+
self.assertIn("12 is not of type", str(e.exception))
1332+
13271333

13281334
class TestRefResolver(SynchronousTestCase):
13291335

jsonschema/validators.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -862,8 +862,12 @@ def validate(instance, schema, cls=None, *args, **kwargs):
862862
"""
863863
if cls is None:
864864
cls = validator_for(schema)
865+
865866
cls.check_schema(schema)
866-
cls(schema, *args, **kwargs).validate(instance)
867+
validator = cls(schema, *args, **kwargs)
868+
error = exceptions.best_match(validator.iter_errors(instance))
869+
if error is not None:
870+
raise error
867871

868872

869873
def validator_for(schema, default=_LATEST_VERSION):

0 commit comments

Comments
 (0)