-
Notifications
You must be signed in to change notification settings - Fork 270
/
test_regressions.py
3463 lines (2716 loc) · 124 KB
/
test_regressions.py
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import datetime
import re
import sys
import typing
import uuid
from decimal import Decimal
from functools import partialmethod
from unittest import mock
import pytest
from django import __version__ as DJANGO_VERSION
from django.core import validators
from django.db import models
from django.db.models import fields
from django.urls import path, re_path, register_converter
from django.urls.converters import StringConverter
from rest_framework import (
filters, generics, mixins, pagination, parsers, renderers, routers, serializers, views,
viewsets,
)
from rest_framework.authentication import BasicAuthentication, TokenAuthentication
from rest_framework.decorators import action, api_view
from rest_framework.views import APIView
from drf_spectacular.extensions import OpenApiSerializerExtension
from drf_spectacular.helpers import forced_singular_serializer
from drf_spectacular.hooks import preprocess_exclude_path_format
from drf_spectacular.openapi import AutoSchema
from drf_spectacular.renderers import OpenApiJsonRenderer, OpenApiYamlRenderer
from drf_spectacular.settings import IMPORT_STRINGS, SPECTACULAR_DEFAULTS
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
OpenApiExample, OpenApiParameter, OpenApiRequest, OpenApiResponse, extend_schema,
extend_schema_field, extend_schema_serializer, extend_schema_view, inline_serializer,
)
from tests import generate_schema, get_request_schema, get_response_schema, strip_int64_details
from tests.models import SimpleModel, SimpleSerializer
def test_primary_key_read_only_queryset_not_found(no_warnings):
# the culprit - looks like a feature not a bug.
# https://github.com/encode/django-rest-framework/blame/4d9f9eb192c5c1ffe4fa9210b90b9adbb00c3fdd/rest_framework/utils/field_mapping.py#L271
class M1(models.Model):
pass # pragma: no cover
class M2(models.Model):
id = models.UUIDField()
m1_r = models.ForeignKey(M1, on_delete=models.CASCADE)
m1_rw = models.ForeignKey(M1, on_delete=models.CASCADE)
class M2Serializer(serializers.ModelSerializer):
class Meta:
fields = ['m1_rw', 'm1_r']
read_only_fields = ['m1_r'] # this produces the bug
model = M2
class M2Viewset(viewsets.ReadOnlyModelViewSet):
serializer_class = M2Serializer
queryset = M2.objects.none()
schema = generate_schema('m2', M2Viewset)
props = schema['components']['schemas']['M2']['properties']
assert props['m1_rw']['type'] == 'integer'
assert props['m1_r']['type'] == 'integer'
def test_multi_step_serializer_primary_key_related_field(no_warnings):
class MA1(models.Model):
id = models.UUIDField(primary_key=True)
class MA2(models.Model):
m1 = models.ForeignKey(MA1, on_delete=models.CASCADE)
class MA3(models.Model):
m2 = models.ForeignKey(MA2, on_delete=models.CASCADE)
class M3Serializer(serializers.ModelSerializer):
# this scenario looks explicitly at multi-step sources with read_only=True
m1 = serializers.PrimaryKeyRelatedField(source='m2.m1', required=False, read_only=True)
class Meta:
fields = ['m1', 'm2']
model = MA3
class M3Viewset(viewsets.ReadOnlyModelViewSet):
serializer_class = M3Serializer
queryset = MA3.objects.none()
schema = generate_schema('m3', M3Viewset)
properties = schema['components']['schemas']['M3']['properties']
assert properties['m1']['format'] == 'uuid'
assert properties['m2']['type'] == 'integer'
def test_serializer_reverse_relations_including_read_only(no_warnings):
class M5(models.Model):
pass
class M5One(models.Model):
id = models.CharField(primary_key=True, max_length=10)
field = models.OneToOneField(M5, on_delete=models.CASCADE)
class M5Many(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
field = models.ManyToManyField(M5)
class M5Foreign(models.Model):
id = models.FloatField(primary_key=True)
field = models.ForeignKey(M5, on_delete=models.CASCADE)
class XSerializer(serializers.ModelSerializer):
m5foreign_set_explicit = serializers.PrimaryKeyRelatedField(
many=True, source='m5foreign_set', queryset=M5Foreign.objects.all()
)
m5foreign_set_ro = serializers.PrimaryKeyRelatedField(
many=True, source='m5foreign_set', read_only=True,
)
m5many_set_explicit = serializers.PrimaryKeyRelatedField(
many=True, source='m5many_set', queryset=M5Many.objects.all()
)
m5many_set_ro = serializers.PrimaryKeyRelatedField(
many=True, source='m5many_set', read_only=True,
)
m5one_ro = serializers.PrimaryKeyRelatedField(
source='m5one', read_only=True,
)
class Meta:
model = M5
fields = [
'm5many_set',
'm5many_set_explicit',
'm5many_set_ro',
'm5foreign_set',
'm5foreign_set_explicit',
'm5foreign_set_ro',
'm5one',
'm5one_ro',
]
class TestViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
queryset = M5.objects.all()
serializer_class = XSerializer
schema = generate_schema('/x/', TestViewSet)
properties = schema['components']['schemas']['X']['properties']
m5many_pk = {'type': 'string', 'format': 'uuid'}
assert properties['m5many_set']['items'] == m5many_pk
assert properties['m5many_set_ro']['items'] == m5many_pk
assert properties['m5many_set_explicit']['items'] == m5many_pk
m5foreign_pk = {'type': 'number', 'format': 'double'}
assert properties['m5foreign_set']['items'] == m5foreign_pk
assert properties['m5foreign_set_ro']['items'] == m5foreign_pk
assert properties['m5foreign_set_explicit']['items'] == m5foreign_pk
assert properties['m5one'] == {'type': 'string'}
assert properties['m5one_ro'] == {'readOnly': True, 'type': 'string'}
def test_serializer_forward_relations_including_read_only(no_warnings):
class M6One(models.Model):
id = models.CharField(primary_key=True, max_length=10)
class M6Many(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
class M6Foreign(models.Model):
id = models.FloatField(primary_key=True)
class M6(models.Model):
field_one = models.OneToOneField(M6One, on_delete=models.CASCADE)
field_many = models.ManyToManyField(M6Many)
field_foreign = models.ForeignKey(M6Foreign, on_delete=models.CASCADE)
class XSerializer(serializers.ModelSerializer):
field_one_ro = serializers.PrimaryKeyRelatedField(
source='field_one', read_only=True
)
field_foreign_ro = serializers.PrimaryKeyRelatedField(
source='field_foreign', read_only=True
)
field_many_ro = serializers.PrimaryKeyRelatedField(
source='field_many', read_only=True, many=True
)
class Meta:
model = M6
fields = [
'field_one',
'field_one_ro',
'field_many',
'field_many_ro',
'field_foreign',
'field_foreign_ro',
]
class TestViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
queryset = M6.objects.all()
serializer_class = XSerializer
schema = generate_schema('/x/', TestViewSet)
properties = schema['components']['schemas']['X']['properties']
assert properties['field_one'] == {'type': 'string'}
assert properties['field_one_ro'] == {'type': 'string', 'readOnly': True}
assert properties['field_foreign'] == {'type': 'number', 'format': 'double'}
assert properties['field_foreign_ro'] == {'type': 'number', 'format': 'double', 'readOnly': True}
assert properties['field_many'] == {'type': 'array', 'items': {'type': 'string', 'format': 'uuid'}}
assert properties['field_many_ro'] == {
'type': 'array', 'items': {'type': 'string', 'format': 'uuid'}, 'readOnly': True
}
def test_path_implicit_required(no_warnings):
class M2Serializer(serializers.Serializer):
pass # pragma: no cover
class M2Viewset(viewsets.GenericViewSet):
serializer_class = M2Serializer
@extend_schema(parameters=[OpenApiParameter('id', str, 'path')])
def retrieve(self, request, *args, **kwargs):
pass # pragma: no cover
generate_schema('m2', M2Viewset)
def test_free_form_responses(no_warnings):
class XAPIView(APIView):
@extend_schema(responses={200: OpenApiTypes.OBJECT})
def get(self, request):
pass # pragma: no cover
class YAPIView(APIView):
@extend_schema(responses=OpenApiTypes.OBJECT)
def get(self, request):
pass # pragma: no cover
generate_schema(None, patterns=[
re_path(r'^x$', XAPIView.as_view(), name='x'),
re_path(r'^y$', YAPIView.as_view(), name='y'),
])
@mock.patch(
target='drf_spectacular.settings.spectacular_settings.APPEND_COMPONENTS',
new={'schemas': {'SomeExtraComponent': {'type': 'integer'}}}
)
def test_append_extra_components(no_warnings):
class XSerializer(serializers.Serializer):
id = serializers.UUIDField()
class XAPIView(APIView):
@extend_schema(responses={200: XSerializer})
def get(self, request):
pass # pragma: no cover
schema = generate_schema(None, patterns=[
re_path(r'^x$', XAPIView.as_view(), name='x'),
])
assert len(schema['components']['schemas']) == 2
def test_serializer_retrieval_from_view(no_warnings):
class UnusedSerializer(serializers.Serializer):
pass # pragma: no cover
class XSerializer(serializers.Serializer):
id = serializers.UUIDField()
class YSerializer(serializers.Serializer):
id = serializers.UUIDField()
class X1Viewset(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = UnusedSerializer
def get_serializer(self, *args, **kwargs):
assert 'request' in kwargs['context']
return XSerializer(*args, **kwargs)
class X2Viewset(mixins.ListModelMixin, viewsets.GenericViewSet):
def get_serializer_class(self):
return YSerializer
router = routers.SimpleRouter()
router.register('x1', X1Viewset, basename='x1')
router.register('x2', X2Viewset, basename='x2')
schema = generate_schema(None, patterns=router.urls)
assert len(schema['components']['schemas']) == 2
assert 'Unused' not in schema['components']['schemas']
def test_retrieve_on_apiview_get(no_warnings):
class XSerializer(serializers.Serializer):
id = serializers.UUIDField()
class XApiView(APIView):
authentication_classes = []
@extend_schema(
parameters=[OpenApiParameter('id', OpenApiTypes.INT, OpenApiParameter.PATH)],
responses={200: XSerializer},
)
def get(self, request):
pass # pragma: no cover
schema = generate_schema('x', view=XApiView)
operation = schema['paths']['/x']['get']
assert operation['operationId'] == 'x_retrieve'
operation_schema = get_response_schema(operation)
assert '$ref' in operation_schema and 'type' not in operation_schema
def test_list_on_apiview_get(no_warnings):
class XSerializer(serializers.Serializer):
id = serializers.UUIDField()
class XApiView(APIView):
authentication_classes = []
@extend_schema(
parameters=[OpenApiParameter('id', OpenApiTypes.INT, OpenApiParameter.PATH)],
responses={200: XSerializer(many=True)},
)
def get(self, request):
pass # pragma: no cover
schema = generate_schema('x', view=XApiView)
operation = schema['paths']['/x']['get']
assert operation['operationId'] == 'x_list'
operation_schema = get_response_schema(operation)
assert operation_schema['type'] == 'array'
def test_multi_method_action(no_warnings):
class DummySerializer(serializers.Serializer):
id = serializers.UUIDField()
class UpdateSerializer(serializers.Serializer):
id = serializers.UUIDField()
class CreateSerializer(serializers.Serializer):
id = serializers.UUIDField()
class XViewset(viewsets.GenericViewSet):
serializer_class = DummySerializer
# basic usage
@extend_schema(request=UpdateSerializer, methods=['PUT'])
@extend_schema(request=CreateSerializer, methods=['POST'])
@action(detail=False, methods=['PUT', 'POST'])
def multi(self, request, *args, **kwargs):
pass # pragma: no cover
# bolt-on decorator variation
@extend_schema(request=CreateSerializer)
@action(detail=False, methods=['POST'])
def multi2(self, request, *args, **kwargs):
pass # pragma: no cover
@extend_schema(request=UpdateSerializer)
@multi2.mapping.put
def multi2put(self, request, *args, **kwargs):
pass # pragma: no cover
schema = generate_schema('x', XViewset)
def get_req_body(s):
return s['requestBody']['content']['application/json']['schema']['$ref']
assert get_req_body(schema['paths']['/x/multi/']['put']) == '#/components/schemas/Update'
assert get_req_body(schema['paths']['/x/multi/']['post']) == '#/components/schemas/Create'
assert get_req_body(schema['paths']['/x/multi2/']['put']) == '#/components/schemas/Update'
assert get_req_body(schema['paths']['/x/multi2/']['post']) == '#/components/schemas/Create'
def test_serializer_class_on_apiview(no_warnings):
class XSerializer(serializers.Serializer):
field = serializers.UUIDField()
class XView(views.APIView):
serializer_class = XSerializer # not supported by DRF but pick it up anyway
def get(self, request):
pass # pragma: no cover
def post(self, request):
pass # pragma: no cover
schema = generate_schema('x', view=XView)
comp = '#/components/schemas/X'
assert get_response_schema(schema['paths']['/x']['get'])['$ref'] == comp
assert get_response_schema(schema['paths']['/x']['post'])['$ref'] == comp
assert schema['paths']['/x']['post']['requestBody']['content']['application/json']['schema']['$ref'] == comp
def test_customized_list_serializer():
class X(models.Model):
position = models.IntegerField()
class XSerializer(serializers.ModelSerializer):
class Meta:
model = X
fields = ("id", "position")
class XListUpdateSerializer(serializers.ListSerializer):
child = XSerializer()
class XAPIView(generics.GenericAPIView):
model = X
serializer_class = XListUpdateSerializer
def put(self, request, *args, **kwargs):
pass # pragma: no cover
schema = generate_schema('x', view=XAPIView)
operation = schema['paths']['/x']['put']
comp = '#/components/schemas/X'
assert get_request_schema(operation)['type'] == 'array'
assert get_request_schema(operation)['items']['$ref'] == comp
assert get_response_schema(operation)['type'] == 'array'
assert get_response_schema(operation)['items']['$ref'] == comp
assert operation['operationId'] == 'x_update'
assert len(schema['components']['schemas']) == 1 and 'X' in schema['components']['schemas']
def test_api_view_decorator(no_warnings):
@extend_schema(responses=OpenApiTypes.FLOAT)
@api_view(['GET'])
def pi(request):
pass # pragma: no cover
schema = generate_schema('x', view_function=pi)
operation = schema['paths']['/x']['get']
assert get_response_schema(operation)['type'] == 'number'
def test_api_view_decorator_multi(no_warnings):
@extend_schema(request=OpenApiTypes.FLOAT, responses=OpenApiTypes.INT, methods=['POST'])
@extend_schema(responses=OpenApiTypes.FLOAT, methods=['GET'])
@api_view(['GET', 'POST'])
def pi(request):
pass # pragma: no cover
schema = generate_schema('x', view_function=pi)
operation = schema['paths']['/x']['get']
assert get_response_schema(operation)['type'] == 'number'
operation = schema['paths']['/x']['post']
assert get_request_schema(operation)['type'] == 'number'
assert get_response_schema(operation)['type'] == 'integer'
def test_pk_and_no_id(no_warnings):
class XModel(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class YModel(models.Model):
x = models.OneToOneField(XModel, primary_key=True, on_delete=models.CASCADE)
class YSerializer(serializers.ModelSerializer):
class Meta:
model = YModel
fields = '__all__'
class YViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = YSerializer
queryset = YModel.objects.all()
schema = generate_schema('y', YViewSet)
assert schema['components']['schemas']['Y']['properties']['x']['format'] == 'uuid'
@pytest.mark.parametrize('allowed', [None, ['json', 'NoRendererAvailable']])
def test_drf_format_suffix_parameter(no_warnings, allowed):
from rest_framework.urlpatterns import format_suffix_patterns
@extend_schema(responses=OpenApiTypes.FLOAT)
@api_view(['GET'])
def view_func(request, format=None):
pass # pragma: no cover
urlpatterns = [
path('pi/', view_func),
path('pi/subpath', view_func),
path('pick', view_func),
]
urlpatterns = format_suffix_patterns(urlpatterns, allowed=allowed)
schema = generate_schema(None, patterns=urlpatterns)
# Only seven alternatives are created, as /pi/{format} would be
# /pi/.json which is not supported.
assert list(schema['paths'].keys()) == [
'/pi/',
'/pi{format}',
'/pi/subpath',
'/pi/subpath{format}',
'/pick',
'/pick{format}',
]
assert schema['paths']['/pi/']['get']['operationId'] == 'pi_retrieve'
assert schema['paths']['/pi{format}']['get']['operationId'] == 'pi_formatted_retrieve'
format_parameter = schema['paths']['/pi{format}']['get']['parameters'][0]
assert format_parameter['name'] == 'format'
assert format_parameter['required'] is True
assert format_parameter['in'] == 'path'
assert format_parameter['schema']['type'] == 'string'
# When allowed is not specified, all of the default formats are possible.
# Even if other values are provided, only the valid formats are possible.
assert format_parameter['schema']['enum'] == ['.json']
@mock.patch(
'drf_spectacular.settings.spectacular_settings.PREPROCESSING_HOOKS',
[preprocess_exclude_path_format]
)
def test_drf_format_suffix_parameter_exclude(no_warnings):
from rest_framework.urlpatterns import format_suffix_patterns
@extend_schema(responses=OpenApiTypes.FLOAT)
@api_view(['GET'])
def view_func(request, format=None):
pass # pragma: no cover
urlpatterns = format_suffix_patterns([
path('pi', view_func),
])
schema = generate_schema(None, patterns=urlpatterns)
assert list(schema['paths'].keys()) == ['/pi']
def test_regex_path_parameter_discovery(no_warnings):
@extend_schema(responses=OpenApiTypes.FLOAT)
@api_view(['GET'])
def pi(request, foo):
pass # pragma: no cover
urlpatterns = [re_path(r'^/pi/<int:precision>', pi)]
schema = generate_schema(None, patterns=urlpatterns)
parameter = schema['paths']['/pi/{precision}']['get']['parameters'][0]
assert parameter['name'] == 'precision'
assert parameter['in'] == 'path'
assert parameter['schema']['type'] == 'integer'
def test_lib_serializer_naming_collision_resolution(no_warnings):
""" parity test in tests.test_warnings.test_serializer_name_reuse """
def x_lib1():
class XSerializer(serializers.Serializer):
x = serializers.UUIDField()
return XSerializer
def x_lib2():
class XSerializer(serializers.Serializer):
x = serializers.IntegerField()
return XSerializer
x_lib1, x_lib2 = x_lib1(), x_lib2()
class XAPIView(APIView):
@extend_schema(request=x_lib1, responses=x_lib2)
def post(self, request):
pass # pragma: no cover
class Lib2XSerializerRename(OpenApiSerializerExtension):
target_class = x_lib2 # also accepts import strings
def get_name(self):
return 'RenamedLib2X'
schema = generate_schema('x', view=XAPIView)
operation = schema['paths']['/x']['post']
assert get_request_schema(operation)['$ref'] == '#/components/schemas/X'
assert get_response_schema(operation)['$ref'] == '#/components/schemas/RenamedLib2X'
def test_owned_serializer_naming_override_with_ref_name(no_warnings):
def x_owned1():
class XSerializer(serializers.Serializer):
x = serializers.UUIDField()
return XSerializer
def x_owned2():
class XSerializer(serializers.Serializer):
x = serializers.IntegerField()
class Meta:
ref_name = 'Y'
return XSerializer
x_owned1, x_owned2 = x_owned1(), x_owned2()
class XAPIView(APIView):
@extend_schema(request=x_owned1, responses=x_owned2)
def post(self, request):
pass # pragma: no cover
schema = generate_schema('x', view=XAPIView)
operation = schema['paths']['/x']['post']
assert get_request_schema(operation)['$ref'] == '#/components/schemas/X'
assert get_response_schema(operation)['$ref'] == '#/components/schemas/Y'
def test_custom_model_field_from_typed_field(no_warnings):
class CustomIntegerField(fields.IntegerField):
pass # pragma: no cover
class CustomTypedFieldModel(models.Model):
custom_int_field = CustomIntegerField()
class XSerializer(serializers.ModelSerializer):
class Meta:
model = CustomTypedFieldModel
fields = '__all__'
class XAPIView(APIView):
@extend_schema(responses=XSerializer)
def get(self, request):
pass # pragma: no cover
schema = generate_schema('x', view=XAPIView)
component = schema['components']['schemas']['X']
assert component['properties']['custom_int_field']['type'] == 'integer'
def test_custom_model_field_from_base_field(no_warnings):
class CustomIntegerField(fields.Field):
def get_internal_type(self):
return 'IntegerField'
class CustomBaseFieldModel(models.Model):
custom_int_field = CustomIntegerField()
class XSerializer(serializers.ModelSerializer):
class Meta:
model = CustomBaseFieldModel
fields = '__all__'
class XAPIView(APIView):
@extend_schema(responses=XSerializer)
def get(self, request):
pass # pragma: no cover
schema = generate_schema('x', view=XAPIView)
component = schema['components']['schemas']['X']
assert component['properties']['custom_int_field']['type'] == 'integer'
def test_follow_field_source_through_intermediate_property_or_function(no_warnings):
class FieldSourceTraversalModel2(models.Model):
x = models.IntegerField(choices=[(1, '1'), (2, '2')])
y = models.IntegerField(choices=[(1, '1'), (2, '2'), (3, '3')])
class FieldSourceTraversalModel1(models.Model):
@property
def prop(self) -> FieldSourceTraversalModel2: # property is required for traversal
return # type: ignore # pragma: no cover
def func(self) -> FieldSourceTraversalModel2: # property is required for traversal
return # type: ignore # pragma: no cover
class XSerializer(serializers.ModelSerializer):
prop = serializers.ReadOnlyField(source='prop.x')
func = serializers.ReadOnlyField(source='func.y')
class Meta:
model = FieldSourceTraversalModel1
fields = '__all__'
class XAPIView(APIView):
@extend_schema(responses=XSerializer)
def get(self, request):
pass # pragma: no cover
# this checks if field type is correctly estimated AND field was initialized
# with the model parameters (choices)
schema = generate_schema('x', view=XAPIView)
assert schema['components']['schemas']['X']['properties']['func']['readOnly'] is True
assert schema['components']['schemas']['X']['properties']['prop']['readOnly'] is True
assert 'enum' in schema['components']['schemas']['PropEnum']
assert 'enum' in schema['components']['schemas']['FuncEnum']
assert schema['components']['schemas']['PropEnum']['type'] == 'integer'
assert schema['components']['schemas']['FuncEnum']['type'] == 'integer'
def test_viewset_list_with_envelope(no_warnings):
class XSerializer(serializers.Serializer):
x = serializers.IntegerField()
def enveloper(serializer_class, many):
component_name = 'Enveloped{}{}'.format(
serializer_class.__name__.replace("Serializer", ""),
"List" if many else "",
)
@extend_schema_serializer(many=False, component_name=component_name)
class EnvelopeSerializer(serializers.Serializer):
status = serializers.BooleanField()
data = serializer_class(many=many)
return EnvelopeSerializer
class XViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
@extend_schema(responses=enveloper(XSerializer, True))
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs) # pragma: no cover
@extend_schema(
responses=enveloper(XSerializer, False),
parameters=[OpenApiParameter('id', int, OpenApiParameter.PATH)],
)
def retrieve(self, request, *args, **kwargs):
return super().retrieve(request, *args, **kwargs) # pragma: no cover
schema = generate_schema('x', viewset=XViewset)
operation_list = schema['paths']['/x/']['get']
assert operation_list['operationId'] == 'x_list'
assert get_response_schema(operation_list)['$ref'] == '#/components/schemas/EnvelopedXList'
operation_retrieve = schema['paths']['/x/{id}/']['get']
assert operation_retrieve['operationId'] == 'x_retrieve'
assert get_response_schema(operation_retrieve)['$ref'] == '#/components/schemas/EnvelopedX'
@mock.patch('drf_spectacular.settings.spectacular_settings.COMPONENT_SPLIT_REQUEST', True)
def test_component_split_request():
class XSerializer(serializers.Serializer):
ro = serializers.IntegerField(read_only=True)
rw = serializers.IntegerField()
wo = serializers.IntegerField(write_only=True)
@extend_schema(request=XSerializer, responses=XSerializer)
@api_view(['POST'])
def pi(request, format=None):
pass # pragma: no cover
schema = generate_schema('/x', view_function=pi)
operation = schema['paths']['/x']['post']
assert get_response_schema(operation)['$ref'] == '#/components/schemas/X'
assert get_request_schema(operation)['$ref'] == '#/components/schemas/XRequest'
assert len(schema['components']['schemas']['X']['properties']) == 2
assert 'wo' not in schema['components']['schemas']['X']['properties']
assert len(schema['components']['schemas']['XRequest']['properties']) == 2
assert 'ro' not in schema['components']['schemas']['XRequest']['properties']
def test_list_api_view(no_warnings):
class XSerializer(serializers.Serializer):
id = serializers.IntegerField()
class XView(generics.ListAPIView):
serializer_class = XSerializer
schema = generate_schema('/x', view=XView)
operation = schema['paths']['/x']['get']
assert operation['operationId'] == 'x_list'
assert get_response_schema(operation)['type'] == 'array'
@mock.patch('drf_spectacular.settings.spectacular_settings.COMPONENT_SPLIT_REQUEST', True)
def test_file_field_duality_on_split_request(no_warnings):
class XSerializer(serializers.Serializer):
file = serializers.FileField()
class XView(generics.ListCreateAPIView):
serializer_class = XSerializer
parser_classes = [parsers.MultiPartParser]
schema = generate_schema('/x', view=XView)
assert get_response_schema(
schema['paths']['/x']['get']
)['items']['$ref'] == '#/components/schemas/X'
assert get_request_schema(
schema['paths']['/x']['post'], content_type='multipart/form-data'
)['$ref'] == '#/components/schemas/XRequest'
assert schema['components']['schemas']['X']['properties']['file']['format'] == 'uri'
assert schema['components']['schemas']['XRequest']['properties']['file']['format'] == 'binary'
@mock.patch('drf_spectacular.settings.spectacular_settings.COMPONENT_SPLIT_REQUEST', True)
def test_component_split_nested_ro_wo_serializer(no_warnings):
class RoSerializer(serializers.Serializer):
ro_field = serializers.IntegerField(read_only=True)
class WoSerializer(serializers.Serializer):
wo_field = serializers.IntegerField(write_only=True)
class XSerializer(serializers.Serializer):
ro = RoSerializer()
wo = WoSerializer()
class XView(generics.ListCreateAPIView):
serializer_class = XSerializer
schema = generate_schema('/x', view=XView)
assert 'RoRequest' not in schema['components']['schemas']
assert 'Wo' not in schema['components']['schemas']
assert len(schema['components']['schemas']['X']['properties']) == 1
assert len(schema['components']['schemas']['XRequest']['properties']) == 1
@mock.patch('drf_spectacular.settings.spectacular_settings.COMPONENT_SPLIT_REQUEST', True)
def test_component_split_nested_explicit_ro_wo_serializer(no_warnings):
class NestedSerializer(serializers.Serializer):
field = serializers.IntegerField()
class XSerializer(serializers.Serializer):
ro = NestedSerializer(read_only=True)
wo = NestedSerializer(write_only=True, required=False)
class XView(generics.ListCreateAPIView):
serializer_class = XSerializer
schema = generate_schema('/x', view=XView)
assert 'NestedRequest' in schema['components']['schemas']
assert 'Nested' in schema['components']['schemas']
assert len(schema['components']['schemas']['X']['properties']) == 1
assert len(schema['components']['schemas']['XRequest']['properties']) == 1
def test_read_only_many_related_field(no_warnings):
class ManyRelatedTargetModel(models.Model):
field = models.IntegerField()
class ManyRelatedModel(models.Model):
field_m2m = models.ManyToManyField(ManyRelatedTargetModel)
field_m2m_ro = models.ManyToManyField(ManyRelatedTargetModel)
class XSerializer(serializers.ModelSerializer):
class Meta:
model = ManyRelatedModel
fields = '__all__'
read_only_fields = ['field_m2m_ro']
class XAPIView(APIView):
@extend_schema(responses=XSerializer)
def get(self, request):
pass # pragma: no cover
schema = generate_schema('x', view=XAPIView)
properties = schema['components']['schemas']['X']['properties']
# readOnly only needed on outer object, not in items
assert properties['field_m2m'] == {'type': 'array', 'items': {'type': 'integer'}}
assert properties['field_m2m_ro'] == {
'type': 'array', 'items': {'type': 'integer'}, 'readOnly': True
}
def test_extension_subclass_discovery(no_warnings):
from rest_framework.authentication import TokenAuthentication
class CustomAuth(TokenAuthentication):
pass
class XSerializer(serializers.Serializer):
field = serializers.IntegerField()
class XAPIView(APIView):
authentication_classes = [CustomAuth]
@extend_schema(responses=XSerializer)
def get(self, request):
pass # pragma: no cover
generate_schema('x', view=XAPIView)
def test_extend_schema_no_req_no_res(no_warnings):
class XAPIView(APIView):
@extend_schema(request=None, responses=None)
def post(self, request):
pass # pragma: no cover
schema = generate_schema('/x', view=XAPIView)
operation = schema['paths']['/x']['post']
assert 'requestBody' not in operation
assert len(operation['responses']['200']) == 1
assert 'description' in operation['responses']['200']
def test_extend_schema_field_exclusion(no_warnings):
@extend_schema_field(None)
class CustomField(serializers.IntegerField):
pass # pragma: no cover
class XSerializer(serializers.Serializer):
id = serializers.IntegerField()
hidden = CustomField()
class XView(generics.CreateAPIView):
serializer_class = XSerializer
schema = generate_schema('/x', view=XView)
assert 'hidden' not in schema['components']['schemas']['X']['properties']
def test_extend_schema_serializer_field_exclusion(no_warnings):
@extend_schema_serializer(exclude_fields=['hidden1', 'hidden2'])
class XSerializer(serializers.Serializer):
integer = serializers.IntegerField()
hidden1 = serializers.IntegerField()
hidden2 = serializers.CharField()
class XView(generics.ListCreateAPIView):
serializer_class = XSerializer
schema = generate_schema('/x', view=XView)
assert 'integer' in schema['components']['schemas']['X']['properties']
assert 'hidden1' not in schema['components']['schemas']['X']['properties']
assert 'hidden2' not in schema['components']['schemas']['X']['properties']
def test_schema_contains_only_urlpatterns_first_match(no_warnings):
class XSerializer(serializers.Serializer):
integer = serializers.IntegerField()
class XAPIView(APIView):
@extend_schema(responses=XSerializer)
def get(self, request):
pass # pragma: no cover
class YSerializer(serializers.Serializer):
integer = serializers.DateTimeField()
class YAPIView(APIView):
@extend_schema(responses=YSerializer)
def get(self, request):
pass # pragma: no cover
urlpatterns = [
path('api/x/', XAPIView.as_view()), # only first occurrence is used
path('api/x/', YAPIView.as_view()),
]
schema = generate_schema(None, patterns=urlpatterns)
assert len(schema['components']['schemas']) == 1
assert 'X' in schema['components']['schemas']
operation = schema['paths']['/api/x/']['get']
assert '#/components/schemas/X' in get_response_schema(operation)['$ref']
def test_schema_contains_only_allowed_methods(no_warnings):
class XSerializer(serializers.Serializer):
integer = serializers.IntegerField()
class X(models.Model):
integer = models.IntegerField()
class XAPIView(generics.ListCreateAPIView):
model = X
serializer_class = XSerializer
urlpatterns = [
path('api/x/', XAPIView.as_view()),
path('api/x1/', XAPIView.as_view(http_method_names=['post'])),
]
schema = generate_schema(None, patterns=urlpatterns)
assert sorted(schema['paths']['/api/x/'].keys()) == sorted(['get', 'post'])
assert list(schema['paths']['/api/x1/'].keys()) == ['post']
assert 'X' in schema['components']['schemas']
def test_auto_schema_and_extend_parameters(no_warnings):
class CustomAutoSchema(AutoSchema):
def get_override_parameters(self):
return [
OpenApiParameter("id", str, OpenApiParameter.PATH),
OpenApiParameter("foo", str, deprecated=True),
OpenApiParameter("bar", str),
]
class XSerializer(serializers.Serializer):
id = serializers.IntegerField()
with mock.patch('rest_framework.settings.api_settings.DEFAULT_SCHEMA_CLASS', CustomAutoSchema):
class XViewSet(viewsets.GenericViewSet):
serializer_class = XSerializer
@extend_schema(parameters=[OpenApiParameter("bar", int)])
def list(self, request, *args, **kwargs):
pass # pragma: no cover