-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathtest_examples.py
431 lines (386 loc) · 15.1 KB
/
test_examples.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
import pytest
from rest_framework import __version__ as DRF_VERSION # type: ignore[attr-defined]
from rest_framework import generics, pagination, serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
OpenApiExample, OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_serializer,
)
from tests import assert_schema, generate_schema
from tests.models import SimpleModel, SimpleSerializer
@extend_schema_serializer(
examples=[
OpenApiExample(
'Serializer A Example RO',
value={"field": 1},
response_only=True,
),
OpenApiExample(
'Serializer A Example WO',
value={"field": 2},
request_only=True,
),
OpenApiExample(
'Serializer A Example RW',
summary='Serializer A Example RW custom summary',
value={'field': 3}
),
OpenApiExample(
'Serializer A Example RW External',
external_value='https://example.com/example_a.txt',
media_type='application/x-www-form-urlencoded'
)
]
)
class ASerializer(serializers.Serializer):
field = serializers.IntegerField()
class BSerializer(serializers.Serializer):
field = serializers.IntegerField()
@extend_schema_serializer(
examples=[
OpenApiExample(
'Serializer C Example RO',
value={"field": 111},
response_only=True,
),
OpenApiExample(
'Serializer C Example WO',
value={"field": 222},
request_only=True,
),
OpenApiExample(
'Serializer C Example List',
value=[{"field": 333}, {"field": 444}],
response_only=True,
),
]
)
class CSerializer(serializers.Serializer):
field = serializers.IntegerField()
@extend_schema(
responses=BSerializer,
examples=[OpenApiExample("Example ID 1", value=1, parameter_only=('id', 'path'))]
)
class ExampleTestWithExtendedViewSet(viewsets.GenericViewSet):
serializer_class = ASerializer
queryset = SimpleModel.objects.none()
@extend_schema(
request=ASerializer,
responses={
201: BSerializer,
400: OpenApiTypes.OBJECT,
403: OpenApiTypes.OBJECT,
},
examples=[
OpenApiExample(
'Create Example RO',
value={'field': 11},
response_only=True,
),
OpenApiExample(
'Create Example WO',
value={'field': 22},
request_only=True,
),
OpenApiExample(
'Create Example RW',
value={'field': 33},
),
OpenApiExample(
'Create Error 403 Integer Example',
value={'field': 'error (int)'},
response_only=True,
status_codes=[status.HTTP_403_FORBIDDEN],
),
OpenApiExample(
'Create Error 403 String Example',
value={'field': 'error (str)'},
response_only=True,
status_codes=['403']
),
],
)
def create(self, request, *args, **kwargs):
super().create(request, *args, **kwargs) # pragma: no cover
@extend_schema(
parameters=[
OpenApiParameter(
name="artist",
description="Filter by artist",
required=False,
type=str,
examples=[
OpenApiExample(
"Artist Query Example 1",
value="prince",
description="description for artist query example 1"
),
OpenApiExample(
"Artist Query Example 2",
value="miles davis",
description="description for artist query example 2"
)
]
),
],
responses=CSerializer,
)
def list(self, request):
return Response() # pragma: no cover
@extend_schema(
examples=[
OpenApiExample(
"Example ID 2",
value=2,
parameter_only=('id', OpenApiParameter.PATH)
)
]
)
def retrieve(self, request):
return Response() # pragma: no cover
@action(detail=False, methods=['GET'])
def raw_action(self, request):
return Response() # pragma: no cover
@extend_schema(responses=BSerializer)
@action(detail=False, methods=['POST'])
def override_extend_schema_action(self, request):
return Response() # pragma: no cover
def test_examples(no_warnings):
assert_schema(
generate_schema('schema', ExampleTestWithExtendedViewSet),
'tests/test_examples.yml',
)
@pytest.mark.skipif(DRF_VERSION < '3.12', reason='DRF pagination schema broken')
def test_example_pagination(no_warnings):
class PaginatedExamplesViewSet(ExampleTestWithExtendedViewSet):
pagination_class = pagination.LimitOffsetPagination
schema = generate_schema('e', PaginatedExamplesViewSet)
operation = schema['paths']['/e/']['get']
assert operation['responses']['200']['content']['application/json']['examples'] == {
'SerializerCExampleRO': {
'value': {
'count': 123,
'next': 'http://api.example.org/accounts/?offset=400&limit=100',
'previous': 'http://api.example.org/accounts/?offset=200&limit=100',
'results': [{'field': 111}],
},
'summary': 'Serializer C Example RO'
},
'SerializerCExampleList': {
'value': {
'count': 123,
'next': 'http://api.example.org/accounts/?offset=400&limit=100',
'previous': 'http://api.example.org/accounts/?offset=200&limit=100',
'results': [{'field': 333}, {'field': 444}],
},
'summary': 'Serializer C Example List'
},
}
@pytest.mark.skipif(DRF_VERSION < '3.12', reason='DRF pagination schema broken')
def test_example_nested_pagination(no_warnings):
class NestedPagination(pagination.LimitOffsetPagination):
def get_paginated_response_schema(self, schema):
return {
'type': 'object',
'required': ['pagination', 'results'],
'properties': {
'pagination': {
'type': 'object',
'required': ['next', 'previous'],
'properties': {
'count': {
'type': 'integer',
'example': 123,
},
'next': {
'type': 'string',
'nullable': True,
'format': 'uri',
'example': 'http://api.example.org/accounts/?{offset_prm}=400&{limit_prm}=100'.format(
offset_prm=self.offset_query_param, limit_prm=self.limit_query_param),
},
'previous': {
'type': 'string',
'nullable': True,
'format': 'uri',
'example': 'http://api.example.org/accounts/?{offset_prm}=200&{limit_prm}=100'.format(
offset_prm=self.offset_query_param, limit_prm=self.limit_query_param),
},
}
},
'results': schema,
},
}
class PaginatedExamplesViewSet(ExampleTestWithExtendedViewSet):
pagination_class = NestedPagination
schema = generate_schema('e', PaginatedExamplesViewSet)
operation = schema['paths']['/e/']['get']
assert operation['responses']['200']['content']['application/json']['examples'] == {
'SerializerCExampleRO': {
'value': {
'pagination': {
'count': 123,
'next': 'http://api.example.org/accounts/?offset=400&limit=100',
'previous': 'http://api.example.org/accounts/?offset=200&limit=100',
},
'results': [{'field': 111}],
},
'summary': 'Serializer C Example RO'
},
'SerializerCExampleList': {
'value': {
'pagination': {
'count': 123,
'next': 'http://api.example.org/accounts/?offset=400&limit=100',
'previous': 'http://api.example.org/accounts/?offset=200&limit=100',
},
'results': [{'field': 333}, {'field': 444}],
},
'summary': 'Serializer C Example List'
},
}
def test_example_request_response_singular_examples(no_warnings):
@extend_schema(
request=ASerializer(many=True),
responses=ASerializer(many=True),
examples=[
OpenApiExample('Ex', {'id': '1234'})
]
)
class XView(generics.CreateAPIView):
pass
schema = generate_schema('e', view=XView)
operation = schema['paths']['/e']['post']
assert operation['requestBody']['content']['application/json'] == {
'schema': {'type': 'array', 'items': {'$ref': '#/components/schemas/A'}},
'examples': {'Ex': {'value': [{'id': '1234'}]}}
}
assert operation['responses']['201']['content']['application/json'] == {
'schema': {'type': 'array', 'items': {'$ref': '#/components/schemas/A'}},
'examples': {'Ex': {'value': [{'id': '1234'}]}}
}
def test_example_request_response_listed_examples(no_warnings):
@extend_schema(
request=ASerializer(many=True),
responses=ASerializer(many=True),
examples=[
OpenApiExample('Ex', [{'id': '2345'}, {'id': '2345'}])
]
)
class XView(generics.CreateAPIView):
pass
schema = generate_schema('e', view=XView)
operation = schema['paths']['/e']['post']
assert operation['requestBody']['content']['application/json'] == {
'schema': {'type': 'array', 'items': {'$ref': '#/components/schemas/A'}},
'examples': {'Ex': {'value': [{'id': '2345'}, {'id': '2345'}]}}
}
assert operation['responses']['201']['content']['application/json'] == {
'schema': {'type': 'array', 'items': {'$ref': '#/components/schemas/A'}},
'examples': {'Ex': {'value': [{'id': '2345'}, {'id': '2345'}]}}
}
def test_examples_list_detection_on_non_200_decoration(no_warnings):
class ExceptionSerializer(serializers.Serializer):
api_status_code = serializers.CharField()
extra = serializers.DictField(required=False)
@extend_schema(
responses={
200: SimpleSerializer,
400: OpenApiResponse(
response=ExceptionSerializer,
examples=[
OpenApiExample(
"Date parse error",
value={"api_status_code": "DATE_PARSE_ERROR", "extra": {"details": "foobar"}},
status_codes=['400']
)
],
),
},
)
class XListView(generics.ListAPIView):
model = SimpleModel
serializer_class = SimpleSerializer
pagination_class = pagination.LimitOffsetPagination
schema = generate_schema('/x/', view=XListView)
# regular response listed/paginated
assert schema['paths']['/x/']['get']['responses']['200']['content']['application/json'] == {
'schema': {'$ref': '#/components/schemas/PaginatedSimpleList'}
}
# non-200 error response example NOT listed/paginated
assert schema['paths']['/x/']['get']['responses']['400']['content']['application/json'] == {
'examples': {
'DateParseError': {
'summary': 'Date parse error',
'value': {'api_status_code': 'DATE_PARSE_ERROR', 'extra': {'details': 'foobar'}}
}
},
'schema': {'$ref': '#/components/schemas/Exception'},
}
def test_inherited_status_code_from_response_container(no_warnings):
@extend_schema(
responses={
400: OpenApiResponse(
response=SimpleSerializer,
examples=[
# prior to the fix this required the argument status_code=[400]
# as the code was not passed down and the filtering sorted it out.
OpenApiExample("an example", value={"id": 3})
],
),
},
)
class XListView(generics.ListAPIView):
model = SimpleModel
serializer_class = SimpleSerializer
schema = generate_schema('/x/', view=XListView)
assert schema['paths']['/x/']['get']['responses']['400']['content']['application/json'] == {
'schema': {'$ref': '#/components/schemas/Simple'},
'examples': {'AnExample': {'value': {'id': 3}, 'summary': 'an example'}}
}
def test_examples_with_falsy_values(no_warnings):
@extend_schema(
responses=OpenApiResponse(
description='something',
response=OpenApiTypes.JSON_PTR,
examples=[
OpenApiExample('one', value=1),
OpenApiExample('empty-list', value=[]),
OpenApiExample('false', value=False),
OpenApiExample('zero', value=0),
OpenApiExample('empty'),
],
),
)
class XListView(generics.ListAPIView):
model = SimpleModel
serializer_class = SimpleSerializer
schema = generate_schema('/x/', view=XListView)
assert schema['paths']['/x/']['get']['responses']['200']['content']['application/json']['examples'] == {
'One': {'summary': 'one', 'value': 1},
'Empty-list': {'summary': 'empty-list', 'value': []},
'False': {'summary': 'false', 'value': False},
'Zero': {'summary': 'zero', 'value': 0},
'Empty': {'summary': 'empty'},
}
@pytest.mark.skipif(DRF_VERSION < '3.12', reason='DRF pagination schema broken')
def test_plain_pagination_example(no_warnings):
class PlainPagination(pagination.LimitOffsetPagination):
""" return a (unpaginated) basic list, while other might happen in the headers """
def get_paginated_response_schema(self, schema):
return schema
class PaginatedExamplesViewSet(ExampleTestWithExtendedViewSet):
pagination_class = PlainPagination
schema = generate_schema('e', PaginatedExamplesViewSet)
operation = schema['paths']['/e/']['get']
assert operation['responses']['200']['content']['application/json']['examples'] == {
'SerializerCExampleRO': {
'value': [{'field': 111}],
'summary': 'Serializer C Example RO'
},
'SerializerCExampleList': {
'value': [{'field': 333}, {'field': 444}],
'summary': 'Serializer C Example List'
}
}