| 1 |
from typing import List, Optional, Union |
| 2 |
from unittest.mock import Mock |
| 3 |
|
| 4 |
import pytest |
| 5 |
from django.db.models import Manager, QuerySet |
| 6 |
from django.db.models.fields.files import ImageFieldFile |
| 7 |
from pydantic_core import ValidationError |
| 8 |
|
| 9 |
from ninja import Schema |
| 10 |
from ninja.schema import DjangoGetter, Field |
| 11 |
|
| 12 |
|
| 13 |
class FakeManager(Manager): |
| 14 |
def __init__(self, items): |
| 15 |
self._items = items |
| 16 |
|
| 17 |
def all(self): |
| 18 |
return self._items |
| 19 |
|
| 20 |
def __str__(self): |
| 21 |
return "FakeManager" |
| 22 |
|
| 23 |
|
| 24 |
class FakeQS(QuerySet): |
| 25 |
def __init__(self, items): |
| 26 |
self._result_cache = items |
| 27 |
self._prefetch_related_lookups = False |
| 28 |
|
| 29 |
def __str__(self): |
| 30 |
return "FakeQS" |
| 31 |
|
| 32 |
|
| 33 |
class Tag: |
| 34 |
def __init__(self, id, title): |
| 35 |
self.id = id |
| 36 |
self.title = title |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
class Boss: |
| 41 |
name = "Jane Jackson" |
| 42 |
title = "CEO" |
| 43 |
|
| 44 |
|
| 45 |
class User: |
| 46 |
name = "John Smith" |
| 47 |
group_set = FakeManager([1, 2, 3]) |
| 48 |
avatar = ImageFieldFile(None, Mock(), name=None) |
| 49 |
boss: Optional[Boss] = Boss() |
| 50 |
|
| 51 |
@property |
| 52 |
def tags(self): |
| 53 |
return FakeQS([Tag(1, "foo"), Tag(2, "bar")]) |
| 54 |
|
| 55 |
def get_boss_title(self): |
| 56 |
return self.boss and self.boss.title |
| 57 |
|
| 58 |
|
| 59 |
class TagSchema(Schema): |
| 60 |
id: int |
| 61 |
title: str |
| 62 |
|
| 63 |
|
| 64 |
class UserSchema(Schema): |
| 65 |
name: str |
| 66 |
groups: List[int] = Field(..., alias="group_set") |
| 67 |
tags: List[TagSchema] |
| 68 |
avatar: Optional[str] = None |
| 69 |
|
| 70 |
|
| 71 |
class UserWithBossSchema(UserSchema): |
| 72 |
boss: Optional[str] = Field(None, alias="boss.name") |
| 73 |
has_boss: bool |
| 74 |
boss_title: Optional[str] = Field(None, alias="get_boss_title") |
| 75 |
|
| 76 |
@staticmethod |
| 77 |
def resolve_has_boss(obj): |
| 78 |
return bool(obj.boss) |
| 79 |
|
| 80 |
|
| 81 |
class UserWithInitialsSchema(UserWithBossSchema): |
| 82 |
initials: str |
| 83 |
|
| 84 |
def resolve_initials(self, obj): |
| 85 |
return "".join(n[:1] for n in self.name.split()) |
| 86 |
|
| 87 |
|
| 88 |
class ResolveAttrSchema(Schema): |
| 89 |
"The goal is to test that the resolve_xxx is not callable it should be a regular attribute" |
| 90 |
|
| 91 |
id: str |
| 92 |
resolve_attr: str |
| 93 |
|
| 94 |
|
| 95 |
def test_schema(): |
| 96 |
user = User() |
| 97 |
schema = UserSchema.from_orm(user) |
| 98 |
assert schema.dict() == { |
| 99 |
"name": "John Smith", |
| 100 |
"groups": [1, 2, 3], |
| 101 |
"tags": [{"id": 1, "title": "foo"}, {"id": 2, "title": "bar"}], |
| 102 |
"avatar": None, |
| 103 |
} |
| 104 |
|
| 105 |
|
| 106 |
def test_schema_with_image(): |
| 107 |
user = User() |
| 108 |
field = Mock() |
| 109 |
field.storage.url = Mock(return_value="/smile.jpg") |
| 110 |
user.avatar = ImageFieldFile(None, field, name="smile.jpg") |
| 111 |
schema = UserSchema.from_orm(user) |
| 112 |
assert schema.dict() == { |
| 113 |
"name": "John Smith", |
| 114 |
"groups": [1, 2, 3], |
| 115 |
"tags": [{"id": 1, "title": "foo"}, {"id": 2, "title": "bar"}], |
| 116 |
"avatar": "/smile.jpg", |
| 117 |
} |
| 118 |
|
| 119 |
|
| 120 |
def test_with_boss_schema(): |
| 121 |
user = User() |
| 122 |
schema = UserWithBossSchema.from_orm(user) |
| 123 |
assert schema.dict() == { |
| 124 |
"name": "John Smith", |
| 125 |
"boss": "Jane Jackson", |
| 126 |
"has_boss": True, |
| 127 |
"groups": [1, 2, 3], |
| 128 |
"tags": [{"id": 1, "title": "foo"}, {"id": 2, "title": "bar"}], |
| 129 |
"avatar": None, |
| 130 |
"boss_title": "CEO", |
| 131 |
} |
| 132 |
|
| 133 |
user_without_boss = User() |
| 134 |
user_without_boss.boss = None |
| 135 |
schema = UserWithBossSchema.from_orm(user_without_boss) |
| 136 |
assert schema.dict() == { |
| 137 |
"name": "John Smith", |
| 138 |
"boss": None, |
| 139 |
"has_boss": False, |
| 140 |
"boss_title": None, |
| 141 |
"groups": [1, 2, 3], |
| 142 |
"tags": [{"id": 1, "title": "foo"}, {"id": 2, "title": "bar"}], |
| 143 |
"avatar": None, |
| 144 |
} |
| 145 |
|
| 146 |
|
| 147 |
SKIP_NON_STATIC_RESOLVES = True |
| 148 |
|
| 149 |
|
| 150 |
@pytest.mark.skipif(SKIP_NON_STATIC_RESOLVES, reason="Lets deal with this later") |
| 151 |
def test_with_initials_schema(): |
| 152 |
user = User() |
| 153 |
schema = UserWithInitialsSchema.from_orm(user) |
| 154 |
assert schema.dict() == { |
| 155 |
"name": "John Smith", |
| 156 |
"initials": "JS", |
| 157 |
"boss": "Jane Jackson", |
| 158 |
"has_boss": True, |
| 159 |
"groups": [1, 2, 3], |
| 160 |
"tags": [{"id": 1, "title": "foo"}, {"id": 2, "title": "bar"}], |
| 161 |
"avatar": None, |
| 162 |
"boss_title": "CEO", |
| 163 |
} |
| 164 |
|
| 165 |
|
| 166 |
def test_complex_alias_resolve(): |
| 167 |
class Top: |
| 168 |
class Midddle: |
| 169 |
def call(self): |
| 170 |
return {"dict": [1, 10]} |
| 171 |
|
| 172 |
m = Midddle() |
| 173 |
|
| 174 |
class AliasSchema(Schema): |
| 175 |
value: int = Field(..., alias="m.call.dict.1") |
| 176 |
|
| 177 |
x = Top() |
| 178 |
|
| 179 |
assert AliasSchema.from_orm(x).dict() == {"value": 10} |
| 180 |
|
| 181 |
|
| 182 |
def test_with_attr_that_has_resolve(): |
| 183 |
class Obj: |
| 184 |
id = "1" |
| 185 |
resolve_attr = "2" |
| 186 |
|
| 187 |
assert ResolveAttrSchema.from_orm(Obj()).dict() == {"id": "1", "resolve_attr": "2"} |
| 188 |
|
| 189 |
|
| 190 |
def test_django_getter(): |
| 191 |
"Coverage for DjangoGetter __repr__ method" |
| 192 |
|
| 193 |
class Somechema(Schema): |
| 194 |
i: int |
| 195 |
|
| 196 |
dg = DjangoGetter({"i": 1}, Somechema) |
| 197 |
assert repr(dg) == "<DjangoGetter: {'i': 1}>" |
| 198 |
|
| 199 |
|
| 200 |
def test_schema_validates_assignment_and_reassigns_the_value(): |
| 201 |
class ValidateAssignmentSchema(Schema): |
| 202 |
str_var: str |
| 203 |
model_config = {"validate_assignment": True} |
| 204 |
|
| 205 |
schema_inst = ValidateAssignmentSchema(str_var="test_value") |
| 206 |
schema_inst.str_var = "reassigned_value" |
| 207 |
assert schema_inst.str_var == "reassigned_value" |
| 208 |
try: |
| 209 |
schema_inst.str_var = 5 |
| 210 |
raise AssertionError() |
| 211 |
except ValidationError: |
| 212 |
|
| 213 |
pass |
| 214 |
|
| 215 |
|
| 216 |
@pytest.mark.parametrize("test_validate_assignment", [False, None]) |
| 217 |
def test_schema_skips_validation_when_validate_assignment_False( |
| 218 |
test_validate_assignment: Union[bool, None], |
| 219 |
): |
| 220 |
class ValidateAssignmentSchema(Schema): |
| 221 |
str_var: str |
| 222 |
model_config = {"validate_assignment": test_validate_assignment} |
| 223 |
|
| 224 |
schema_inst = ValidateAssignmentSchema(str_var="test_value") |
| 225 |
try: |
| 226 |
schema_inst.str_var = 5 |
| 227 |
assert schema_inst.str_var == 5 |
| 228 |
except ValidationError as ve: |
| 229 |
raise AssertionError() from ve |