File tree 2 files changed +30
-3
lines changed
django_custom_jsonfield/rest_framework
2 files changed +30
-3
lines changed Original file line number Diff line number Diff line change 1
1
import jsonschema
2
2
from django .utils .translation import gettext_lazy as _
3
+ from jsonschema import validators
3
4
from rest_framework import serializers
4
5
5
6
6
7
class CustomJSONField (serializers .JSONField ):
7
8
default_error_messages = {
8
9
"invalid_data" : _ ("Value does not match the JSON schema." ),
10
+ "invalid_schema" : _ ("Invalid JSON schema." ),
9
11
}
10
12
11
13
def __init__ (self , schema : dict , ** kwargs ):
12
14
self .schema = schema
13
15
super ().__init__ (** kwargs )
16
+
17
+ validator = validators .validator_for (self .schema )
18
+ try :
19
+ validator .check_schema (self .schema )
20
+ except jsonschema .exceptions .SchemaError :
21
+ self .fail ("invalid_schema" )
22
+
14
23
self .validators .append (self ._validate_data )
15
24
16
25
def _validate_data (self , value ):
Original file line number Diff line number Diff line change 1
1
import pytest
2
- from rest_framework import serializers
3
- from rest_framework .exceptions import ErrorDetail
2
+ from rest_framework import exceptions , serializers
4
3
5
4
from django_custom_jsonfield .rest_framework .serializers import CustomJSONField
6
5
@@ -27,10 +26,29 @@ class FakeSerializer(serializers.Serializer):
27
26
28
27
expected_errors = {
29
28
"json_field" : [
30
- ErrorDetail (
29
+ exceptions . ErrorDetail (
31
30
string = "Value does not match the JSON schema." ,
32
31
code = "invalid_data" ,
33
32
),
34
33
],
35
34
}
36
35
assert serializer .errors == expected_errors
36
+
37
+
38
+ @pytest .mark .parametrize (
39
+ "schema" ,
40
+ [
41
+ {"minItems" : "1" },
42
+ {"properties" : 1 },
43
+ {"pattern" : "*invalid.regex" },
44
+ ],
45
+ )
46
+ def test_map_serializer_field_invalid_schema (schema : dict ):
47
+ """Test serializer raises an exception if JSON schema is invalid."""
48
+
49
+ with pytest .raises (exceptions .ValidationError ) as e :
50
+ CustomJSONField (schema = schema )
51
+
52
+ assert isinstance (e .value , exceptions .ValidationError )
53
+ assert e .value .detail [0 ] == "Invalid JSON schema."
54
+ assert e .value .detail [0 ].code == "invalid_schema"
You can’t perform that action at this time.
0 commit comments