Skip to content

Commit f7ebce5

Browse files
committed
Return all JSON schema errors
This is currently failing due to python-jsonschema/jsonschema#411
1 parent 575c4fd commit f7ebce5

File tree

2 files changed

+17
-11
lines changed

2 files changed

+17
-11
lines changed

src/rest_toolkit/ext/jsonschema.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
from __future__ import absolute_import
22
import abc
33
import jsonschema
4+
from jsonschema.validators import validator_for
45
from pyramid.httpexceptions import HTTPBadRequest
56
from ..compat import add_metaclass
6-
from ..utils import add_missing
77

88

99
class JSONValidationError(HTTPBadRequest):
1010
"""HTTP response for JSON validation errors.
1111
"""
1212

13+
1314
def validate(data, schema):
1415
"""Validate data against a JSON schema.
1516
@@ -21,15 +22,12 @@ def validate(data, schema):
2122
:raises pyramid.httpexceptions.HTTPBadRequest: if validation fails this
2223
exception is raised to abort any further processing.
2324
"""
24-
try:
25-
jsonschema.validate(data, schema,
26-
format_checker=jsonschema.draft4_format_checker)
27-
except jsonschema.ValidationError as e:
28-
error = {
29-
'.'.join(str(p) for p in e.path): e.message
30-
}
31-
response = JSONValidationError(json=error)
32-
response.validation_error = e
25+
validator = validator_for(schema)
26+
errors = {}
27+
for e in validator(schema).iter_errors(data):
28+
errors['.'.join(str(p) for p in e.path)] = e.message
29+
if errors:
30+
response = JSONValidationError(json=errors)
3331
raise response
3432

3533

tests/ext/test_jsonschema.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
class DummyResource(JsonSchemaValidationMixin, EditableResource):
88
schema = {
9-
'$schema': 'http://json-schema.org/draft-04/schema',
109
'type': 'object',
1110
'properties': {
1211
'email': {
@@ -57,6 +56,15 @@ def test_array_validation_error():
5756
}, partial=False)
5857

5958

59+
def test_multiple_errors():
60+
resource = DummyResource()
61+
with pytest.raises(HTTPBadRequest) as exc_info:
62+
import pdb ; pdb.set_trace()
63+
resource.validate({})
64+
assert 'email' in exc_info.value.json
65+
assert 'password' in exc_info.value.json
66+
67+
6068
def test_partial_data():
6169
resource = DummyResource()
6270
resource.to_dict = lambda: {'password': 'Jane'}

0 commit comments

Comments
 (0)