File: test_types.py

package info (click to toggle)
strawberry-graphql-django 0.62.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,968 kB
  • sloc: python: 27,530; sh: 17; makefile: 16
file content (504 lines) | stat: -rw-r--r-- 14,662 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
import datetime
import decimal
import enum
import uuid
from typing import Any, Optional, Union, cast

import django
import pytest
import strawberry
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import FieldDoesNotExist
from django.db import models
from strawberry import auto
from strawberry.scalars import JSON
from strawberry.types import get_object_definition
from strawberry.types.base import (
    StrawberryContainer,
    StrawberryList,
    StrawberryOptional,
)
from strawberry.types.enum import EnumDefinition, EnumValue

import strawberry_django
from strawberry_django.fields.field import StrawberryDjangoField
from strawberry_django.type import _process_type  # noqa: PLC2701

if django.VERSION >= (5, 0):
    from django.db.models import GeneratedField  # type: ignore
else:
    GeneratedField = None


class FieldTypesModel(models.Model):
    boolean = models.BooleanField()
    char = models.CharField(max_length=50)
    date = models.DateField()
    date_time = models.DateTimeField()
    decimal = models.DecimalField()
    email = models.EmailField()
    file = models.FileField()
    file_path = models.FilePathField()
    float = models.FloatField()
    generic_ip_address = models.GenericIPAddressField()
    integer = models.IntegerField()
    image = models.ImageField()
    positive_big_integer = models.PositiveBigIntegerField()
    positive_integer = models.PositiveIntegerField()
    positive_small_integer = models.PositiveSmallIntegerField()
    slug = models.SlugField()
    small_integer = models.SmallIntegerField()
    text = models.TextField()
    time = models.TimeField()
    url = models.URLField()
    uuid = models.UUIDField()
    json = models.JSONField()
    generated_decimal = (
        GeneratedField(
            expression=models.F("decimal") * 2,
            db_persist=True,
            output_field=models.DecimalField(),
        )
        if GeneratedField is not None
        else None
    )
    generated_nullable_decimal = (
        GeneratedField(
            expression=models.F("decimal") * 2,
            db_persist=True,
            output_field=models.DecimalField(null=True, blank=True),
        )
        if GeneratedField is not None
        else None
    )
    foreign_key = models.ForeignKey(
        "FieldTypesModel",
        blank=True,
        related_name="related_foreign_key",
        on_delete=models.CASCADE,
    )
    one_to_one = models.OneToOneField(
        "FieldTypesModel",
        blank=True,
        related_name="related_one_to_one",
        on_delete=models.CASCADE,
    )
    many_to_many = models.ManyToManyField(
        "FieldTypesModel",
        related_name="related_many_to_many",
    )


def test_field_types():
    @strawberry_django.type(FieldTypesModel)
    class Type:
        id: auto
        boolean: auto
        char: auto
        date: auto
        date_time: auto
        decimal: auto
        email: auto
        file: auto
        file_path: auto
        float: auto
        generic_ip_address: auto
        integer: auto
        image: auto
        positive_big_integer: auto
        positive_integer: auto
        positive_small_integer: auto
        slug: auto
        small_integer: auto
        text: auto
        time: auto
        url: auto
        uuid: auto
        json: auto

    expected_types: list[tuple[str, Any]] = [
        ("id", strawberry.ID),
        ("boolean", bool),
        ("char", str),
        ("date", datetime.date),
        ("date_time", datetime.datetime),
        ("decimal", decimal.Decimal),
        ("email", str),
        ("file", strawberry_django.DjangoFileType),
        ("file_path", str),
        ("float", float),
        ("generic_ip_address", str),
        ("integer", int),
        ("image", strawberry_django.DjangoImageType),
        ("positive_big_integer", int),
        ("positive_integer", int),
        ("positive_small_integer", int),
        ("slug", str),
        ("small_integer", int),
        ("text", str),
        ("time", datetime.time),
        ("url", str),
        ("uuid", uuid.UUID),
        ("json", JSON),
    ]

    if django.VERSION >= (5, 0):
        Type.__annotations__["generated_decimal"] = auto
        expected_types.append(("generated_decimal", decimal.Decimal))

        Type.__annotations__["generated_nullable_decimal"] = auto
        expected_types.append(("generated_nullable_decimal", Optional[decimal.Decimal]))

    type_to_test = _process_type(Type, model=FieldTypesModel)
    object_definition = get_object_definition(type_to_test, strict=True)
    assert [(f.name, f.type) for f in object_definition.fields] == expected_types


