Debian Codegraph @

tests/test_pydantic_migrate.py

raw symbols SCIP
1 import warnings
2 from typing import Optional
3
4 import pytest
5 from django.db import models
6 from pydantic import BaseModel, ValidationError
7
8 from ninja import ModelSchema, Schema
9
10
11 class OptModel(BaseModel):
12 a: int = None
13 b: Optional[int]
14 c: Optional[int] = None
15
16
17 class OptSchema(Schema):
18 a: int = None
19 b: Optional[int]
20 c: Optional[int] = None
21
22
23 def test_optional_pydantic_model():
24 with pytest.raises(ValidationError):
25 OptModel().dict()
26
27 assert OptModel(b=None).model_dump() == {"a": None, "b": None, "c": None}
28
29
30 def test_optional_schema():
31 with pytest.raises(ValidationError):
32 OptSchema().dict()
33
34 assert OptSchema(b=None).dict() == {"a": None, "b": None, "c": None}
35
36
37 def test_deprecated_schema():
38 with warnings.catch_warnings(record=True) as w:
39 OptSchema.schema()
40 assert w[0].message.args == (".schema() is deprecated, use .json_schema() instead",)
41
42
43 def test_orm_config():
44 class SomeCustomModel(models.Model):
45 f1 = models.CharField()
46 f2 = models.CharField(blank=True, null=True)
47
48 class Meta:
49 app_label = "tests"
50
51 class SomeCustomSchema(ModelSchema):
52 f3: int
53 f4: int = 1
54 _private: str = "<secret>" # private should be ignored
55
56 class Meta:
57 model = SomeCustomModel
58 fields = ["f1", "f2"]
59
60 assert SomeCustomSchema.json_schema() == {
61 "title": "SomeCustomSchema",
62 "type": "object",
63 "properties": {
64 "f1": {"title": "F1", "type": "string"},
65 "f2": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "F2"},
66 "f3": {"title": "F3", "type": "integer"},
67 "f4": {"title": "F4", "default": 1, "type": "integer"},
68 },
69 "required": ["f3", "f1"],
70 }