Debian Codegraph @

tests/test_orm_schemas.py

raw symbols SCIP
1 from typing import List
2 from unittest.mock import Mock
3
4 import pydantic
5 import pytest
6 from django.contrib.postgres import fields as ps_fields
7 from django.db import models
8 from django.db.models import Manager
9 from util import pydantic_ref_fix
10
11 from ninja.errors import ConfigError
12 from ninja.orm import create_schema, register_field
13 from ninja.orm.shortcuts import L, S
14
15
16 def test_inheritance():
17 class ParentModel(models.Model):
18 parent_field = models.CharField()
19
20 class Meta:
21 app_label = "tests"
22
23 class ChildModel(ParentModel):
24 child_field = models.CharField()
25
26 class Meta:
27 app_label = "tests"
28
29 Schema = create_schema(ChildModel)
30 # print(Schema.json_schema())
31
32 # TODO: I guess parentmodel_ptr_id must be skipped
33 assert Schema.json_schema() == {
34 "title": "ChildModel",
35 "type": "object",
36 "properties": {
37 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
38 "parent_field": {"type": "string", "title": "Parent Field"},
39 "parentmodel_ptr_id": {"type": "integer", "title": "Parentmodel Ptr"},
40 "child_field": {"type": "string", "title": "Child Field"},
41 },
42 "required": ["parent_field", "parentmodel_ptr_id", "child_field"],
43 }
44
45
46 def test_all_fields():
47 # test all except relational field
48
49 class AllFields(models.Model):
50 bigintegerfield = models.BigIntegerField()
51 binaryfield = models.BinaryField()
52 booleanfield = models.BooleanField()
53 charfield = models.CharField()
54 commaseparatedintegerfield = models.CommaSeparatedIntegerField()
55 datefield = models.DateField()
56 datetimefield = models.DateTimeField()
57 decimalfield = models.DecimalField()
58 durationfield = models.DurationField()
59 emailfield = models.EmailField()
60 filefield = models.FileField()
61 filepathfield = models.FilePathField()
62 floatfield = models.FloatField()
63 genericipaddressfield = models.GenericIPAddressField()
64 ipaddressfield = models.IPAddressField()
65 imagefield = models.ImageField()
66 integerfield = models.IntegerField()
67 nullbooleanfield = models.NullBooleanField()
68 positiveintegerfield = models.PositiveIntegerField()
69 positivesmallintegerfield = models.PositiveSmallIntegerField()
70 slugfield = models.SlugField()
71 smallintegerfield = models.SmallIntegerField()
72 textfield = models.TextField()
73 timefield = models.TimeField()
74 urlfield = models.URLField()
75 uuidfield = models.UUIDField()
76 arrayfield = ps_fields.ArrayField(models.CharField())
77 cicharfield = ps_fields.CICharField()
78 ciemailfield = ps_fields.CIEmailField()
79 citextfield = ps_fields.CITextField()
80 hstorefield = ps_fields.HStoreField()
81
82 class Meta:
83 app_label = "tests"
84
85 SchemaCls = create_schema(AllFields)
86 # print(SchemaCls.json_schema())
87 expected_schema = {
88 "title": "AllFields",
89 "type": "object",
90 "properties": {
91 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
92 "bigintegerfield": {"title": "Bigintegerfield", "type": "integer"},
93 "binaryfield": {
94 "title": "Binaryfield",
95 "type": "string",
96 "format": "binary",
97 },
98 "booleanfield": {"type": "boolean", "title": "Booleanfield"},
99 "charfield": {"type": "string", "title": "Charfield"},
100 "commaseparatedintegerfield": {
101 "title": "Commaseparatedintegerfield",
102 "type": "string",
103 },
104 "datefield": {"type": "string", "format": "date", "title": "Datefield"},
105 "datetimefield": {
106 "title": "Datetimefield",
107 "type": "string",
108 "format": "date-time",
109 },
110 "decimalfield": {
111 "anyOf": [
112 {"type": "number"},
113 {"type": "string"},
114 ],
115 "title": "Decimalfield",
116 },
117 "durationfield": {
118 "type": "string",
119 "format": "duration",
120 "title": "Durationfield",
121 },
122 "emailfield": {"type": "string", "maxLength": 254, "title": "Emailfield"},
123 "filefield": {"type": "string", "title": "Filefield"},
124 "filepathfield": {"type": "string", "title": "Filepathfield"},
125 "floatfield": {"type": "number", "title": "Floatfield"},
126 "genericipaddressfield": {
127 "type": "string",
128 "format": "ipvanyaddress",
129 "title": "Genericipaddressfield",
130 },
131 "ipaddressfield": {
132 "type": "string",
133 "format": "ipvanyaddress",
134 "title": "Ipaddressfield",
135 },
136 "imagefield": {"type": "string", "title": "Imagefield"},
137 "integerfield": {"type": "integer", "title": "Integerfield"},
138 "nullbooleanfield": {"type": "boolean", "title": "Nullbooleanfield"},
139 "positiveintegerfield": {
140 "type": "integer",
141 "title": "Positiveintegerfield",
142 },
143 "positivesmallintegerfield": {
144 "type": "integer",
145 "title": "Positivesmallintegerfield",
146 },
147 "slugfield": {"type": "string", "title": "Slugfield"},
148 "smallintegerfield": {"type": "integer", "title": "Smallintegerfield"},
149 "textfield": {"type": "string", "title": "Textfield"},
150 "timefield": {"type": "string", "format": "time", "title": "Timefield"},
151 "urlfield": {"type": "string", "title": "Urlfield"},
152 "uuidfield": {"type": "string", "format": "uuid", "title": "Uuidfield"},
153 "arrayfield": {"type": "array", "items": {}, "title": "Arrayfield"},
154 "cicharfield": {"type": "string", "title": "Cicharfield"},
155 "ciemailfield": {
156 "type": "string",
157 "maxLength": 254,
158 "title": "Ciemailfield",
159 },
160 "citextfield": {"type": "string", "title": "Citextfield"},
161 "hstorefield": {
162 # "additionalProperties": True, # this is added in pydantic 2.11
163 "type": "object",
164 "title": "Hstorefield",
165 },
166 },
167 "required": [
168 "bigintegerfield",
169 "binaryfield",
170 "booleanfield",
171 "charfield",
172 "commaseparatedintegerfield",
173 "datefield",
174 "datetimefield",
175 "decimalfield",
176 "durationfield",
177 "emailfield",
178 "filefield",
179 "filepathfield",
180 "floatfield",
181 "genericipaddressfield",
182 "ipaddressfield",
183 "imagefield",
184 "integerfield",
185 "nullbooleanfield",
186 "positiveintegerfield",
187 "positivesmallintegerfield",
188 "slugfield",
189 "smallintegerfield",
190 "textfield",
191 "timefield",
192 "urlfield",
193 "uuidfield",
194 "arrayfield",
195 "cicharfield",
196 "ciemailfield",
197 "citextfield",
198 "hstorefield",
199 ],
200 }
201
202 pydantic_version = tuple(map(int, pydantic.VERSION.split(".")[:2]))
203 if pydantic_version >= (2, 11):
204 expected_schema["properties"]["hstorefield"]["additionalProperties"] = True
205 if pydantic_version >= (2, 12):
206 # Pydantic 2.12 added pattern validation for decimal strings
207 expected_schema["properties"]["decimalfield"]["anyOf"][1]["pattern"] = (
208 r"^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$"
209 )
210 assert SchemaCls.json_schema() == expected_schema
211
212
213 def test_altautofield():
214 class ModelWithBigAutoField(models.Model):
215 autofield = models.BigAutoField(primary_key=True)
216
217 class Meta:
218 app_label = "tests"
219
220 class ModelWithSmallAutoField(models.Model):
221 autofield = models.SmallAutoField(primary_key=True)
222
223 class Meta:
224 app_label = "tests"
225
226 BigSchema = create_schema(ModelWithBigAutoField)
227 SmallSchema = create_schema(ModelWithSmallAutoField)
228
229 for cls in [BigSchema, SmallSchema]:
230 print(cls.json_schema()["properties"])
231 assert cls.json_schema()["properties"] == {
232 "autofield": {
233 "anyOf": [{"type": "integer"}, {"type": "null"}],
234 "title": "Autofield",
235 }
236 }
237
238
239 def test_django_31_fields():
240 class ModelNewFields(models.Model):
241 jsonfield = models.JSONField()
242 positivebigintegerfield = models.PositiveBigIntegerField()
243
244 class Meta:
245 app_label = "tests"
246
247 Schema = create_schema(ModelNewFields)
248 # print(Schema.json_schema())
249 assert Schema.json_schema() == {
250 "title": "ModelNewFields",
251 "type": "object",
252 "properties": {
253 "id": {"title": "ID", "anyOf": [{"type": "integer"}, {"type": "null"}]},
254 "jsonfield": {"title": "Jsonfield", "type": "object"},
255 "positivebigintegerfield": {
256 "title": "Positivebigintegerfield",
257 "type": "integer",
258 },
259 },
260 "required": ["jsonfield", "positivebigintegerfield"],
261 }
262
263 obj = Schema(id=1, jsonfield={"any": "data"}, positivebigintegerfield=1)
264 assert obj.dict() == {
265 "id": 1,
266 "jsonfield": {"any": "data"},
267 "positivebigintegerfield": 1,
268 }
269
270
271 def test_relational():
272 class Related(models.Model):
273 charfield = models.CharField()
274
275 class Meta:
276 app_label = "tests"
277
278 class TestModel(models.Model):
279 manytomanyfield = models.ManyToManyField(Related)
280 onetoonefield = models.OneToOneField(Related, on_delete=models.CASCADE)
281 foreignkey = models.ForeignKey(Related, on_delete=models.SET_NULL, null=True)
282
283 class Meta:
284 app_label = "tests"
285
286 SchemaCls = create_schema(TestModel, name="TestSchema")
287 # print(SchemaCls.json_schema())
288 assert SchemaCls.json_schema() == {
289 "title": "TestSchema",
290 "type": "object",
291 "properties": {
292 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
293 "onetoonefield_id": {"title": "Onetoonefield", "type": "integer"},
294 "foreignkey_id": {
295 "anyOf": [{"type": "integer"}, {"type": "null"}],
296 "title": "Foreignkey",
297 },
298 "manytomanyfield": {
299 "title": "Manytomanyfield",
300 "type": "array",
301 "items": {"type": "integer"},
302 },
303 },
304 "required": ["onetoonefield_id", "manytomanyfield"],
305 }
306
307 SchemaClsDeep = create_schema(TestModel, name="TestSchemaDeep", depth=1)
308 print(SchemaClsDeep.json_schema())
309 assert SchemaClsDeep.json_schema() == {
310 "type": "object",
311 "properties": {
312 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
313 "onetoonefield": pydantic_ref_fix({
314 "title": "Onetoonefield",
315 "description": "",
316 "$ref": "#/$defs/Related",
317 }),
318 "foreignkey": {
319 "title": "Foreignkey",
320 "allOf": [{"$ref": "#/$defs/Related"}],
321 "description": "",
322 },
323 "manytomanyfield": {
324 "title": "Manytomanyfield",
325 "type": "array",
326 "items": {"$ref": "#/$defs/Related"},
327 "description": "",
328 },
329 },
330 "required": ["onetoonefield", "manytomanyfield"],
331 "title": "TestSchemaDeep",
332 "$defs": {
333 "Related": {
334 "title": "Related",
335 "type": "object",
336 "properties": {
337 "id": {
338 "anyOf": [{"type": "integer"}, {"type": "null"}],
339 "title": "ID",
340 },
341 "charfield": {"type": "string", "title": "Charfield"},
342 },
343 "required": ["charfield"],
344 }
345 },
346 }
347
348
349 def test_default():
350 class MyModel(models.Model):
351 default_static = models.CharField(default="hello")
352 default_dynamic = models.CharField(default=lambda: "world")
353
354 class Meta:
355 app_label = "tests"
356
357 Schema = create_schema(MyModel)
358 # print(Schema.json_schema())
359 assert Schema.json_schema() == {
360 "title": "MyModel",
361 "type": "object",
362 "properties": {
363 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
364 "default_static": {
365 "default": "hello",
366 "title": "Default Static",
367 "type": "string",
368 },
369 "default_dynamic": {"title": "Default Dynamic", "type": "string"},
370 },
371 }
372
373
374 def test_fields_exclude():
375 class SampleModel(models.Model):
376 f1 = models.CharField()
377 f2 = models.CharField()
378 f3 = models.CharField()
379
380 class Meta:
381 app_label = "tests"
382
383 Schema1 = create_schema(SampleModel, fields=["f1", "f2"])
384 # print(Schema1.json_schema())
385 assert Schema1.json_schema() == {
386 "title": "SampleModel",
387 "type": "object",
388 "properties": {
389 "f1": {"type": "string", "title": "F1"},
390 "f2": {"type": "string", "title": "F2"},
391 },
392 "required": ["f1", "f2"],
393 }
394
395 Schema2 = create_schema(SampleModel, fields=["f3", "f2"])
396 # print(Schema2.json_schema())
397 assert Schema2.json_schema() == {
398 "title": "SampleModel2",
399 "type": "object",
400 "properties": {
401 "f3": {"title": "F3", "type": "string"},
402 "f2": {"title": "F2", "type": "string"},
403 },
404 "required": ["f3", "f2"],
405 }
406
407 Schema3 = create_schema(SampleModel, exclude=["f3"])
408 # print(Schema3.json_schema())
409 assert Schema3.json_schema() == {
410 "type": "object",
411 "properties": {
412 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
413 "f1": {"type": "string", "title": "F1"},
414 "f2": {"type": "string", "title": "F2"},
415 },
416 "required": ["f1", "f2"],
417 "title": "SampleModel3",
418 }
419
420
421 def test_exceptions():
422 class MyModel2(models.Model):
423 f1 = models.CharField()
424 f2 = models.CharField()
425
426 class Meta:
427 app_label = "tests"
428
429 with pytest.raises(
430 ConfigError, match="Only one of 'fields' or 'exclude' should be set."
431 ):
432 create_schema(MyModel2, fields=["f1"], exclude=["f2"])
433
434 with pytest.raises(ConfigError):
435 create_schema(MyModel2, fields=["f_invalid"])
436
437
438 def test_shortcuts():
439 class MyModel3(models.Model):
440 f1 = models.CharField()
441
442 class Meta:
443 app_label = "tests"
444
445 schema = S(MyModel3)
446 schema_list = L(MyModel3)
447 assert List[schema] == schema_list
448
449
450 @pytest.mark.django_db
451 def test_with_relations():
452 # this test basically does full coverage for the case when we skip automatic relation attributes
453 from someapp.models import Category
454
455 Schema = create_schema(Category)
456 # print(Schema.json_schema())
457 assert Schema.json_schema() == {
458 "title": "Category",
459 "type": "object",
460 "properties": {
461 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
462 "title": {"title": "Title", "maxLength": 100, "type": "string"},
463 },
464 "required": ["title"],
465 }
466
467
468 def test_manytomany():
469 class Foo(models.Model):
470 f = models.CharField()
471
472 class Meta:
473 app_label = "tests"
474
475 class Bar(models.Model):
476 m2m = models.ManyToManyField(Foo, blank=True)
477
478 class Meta:
479 app_label = "tests"
480
481 Schema = create_schema(Bar)
482
483 # mocking database data:
484
485 foo = Mock()
486 foo.pk = 1
487 foo.f = "test"
488
489 m2m = Mock(spec=Manager)
490 m2m.all = lambda: [foo]
491
492 bar = Mock()
493 bar.id = 1
494 bar.m2m = m2m
495
496 data = Schema.from_orm(bar).dict()
497
498 assert data == {"id": 1, "m2m": [1]}
499
500
501 def test_custom_fields():
502 class SmallModel(models.Model):
503 f1 = models.CharField()
504 f2 = models.CharField()
505
506 class Meta:
507 app_label = "tests"
508
509 Schema1 = create_schema(SmallModel, custom_fields=[("custom", int, ...)])
510
511 # print(Schema1.json_schema())
512 assert Schema1.json_schema() == {
513 "type": "object",
514 "properties": {
515 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
516 "f1": {"type": "string", "title": "F1"},
517 "f2": {"type": "string", "title": "F2"},
518 "custom": {"type": "integer", "title": "Custom"},
519 },
520 "required": ["f1", "f2", "custom"],
521 "title": "SmallModel",
522 }
523
524 Schema2 = create_schema(SmallModel, custom_fields=[("f1", int, ...)])
525 # print(Schema2.json_schema())
526
527 assert Schema2.json_schema() == {
528 "type": "object",
529 "properties": {
530 "id": {"anyOf": [{"type": "integer"}, {"type": "null"}], "title": "ID"},
531 "f1": {"type": "integer", "title": "F1"},
532 "f2": {"type": "string", "title": "F2"},
533 },
534 "required": ["f1", "f2"],
535 "title": "SmallModel2",
536 }
537
538
539 def test_duplicate_schema_names():
540 from django.db import models
541
542 from ninja import Schema
543 from ninja.orm import create_schema
544
545 class TestModelDuplicate(models.Model):
546 field1 = models.CharField()
547 field2 = models.CharField()
548
549 class Meta:
550 app_label = "tests"
551
552 class TestSchema(Schema):
553 data1: create_schema(TestModelDuplicate, fields=["field1"]) # noqa: F821
554 data2: create_schema(TestModelDuplicate, fields=["field2"]) # noqa: F821
555
556 # print(TestSchema.json_schema())
557
558 assert TestSchema.json_schema() == {
559 "type": "object",
560 "properties": {
561 "data1": {"$ref": "#/$defs/TestModelDuplicate"},
562 "data2": {"$ref": "#/$defs/TestModelDuplicate2"},
563 },
564 "required": ["data1", "data2"],
565 "title": "TestSchema",
566 "$defs": {
567 "TestModelDuplicate": {
568 "type": "object",
569 "properties": {"field1": {"type": "string", "title": "Field1"}},
570 "required": ["field1"],
571 "title": "TestModelDuplicate",
572 },
573 "TestModelDuplicate2": {
574 "type": "object",
575 "properties": {"field2": {"type": "string", "title": "Field2"}},
576 "required": ["field2"],
577 "title": "TestModelDuplicate2",
578 },
579 },
580 }
581
582
583 def test_optional_fields():
584 class SomeReqFieldModel(models.Model):
585 some_field = models.CharField()
586 other_field = models.IntegerField()
587 optional = models.IntegerField(null=True, blank=True)
588
589 class Meta:
590 app_label = "tests"
591
592 Schema = create_schema(SomeReqFieldModel)
593 assert Schema.json_schema()["required"] == ["some_field", "other_field"]
594
595 Schema = create_schema(SomeReqFieldModel, optional_fields=["some_field"])
596 assert Schema.json_schema()["required"] == ["other_field"]
597
598 Schema = create_schema(
599 SomeReqFieldModel, optional_fields=["some_field", "other_field", "optional"]
600 )
601 assert Schema.json_schema().get("required") is None
602
603
604 def test_register_custom_field():
605 class MyCustomField(models.Field):
606 description = "MyCustomField"
607
608 class ModelWithCustomField(models.Model):
609 some_field = MyCustomField()
610
611 class Meta:
612 app_label = "tests"
613
614 with pytest.raises(ConfigError):
615 create_schema(ModelWithCustomField)
616
617 register_field("MyCustomField", int)
618 Schema = create_schema(ModelWithCustomField)
619 print(Schema.json_schema())
620 assert Schema.json_schema()["properties"]["some_field"]["type"] == "integer"