def test_field_types_for_array_fields():
    class ModelWithArrays(models.Model):
        str_array = ArrayField(models.CharField(max_length=50))
        int_array = ArrayField(models.IntegerField())

    @strawberry_django.type(ModelWithArrays)
    class Type:
        str_array: auto
        int_array: auto

    type_to_test = _process_type(Type, model=ModelWithArrays)
    object_definition = get_object_definition(type_to_test, strict=True)

    str_array_field = object_definition.get_field("str_array")
    assert str_array_field
    assert isinstance(str_array_field.type, StrawberryList)
    assert str_array_field.type.of_type is str

    int_array_field = object_definition.get_field("int_array")
    assert int_array_field
    assert isinstance(int_array_field.type, StrawberryList)
    assert int_array_field.type.of_type is int


def test_field_types_for_matrix_fields():
    class ModelWithMatrixes(models.Model):
        str_matrix = ArrayField(ArrayField(models.CharField(max_length=50)))
        int_matrix = ArrayField(ArrayField(models.IntegerField()))

    @strawberry_django.type(ModelWithMatrixes)
    class Type:
        str_matrix: auto
        int_matrix: auto

    type_to_test = _process_type(Type, model=ModelWithMatrixes)
    object_definition = get_object_definition(type_to_test, strict=True)

    str_matrix_field = object_definition.get_field("str_matrix")
    assert str_matrix_field
    assert isinstance(str_matrix_field.type, StrawberryList)
    assert isinstance(str_matrix_field.type.of_type, StrawberryList)
    assert str_matrix_field.type.of_type.of_type is str

    int_matrix_field = object_definition.get_field("int_matrix")
    assert int_matrix_field
    assert isinstance(int_matrix_field.type, StrawberryList)
    assert isinstance(int_matrix_field.type.of_type, StrawberryList)
    assert int_matrix_field.type.of_type.of_type is int


def test_subset_of_fields():
    @strawberry_django.type(FieldTypesModel)
    class Type:
        id: auto
        integer: auto
        text: auto

    object_definition = get_object_definition(Type, strict=True)
    assert [(f.name, f.type) for f in object_definition.fields] == [
        ("id", strawberry.ID),
        ("integer", int),
        ("text", str),
    ]


def test_type_extension():
    @strawberry_django.type(FieldTypesModel)
    class Type:
        char: auto
        text: bytes  # override type

        @strawberry.field
        @staticmethod
        def my_field() -> int:
            return 0

    object_definition = get_object_definition(Type, strict=True)
    assert [(f.name, f.type) for f in object_definition.fields] == [
        ("char", str),
        ("text", bytes),
        ("my_field", int),
    ]


def test_field_does_not_exist():
    with pytest.raises(FieldDoesNotExist):

        @strawberry_django.type(FieldTypesModel)
        class Type:
            unknown_field: auto


def test_override_field_type():
    @strawberry.enum
    class EnumType(enum.Enum):
        a = "A"

    @strawberry_django.type(FieldTypesModel)
    class Type:
        char: EnumType

    object_definition = get_object_definition(Type, strict=True)
    assert [(f.name, f.type) for f in object_definition.fields] == [
        (
            "char",
            EnumDefinition(
                wrapped_cls=EnumType,
                name="EnumType",
                values=[EnumValue(name="a", value="A")],
                description=None,
            ),
        ),
    ]


def test_override_field_default_value():
    @strawberry_django.type(FieldTypesModel)
    class Type:
        char: str = "my value"

    object_definition = get_object_definition(Type, strict=True)
    assert [(f.name, f.type) for f in object_definition.fields] == [
        ("char", str),
    ]

    assert Type().char == "my value"


def test_related_fields():
    @strawberry_django.type(FieldTypesModel)
    class Type:
        foreign_key: auto
        one_to_one: auto
        many_to_many: auto
        related_foreign_key: auto
        related_one_to_one: auto
        related_many_to_many: auto

    object_definition = get_object_definition(Type, strict=True)
    assert [
        (f.name, f.type, cast("StrawberryDjangoField", f).is_list)
        for f in object_definition.fields
    ] == [
        ("foreign_key", strawberry_django.DjangoModelType, False),
        ("one_to_one", strawberry_django.DjangoModelType, False),
        (
            "many_to_many",
            StrawberryList(strawberry_django.DjangoModelType),
            True,
        ),
        (
            "related_foreign_key",
            StrawberryList(strawberry_django.DjangoModelType),
            True,
        ),
        (
            "related_one_to_one",
            StrawberryOptional(strawberry_django.DjangoModelType),
            False,
        ),
        (
            "related_many_to_many",
            StrawberryList(strawberry_django.DjangoModelType),
            True,
        ),
    ]


