1
+ from typing import Any
2
+
1
3
import pytest
4
+ from django import VERSION as DJANGO_VERSION
2
5
from django .core import checks
6
+ from django .core .exceptions import ValidationError
3
7
from django .db import models
4
8
5
9
from django_custom_jsonfield .fields import CustomJSONField
13
17
{"pattern" : "*invalid.regex" },
14
18
],
15
19
)
16
- def test_model_check_invalid_schema (schema : dict ):
20
+ def test_json_schema_invalid (schema : dict ):
17
21
class FakeModel (models .Model ):
18
22
json_field = CustomJSONField (schema = schema )
19
23
@@ -31,3 +35,77 @@ class Meta:
31
35
]
32
36
33
37
assert errors == expected_errors
38
+
39
+
40
+ def test_json_schema_ok ():
41
+ class FakeModel (models .Model ):
42
+ json_field = CustomJSONField (
43
+ schema = {
44
+ "type" : "array" ,
45
+ "minLength" : 1 ,
46
+ "maxLength" : 1 ,
47
+ "items" : {"type" : "integer" },
48
+ },
49
+ )
50
+
51
+ class Meta :
52
+ app_label = "test_app"
53
+
54
+ instance = FakeModel ()
55
+
56
+ assert instance .check () == []
57
+
58
+
59
+ @pytest .mark .parametrize (
60
+ "schema" ,
61
+ [10 , 10.00 , list (), tuple (), set (), "" , b"" , True , None ],
62
+ )
63
+ def test_schema_type_invalid (schema : Any ):
64
+ with pytest .raises (ValueError ) as e :
65
+ CustomJSONField (schema = schema )
66
+
67
+ assert e .value .args [0 ] == "The schema parameter must be a dictionary."
68
+
69
+
70
+ @pytest .mark .parametrize (
71
+ "value,schema" ,
72
+ [
73
+ (
74
+ {"name" : "John" },
75
+ {
76
+ "type" : "object" ,
77
+ "properties" : {"name" : {"type" : "string" }, "age" : {"type" : "integer" }},
78
+ "required" : ["name" , "age" ],
79
+ },
80
+ ),
81
+ ],
82
+ )
83
+ def test_validate_value_against_schema (value , schema ):
84
+ class FakeModel (models .Model ):
85
+ json_field = CustomJSONField (schema = schema )
86
+
87
+ class Meta :
88
+ app_label = "test_app"
89
+
90
+ instance = FakeModel ()
91
+ instance .json_field = value
92
+
93
+ with pytest .raises (ValidationError ) as e :
94
+ instance .clean_fields ()
95
+
96
+ assert isinstance (e .value .args [0 ]["json_field" ][0 ], ValidationError )
97
+ assert e .value .args [0 ]["json_field" ][0 ].args [0 ] == "Value does not match the JSON schema."
98
+ assert e .value .args [0 ]["json_field" ][0 ].args [1 ] == "invalid_data"
99
+ assert e .value .args [0 ]["json_field" ][0 ].args [2 ] == {"value" : value }
100
+
101
+
102
+ def test_deconstruct ():
103
+ json_field = CustomJSONField (schema = {})
104
+ _ , _ , _ , kwargs = json_field .deconstruct ()
105
+ assert "schema" in kwargs
106
+
107
+
108
+ @pytest .mark .skipif (DJANGO_VERSION < (4 , 1 ), reason = "non_db_attrs is only available in Django 4.1+" )
109
+ def test_non_db_attrs ():
110
+ json_field = CustomJSONField (schema = {})
111
+ assert "schema" in json_field .non_db_attrs
0 commit comments