def test_related_input_fields():
    @strawberry_django.input(FieldTypesModel)
    class Input:
        foreign_key: auto
        one_to_one: auto
        many_to_many: auto
        related_foreign_key: auto
        related_one_to_one: auto
        related_many_to_many: auto

    expected_fields: dict[str, tuple[Union[type, StrawberryContainer], bool]] = {
        "foreign_key": (
            strawberry_django.OneToManyInput,
            True,
        ),
        "one_to_one": (
            strawberry_django.OneToOneInput,
            True,
        ),
        "many_to_many": (
            strawberry_django.ManyToManyInput,
            True,
        ),
        "related_foreign_key": (
            strawberry_django.ManyToOneInput,
            True,
        ),
        "related_one_to_one": (
            strawberry_django.OneToOneInput,
            True,
        ),
        "related_many_to_many": (
            strawberry_django.ManyToManyInput,
            True,
        ),
    }

    object_definition = get_object_definition(Input, strict=True)
    assert len(object_definition.fields) == len(expected_fields)

    for f in object_definition.fields:
        expected_type, expected_is_optional = expected_fields[f.name]
        assert isinstance(f, StrawberryDjangoField)
        assert f.is_optional == expected_is_optional
        assert isinstance(f.type, StrawberryOptional)
        assert f.type.of_type == expected_type


@pytest.mark.skipif(
    not settings.GEOS_IMPORTED,
    reason="Test requires GEOS to be imported and properly configured",
)
def test_geos_fields():
    from strawberry_django.fields import types
    from tests.models import GeosFieldsModel

    @strawberry_django.type(GeosFieldsModel)
    class GeoFieldType:
        point: auto
        line_string: auto
        polygon: auto
        multi_point: auto
        multi_line_string: auto
        multi_polygon: auto
        geometry: auto

    object_definition = get_object_definition(GeoFieldType, strict=True)
    assert [
        (f.name, cast("StrawberryOptional", f.type).of_type)
        for f in object_definition.fields
    ] == [
        ("point", types.Point),
        ("line_string", types.LineString),
        ("polygon", types.Polygon),
        ("multi_point", types.MultiPoint),
        ("multi_line_string", types.MultiLineString),
        ("multi_polygon", types.MultiPolygon),
        ("geometry", types.Geometry),
    ]


def test_inherit_type():
    global Type

    @strawberry_django.type(FieldTypesModel)
    class Base:
        char: auto
        one_to_one: "Type"

    @strawberry_django.type(FieldTypesModel)
    class Type(Base):  # type: ignore
        many_to_many: list["Type"]

    object_definition = get_object_definition(Type, strict=True)
    assert [(f.name, f.type) for f in object_definition.fields] == [
        ("char", str),
        ("one_to_one", Type),
        ("many_to_many", StrawberryList(Type)),
    ]


def test_inherit_input():
    global Type

    @strawberry_django.type(FieldTypesModel)
    class Type:  # type: ignore
        char: auto
        one_to_one: "Type"
        many_to_many: list["Type"]

    @strawberry_django.input(FieldTypesModel)
    class Input(Type):
        id: auto
        my_data: str

    object_definition = get_object_definition(Input, strict=True)
    assert [(f.name, f.type) for f in object_definition.fields] == [
        ("char", str),
        ("one_to_one", StrawberryOptional(strawberry_django.OneToOneInput)),
        (
            "many_to_many",
            StrawberryOptional(strawberry_django.ManyToManyInput),
        ),
        ("id", StrawberryOptional(cast("type", strawberry.ID))),
        ("my_data", str),
    ]


def test_inherit_partial_input():
    global Type

    @strawberry_django.type(FieldTypesModel)
    class Type:
        char: auto
        one_to_one: "Type"

    @strawberry_django.input(FieldTypesModel)
    class Input(Type):
        pass

    @strawberry_django.input(FieldTypesModel, partial=True)
    class PartialInput(Input):
        pass

    object_definition = get_object_definition(PartialInput, strict=True)
    assert [
        (f.name, f.type, cast("StrawberryDjangoField", f).is_optional)
        for f in object_definition.fields
    ] == [
        ("char", StrawberryOptional(str), True),
        (
            "one_to_one",
            StrawberryOptional(strawberry_django.OneToOneInput),
            True,
        ),
    ]


def test_notimplemented():
    """Test that an unrecognized field raises `NotImplementedError`."""

    class UnknownField(models.Field):
        """A field unknown to Strawberry."""

    class UnknownModel(models.Model):
        """A model with UnknownField."""

        field = UnknownField()

    @strawberry_django.type(UnknownModel)
    class UnknownType:
        field: auto

    @strawberry.type
    class Query:
        unknown_type: UnknownType

    with pytest.raises(TypeError, match=r"UnknownModel\.field"):
        strawberry.Schema(query=Query)