Debian Codegraph @

tests/schemas/test_openapi.py

raw
1 import uuid
2 import warnings
3
4 import pytest
5 from django.db import models
6 from django.test import RequestFactory, TestCase, override_settings
7 from django.urls import path
8 from django.utils.safestring import SafeString
9 from django.utils.translation import gettext_lazy as _
10
11 from rest_framework import filters, generics, pagination, routers, serializers
12 from rest_framework.authtoken.views import obtain_auth_token
13 from rest_framework.compat import uritemplate
14 from rest_framework.parsers import JSONParser, MultiPartParser
15 from rest_framework.renderers import (
16 BaseRenderer, BrowsableAPIRenderer, JSONOpenAPIRenderer, JSONRenderer,
17 OpenAPIRenderer
18 )
19 from rest_framework.request import Request
20 from rest_framework.schemas.openapi import AutoSchema, SchemaGenerator
21
22 from ..models import BasicModel
23 from . import views
24
25
26 def create_request(path):
27 factory = RequestFactory()
28 request = Request(factory.get(path))
29 return request
30
31
32 def create_view(view_cls, method, request):
33 generator = SchemaGenerator()
34 view = generator.create_view(view_cls.as_view(), method, request)
35 return view
36
37
38 class TestBasics(TestCase):
39 def dummy_view(request):
40 pass
41
42 def test_filters(self):
43 classes = [filters.SearchFilter, filters.OrderingFilter]
44 for c in classes:
45 f = c()
46 assert f.get_schema_operation_parameters(self.dummy_view)
47
48 def test_pagination(self):
49 classes = [pagination.PageNumberPagination, pagination.LimitOffsetPagination, pagination.CursorPagination]
50 for c in classes:
51 f = c()
52 assert f.get_schema_operation_parameters(self.dummy_view)
53
54
55 class TestFieldMapping(TestCase):
56 def test_list_field_mapping(self):
57 uuid1 = uuid.uuid4()
58 uuid2 = uuid.uuid4()
59 inspector = AutoSchema()
60 cases = [
61 (serializers.ListField(), {'items': {}, 'type': 'array'}),
62 (serializers.ListField(child=serializers.BooleanField()), {'items': {'type': 'boolean'}, 'type': 'array'}),
63 (serializers.ListField(child=serializers.FloatField()), {'items': {'type': 'number'}, 'type': 'array'}),
64 (serializers.ListField(child=serializers.FloatField(min_value=0.0)),
65 {'items': {'type': 'number', 'minimum': 0.0}, 'type': 'array'}),
66 (serializers.ListField(child=serializers.FloatField(max_value=0.0)),
67 {'items': {'type': 'number', 'maximum': 0.0}, 'type': 'array'}),
68 (serializers.ListField(child=serializers.CharField()), {'items': {'type': 'string'}, 'type': 'array'}),
69 (serializers.ListField(child=serializers.IntegerField(min_value=0)),
70 {'items': {'type': 'integer', 'minimum': 0}, 'type': 'array'}),
71 (serializers.ListField(child=serializers.IntegerField(max_value=0)),
72 {'items': {'type': 'integer', 'maximum': 0}, 'type': 'array'}),
73 (serializers.ListField(child=serializers.IntegerField(max_value=4294967295)),
74 {'items': {'type': 'integer', 'maximum': 4294967295, 'format': 'int64'}, 'type': 'array'}),
75 (serializers.ListField(child=serializers.ChoiceField(choices=[('a', 'Choice A'), ('b', 'Choice B')])),
76 {'items': {'enum': ['a', 'b'], 'type': 'string'}, 'type': 'array'}),
77 (serializers.ListField(child=serializers.ChoiceField(choices=[(1, 'One'), (2, 'Two')])),
78 {'items': {'enum': [1, 2], 'type': 'integer'}, 'type': 'array'}),
79 (serializers.ListField(child=serializers.ChoiceField(choices=[(1.1, 'First'), (2.2, 'Second')])),
80 {'items': {'enum': [1.1, 2.2], 'type': 'number'}, 'type': 'array'}),
81 (serializers.ListField(child=serializers.ChoiceField(choices=[(True, 'true'), (False, 'false')])),
82 {'items': {'enum': [True, False], 'type': 'boolean'}, 'type': 'array'}),
83 (serializers.ListField(child=serializers.ChoiceField(choices=[(uuid1, 'uuid1'), (uuid2, 'uuid2')])),
84 {'items': {'enum': [uuid1, uuid2]}, 'type': 'array'}),
85 (serializers.ListField(child=serializers.ChoiceField(choices=[(1, 'One'), ('a', 'Choice A')])),
86 {'items': {'enum': [1, 'a']}, 'type': 'array'}),
87 (serializers.ListField(child=serializers.ChoiceField(choices=[
88 (1, 'One'), ('a', 'Choice A'), (1.1, 'First'), (1.1, 'First'), (1, 'One'), ('a', 'Choice A'), (1, 'One')
89 ])),
90 {'items': {'enum': [1, 'a', 1.1]}, 'type': 'array'}),
91 (serializers.ListField(child=serializers.ChoiceField(choices=[
92 (1, 'One'), (2, 'Two'), (3, 'Three'), (2, 'Two'), (3, 'Three'), (1, 'One'),
93 ])),
94 {'items': {'enum': [1, 2, 3], 'type': 'integer'}, 'type': 'array'}),
95 (serializers.IntegerField(min_value=2147483648),
96 {'type': 'integer', 'minimum': 2147483648, 'format': 'int64'}),
97 ]
98 for field, mapping in cases:
99 with self.subTest(field=field):
100 assert inspector.map_field(field) == mapping
101
102 def test_integer_field_int64_boundary_mapping(self):
103 inspector = AutoSchema()
104 cases = [
105 (
106 serializers.IntegerField(min_value=-2147483649),
107 {'type': 'integer', 'minimum': -2147483649, 'format': 'int64'},
108 ),
109 (
110 serializers.IntegerField(max_value=-2147483649),
111 {'type': 'integer', 'maximum': -2147483649, 'format': 'int64'},
112 ),
113 (
114 serializers.IntegerField(min_value=-2147483648),
115 {'type': 'integer', 'minimum': -2147483648},
116 ),
117 (
118 serializers.IntegerField(max_value=2147483648),
119 {'type': 'integer', 'maximum': 2147483648, 'format': 'int64'},
120 ),
121 (
122 serializers.IntegerField(max_value=2147483647),
123 {'type': 'integer', 'maximum': 2147483647},
124 ),
125 (
126 serializers.IntegerField(min_value=2147483648),
127 {'type': 'integer', 'minimum': 2147483648, 'format': 'int64'},
128 ),
129 ]
130 for field, mapping in cases:
131 with self.subTest(field=field):
132 assert inspector.map_field(field) == mapping
133
134 def test_lazy_string_field(self):
135 class ItemSerializer(serializers.Serializer):
136 text = serializers.CharField(help_text=_('lazy string'))
137
138 inspector = AutoSchema()
139
140 data = inspector.map_serializer(ItemSerializer())
141 assert isinstance(data['properties']['text']['description'], str), "description must be str"
142
143 def test_boolean_default_field(self):
144 class Serializer(serializers.Serializer):
145 default_true = serializers.BooleanField(default=True)
146 default_false = serializers.BooleanField(default=False)
147 without_default = serializers.BooleanField()
148
149 inspector = AutoSchema()
150
151 data = inspector.map_serializer(Serializer())
152 assert data['properties']['default_true']['default'] is True, "default must be true"
153 assert data['properties']['default_false']['default'] is False, "default must be false"
154 assert 'default' not in data['properties']['without_default'], "default must not be defined"
155
156 def test_custom_field_name(self):
157 class CustomSchema(AutoSchema):
158 def get_field_name(self, field):
159 return 'custom_' + field.field_name
160
161 class Serializer(serializers.Serializer):
162 text_field = serializers.CharField()
163
164 inspector = CustomSchema()
165
166 data = inspector.map_serializer(Serializer())
167 assert 'custom_text_field' in data['properties']
168 assert 'text_field' not in data['properties']
169
170 def test_nullable_fields(self):
171 class Model(models.Model):
172 rw_field = models.CharField(null=True)
173 ro_field = models.CharField(null=True)
174
175 class Serializer(serializers.ModelSerializer):
176 class Meta:
177 model = Model
178 fields = ["rw_field", "ro_field"]
179 read_only_fields = ["ro_field"]
180
181 inspector = AutoSchema()
182
183 data = inspector.map_serializer(Serializer())
184 assert data['properties']['rw_field']['nullable'], "rw_field nullable must be true"
185 assert data['properties']['ro_field']['nullable'], "ro_field nullable must be true"
186 assert data['properties']['ro_field']['readOnly'], "ro_field read_only must be true"
187
188 def test_primary_key_related_field(self):
189 class PrimaryKeyRelatedFieldSerializer(serializers.Serializer):
190 basic = serializers.PrimaryKeyRelatedField(queryset=BasicModel.objects.all())
191 uuid = serializers.PrimaryKeyRelatedField(queryset=BasicModel.objects.all(),
192 pk_field=serializers.UUIDField())
193 char = serializers.PrimaryKeyRelatedField(queryset=BasicModel.objects.all(),
194 pk_field=serializers.CharField())
195
196 serializer = PrimaryKeyRelatedFieldSerializer()
197 inspector = AutoSchema()
198
199 data = inspector.map_serializer(serializer=serializer)
200 assert data['properties']['basic']['type'] == "integer"
201 assert data['properties']['uuid']['format'] == "uuid"
202 assert data['properties']['char']['type'] == "string"
203
204
205 @pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.')
206 class TestOperationIntrospection(TestCase):
207
208 def test_path_without_parameters(self):
209 path = '/example/'
210 method = 'GET'
211
212 view = create_view(
213 views.DocStringExampleListView,
214 method,
215 create_request(path)
216 )
217 inspector = AutoSchema()
218 inspector.view = view
219
220 operation = inspector.get_operation(path, method)
221 assert operation == {
222 'operationId': 'listDocStringExamples',
223 'description': 'A description of my GET operation.',
224 'parameters': [],
225 'tags': ['example'],
226 'responses': {
227 '200': {
228 'description': '',
229 'content': {
230 'application/json': {
231 'schema': {
232 'type': 'array',
233 'items': {},
234 },
235 },
236 },
237 },
238 },
239 }
240
241 def test_path_with_id_parameter(self):
242 path = '/example/{id}/'
243 method = 'GET'
244
245 view = create_view(
246 views.DocStringExampleDetailView,
247 method,
248 create_request(path)
249 )
250 inspector = AutoSchema()
251 inspector.view = view
252
253 operation = inspector.get_operation(path, method)
254 assert operation == {
255 'operationId': 'retrieveDocStringExampleDetail',
256 'description': 'A description of my GET operation.',
257 'parameters': [{
258 'description': '',
259 'in': 'path',
260 'name': 'id',
261 'required': True,
262 'schema': {
263 'type': 'string',
264 },
265 }],
266 'tags': ['example'],
267 'responses': {
268 '200': {
269 'description': '',
270 'content': {
271 'application/json': {
272 'schema': {
273 },
274 },
275 },
276 },
277 },
278 }
279
280 def test_request_body(self):
281 path = '/'
282 method = 'POST'
283
284 class ItemSerializer(serializers.Serializer):
285 text = serializers.CharField()
286 read_only = serializers.CharField(read_only=True)
287
288 class View(generics.GenericAPIView):
289 serializer_class = ItemSerializer
290
291 view = create_view(
292 View,
293 method,
294 create_request(path)
295 )
296 inspector = AutoSchema()
297 inspector.view = view
298
299 request_body = inspector.get_request_body(path, method)
300 assert request_body['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item'
301
302 components = inspector.get_components(path, method)
303 assert components['Item']['required'] == ['text']
304 assert sorted(list(components['Item']['properties'].keys())) == ['read_only', 'text']
305
306 def test_invalid_serializer_class_name(self):
307 path = '/'
308 method = 'POST'
309
310 class Serializer(serializers.Serializer):
311 text = serializers.CharField()
312 read_only = serializers.CharField(read_only=True)
313
314 class View(generics.GenericAPIView):
315 serializer_class = Serializer
316
317 view = create_view(
318 View,
319 method,
320 create_request(path)
321 )
322 inspector = AutoSchema()
323 inspector.view = view
324
325 serializer = inspector.get_serializer(path, method)
326
327 with pytest.raises(Exception) as exc:
328 inspector.get_component_name(serializer)
329 assert "is an invalid class name for schema generation" in str(exc.value)
330
331 def test_empty_required(self):
332 path = '/'
333 method = 'POST'
334
335 class ItemSerializer(serializers.Serializer):
336 read_only = serializers.CharField(read_only=True)
337 write_only = serializers.CharField(write_only=True, required=False)
338
339 class View(generics.GenericAPIView):
340 serializer_class = ItemSerializer
341
342 view = create_view(
343 View,
344 method,
345 create_request(path)
346 )
347 inspector = AutoSchema()
348 inspector.view = view
349
350 components = inspector.get_components(path, method)
351 component = components['Item']
352 # there should be no empty 'required' property, see #6834
353 assert 'required' not in component
354
355 for response in inspector.get_responses(path, method).values():
356 assert 'required' not in component
357
358 def test_empty_required_with_patch_method(self):
359 path = '/'
360 method = 'PATCH'
361
362 class ItemSerializer(serializers.Serializer):
363 read_only = serializers.CharField(read_only=True)
364 write_only = serializers.CharField(write_only=True, required=False)
365
366 class View(generics.GenericAPIView):
367 serializer_class = ItemSerializer
368
369 view = create_view(
370 View,
371 method,
372 create_request(path)
373 )
374 inspector = AutoSchema()
375 inspector.view = view
376
377 components = inspector.get_components(path, method)
378 component = components['Item']
379 # there should be no empty 'required' property, see #6834
380 assert 'required' not in component
381 for response in inspector.get_responses(path, method).values():
382 assert 'required' not in component
383
384 def test_response_body_generation(self):
385 path = '/'
386 method = 'POST'
387
388 class ItemSerializer(serializers.Serializer):
389 text = serializers.CharField()
390 write_only = serializers.CharField(write_only=True)
391
392 class View(generics.GenericAPIView):
393 serializer_class = ItemSerializer
394
395 view = create_view(
396 View,
397 method,
398 create_request(path)
399 )
400 inspector = AutoSchema()
401 inspector.view = view
402
403 responses = inspector.get_responses(path, method)
404 assert responses['201']['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item'
405
406 components = inspector.get_components(path, method)
407 assert sorted(components['Item']['required']) == ['text', 'write_only']
408 assert sorted(list(components['Item']['properties'].keys())) == ['text', 'write_only']
409 assert 'description' in responses['201']
410
411 def test_response_body_nested_serializer(self):
412 path = '/'
413 method = 'POST'
414
415 class NestedSerializer(serializers.Serializer):
416 number = serializers.IntegerField()
417
418 class ItemSerializer(serializers.Serializer):
419 text = serializers.CharField()
420 nested = NestedSerializer()
421
422 class View(generics.GenericAPIView):
423 serializer_class = ItemSerializer
424
425 view = create_view(
426 View,
427 method,
428 create_request(path),
429 )
430 inspector = AutoSchema()
431 inspector.view = view
432
433 responses = inspector.get_responses(path, method)
434 assert responses['201']['content']['application/json']['schema']['$ref'] == '#/components/schemas/Item'
435 components = inspector.get_components(path, method)
436 assert components['Item']
437
438 schema = components['Item']
439 assert sorted(schema['required']) == ['nested', 'text']
440 assert sorted(list(schema['properties'].keys())) == ['nested', 'text']
441 assert schema['properties']['nested']['type'] == 'object'
442 assert list(schema['properties']['nested']['properties'].keys()) == ['number']
443 assert schema['properties']['nested']['required'] == ['number']
444
445 def test_response_body_partial_serializer(self):
446 path = '/'
447 method = 'GET'
448
449 class ItemSerializer(serializers.Serializer):
450 text = serializers.CharField()
451
452 def __init__(self, *args, **kwargs):
453 super().__init__(*args, **kwargs)
454 self.partial = True
455
456 class View(generics.GenericAPIView):
457 serializer_class = ItemSerializer
458
459 view = create_view(
460 View,
461 method,
462 create_request(path),
463 )
464 inspector = AutoSchema()
465 inspector.view = view
466
467 responses = inspector.get_responses(path, method)
468 assert responses == {
469 '200': {
470 'description': '',
471 'content': {
472 'application/json': {
473 'schema': {
474 'type': 'array',
475 'items': {
476 '$ref': '#/components/schemas/Item'
477 },
478 },
479 },
480 },
481 },
482 }
483 components = inspector.get_components(path, method)
484 assert components == {
485 'Item': {
486 'type': 'object',
487 'properties': {
488 'text': {
489 'type': 'string',
490 },
491 },
492 }
493 }
494
495 def test_list_response_body_generation(self):
496 """Test that an array schema is returned for list views."""
497 path = '/'
498 method = 'GET'
499
500 class ItemSerializer(serializers.Serializer):
501 text = serializers.CharField()
502
503 class View(generics.GenericAPIView):
504 serializer_class = ItemSerializer
505
506 view = create_view(
507 View,
508 method,
509 create_request(path),
510 )
511 inspector = AutoSchema()
512 inspector.view = view
513
514 responses = inspector.get_responses(path, method)
515 assert responses == {
516 '200': {
517 'description': '',
518 'content': {
519 'application/json': {
520 'schema': {
521 'type': 'array',
522 'items': {
523 '$ref': '#/components/schemas/Item'
524 },
525 },
526 },
527 },
528 },
529 }
530 components = inspector.get_components(path, method)
531 assert components == {
532 'Item': {
533 'type': 'object',
534 'properties': {
535 'text': {
536 'type': 'string',
537 },
538 },
539 'required': ['text'],
540 }
541 }
542
543 def test_paginated_list_response_body_generation(self):
544 """Test that pagination properties are added for a paginated list view."""
545 path = '/'
546 method = 'GET'
547
548 class Pagination(pagination.BasePagination):
549 def get_paginated_response_schema(self, schema):
550 return {
551 'type': 'object',
552 'item': schema,
553 }
554
555 class ItemSerializer(serializers.Serializer):
556 text = serializers.CharField()
557
558 class View(generics.GenericAPIView):
559 serializer_class = ItemSerializer
560 pagination_class = Pagination
561
562 view = create_view(
563 View,
564 method,
565 create_request(path),
566 )
567 inspector = AutoSchema()
568 inspector.view = view
569
570 responses = inspector.get_responses(path, method)
571 assert responses == {
572 '200': {
573 'description': '',
574 'content': {
575 'application/json': {
576 'schema': {
577 'type': 'object',
578 'item': {
579 'type': 'array',
580 'items': {
581 '$ref': '#/components/schemas/Item'
582 },
583 },
584 },
585 },
586 },
587 },
588 }
589 components = inspector.get_components(path, method)
590 assert components == {
591 'Item': {
592 'type': 'object',
593 'properties': {
594 'text': {
595 'type': 'string',
596 },
597 },
598 'required': ['text'],
599 }
600 }
601
602 def test_delete_response_body_generation(self):
603 """Test that a view's delete method generates a proper response body schema."""
604 path = '/{id}/'
605 method = 'DELETE'
606
607 class View(generics.DestroyAPIView):
608 serializer_class = views.ExampleSerializer
609
610 view = create_view(
611 View,
612 method,
613 create_request(path),
614 )
615 inspector = AutoSchema()
616 inspector.view = view
617
618 responses = inspector.get_responses(path, method)
619 assert responses == {
620 '204': {
621 'description': '',
622 },
623 }
624
625 def test_parser_mapping(self):
626 """Test that view's parsers are mapped to OA media types"""
627 path = '/{id}/'
628 method = 'POST'
629
630 class View(generics.CreateAPIView):
631 serializer_class = views.ExampleSerializer
632 parser_classes = [JSONParser, MultiPartParser]
633
634 view = create_view(
635 View,
636 method,
637 create_request(path),
638 )
639 inspector = AutoSchema()
640 inspector.view = view
641
642 request_body = inspector.get_request_body(path, method)
643
644 assert len(request_body['content'].keys()) == 2
645 assert 'multipart/form-data' in request_body['content']
646 assert 'application/json' in request_body['content']
647
648 def test_renderer_mapping(self):
649 """Test that view's renderers are mapped to OA media types"""
650 path = '/{id}/'
651 method = 'GET'
652
653 class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
654 media_type = 'image/jpeg' # that's a wild API renderer
655
656 class TextRenderer(BaseRenderer):
657 media_type = 'text/plain'
658 format = 'text'
659
660 class View(generics.CreateAPIView):
661 serializer_class = views.ExampleSerializer
662 renderer_classes = [JSONRenderer, TextRenderer, BrowsableAPIRenderer, CustomBrowsableAPIRenderer]
663
664 view = create_view(
665 View,
666 method,
667 create_request(path),
668 )
669 inspector = AutoSchema()
670 inspector.view = view
671
672 responses = inspector.get_responses(path, method)
673 # TODO this should be changed once the multiple response
674 # schema support is there
675 success_response = responses['200']
676
677 # Check that the API renderers aren't included, but custom renderers are
678 assert set(success_response['content']) == {'application/json', 'text/plain'}
679
680 def test_openapi_yaml_rendering_without_aliases(self):
681 renderer = OpenAPIRenderer()
682
683 reused_object = {'test': 'test'}
684 data = {
685 'o1': reused_object,
686 'o2': reused_object,
687 }
688 assert (
689 renderer.render(data) == b'o1:\n test: test\no2:\n test: test\n' or
690 renderer.render(data) == b'o2:\n test: test\no1:\n test: test\n' # py <= 3.5
691 )
692
693 def test_openapi_yaml_safestring_render(self):
694 renderer = OpenAPIRenderer()
695 data = {'o1': SafeString('test')}
696 assert renderer.render(data) == b'o1: test\n'
697
698 def test_serializer_filefield(self):
699 path = '/{id}/'
700 method = 'POST'
701
702 class ItemSerializer(serializers.Serializer):
703 attachment = serializers.FileField()
704
705 class View(generics.CreateAPIView):
706 serializer_class = ItemSerializer
707
708 view = create_view(
709 View,
710 method,
711 create_request(path),
712 )
713 inspector = AutoSchema()
714 inspector.view = view
715
716 components = inspector.get_components(path, method)
717 component = components['Item']
718 properties = component['properties']
719 assert properties['attachment']['format'] == 'binary'
720
721 def test_retrieve_response_body_generation(self):
722 """
723 Test that a list of properties is returned for retrieve item views.
724
725 Pagination properties should not be added as the view represents a single item.
726 """
727 path = '/{id}/'
728 method = 'GET'
729
730 class Pagination(pagination.BasePagination):
731 def get_paginated_response_schema(self, schema):
732 return {
733 'type': 'object',
734 'item': schema,
735 }
736
737 class ItemSerializer(serializers.Serializer):
738 text = serializers.CharField()
739
740 class View(generics.GenericAPIView):
741 serializer_class = ItemSerializer
742 pagination_class = Pagination
743
744 view = create_view(
745 View,
746 method,
747 create_request(path),
748 )
749 inspector = AutoSchema()
750 inspector.view = view
751
752 responses = inspector.get_responses(path, method)
753 assert responses == {
754 '200': {
755 'description': '',
756 'content': {
757 'application/json': {
758 'schema': {
759 '$ref': '#/components/schemas/Item'
760 },
761 },
762 },
763 },
764 }
765
766 components = inspector.get_components(path, method)
767 assert components == {
768 'Item': {
769 'type': 'object',
770 'properties': {
771 'text': {
772 'type': 'string',
773 },
774 },
775 'required': ['text'],
776 }
777 }
778
779 def test_operation_id_generation(self):
780 path = '/'
781 method = 'GET'
782
783 view = create_view(
784 views.ExampleGenericAPIView,
785 method,
786 create_request(path),
787 )
788 inspector = AutoSchema()
789 inspector.view = view
790
791 operationId = inspector.get_operation_id(path, method)
792 assert operationId == 'listExamples'
793
794 def test_operation_id_custom_operation_id_base(self):
795 path = '/'
796 method = 'GET'
797
798 view = create_view(
799 views.ExampleGenericAPIView,
800 method,
801 create_request(path),
802 )
803 inspector = AutoSchema(operation_id_base="Ulysse")
804 inspector.view = view
805
806 operationId = inspector.get_operation_id(path, method)
807 assert operationId == 'listUlysses'
808
809 def test_operation_id_custom_name(self):
810 path = '/'
811 method = 'GET'
812
813 view = create_view(
814 views.ExampleGenericAPIView,
815 method,
816 create_request(path),
817 )
818 inspector = AutoSchema(operation_id_base='Ulysse')
819 inspector.view = view
820
821 operationId = inspector.get_operation_id(path, method)
822 assert operationId == 'listUlysses'
823
824 def test_operation_id_plural(self):
825 path = '/'
826 method = 'GET'
827
828 view = create_view(
829 views.ExampleGenericAPIView,
830 method,
831 create_request(path),
832 )
833 inspector = AutoSchema(operation_id_base='City')
834 inspector.view = view
835
836 operationId = inspector.get_operation_id(path, method)
837 assert operationId == 'listCities'
838
839 def test_operation_id_override_get(self):
840 class CustomSchema(AutoSchema):
841 def get_operation_id(self, path, method):
842 return 'myCustomOperationId'
843
844 path = '/'
845 method = 'GET'
846 view = create_view(
847 views.ExampleGenericAPIView,
848 method,
849 create_request(path),
850 )
851 inspector = CustomSchema()
852 inspector.view = view
853
854 operationId = inspector.get_operation_id(path, method)
855 assert operationId == 'myCustomOperationId'
856
857 def test_operation_id_override_base(self):
858 class CustomSchema(AutoSchema):
859 def get_operation_id_base(self, path, method, action):
860 return 'Item'
861
862 path = '/'
863 method = 'GET'
864 view = create_view(
865 views.ExampleGenericAPIView,
866 method,
867 create_request(path),
868 )
869 inspector = CustomSchema()
870 inspector.view = view
871
872 operationId = inspector.get_operation_id(path, method)
873 assert operationId == 'listItem'
874
875 def test_different_request_response_objects(self):
876 class RequestSerializer(serializers.Serializer):
877 text = serializers.CharField()
878
879 class ResponseSerializer(serializers.Serializer):
880 text = serializers.BooleanField()
881
882 class CustomSchema(AutoSchema):
883 def get_request_serializer(self, path, method):
884 return RequestSerializer()
885
886 def get_response_serializer(self, path, method):
887 return ResponseSerializer()
888
889 path = '/'
890 method = 'POST'
891 view = create_view(
892 views.ExampleGenericAPIView,
893 method,
894 create_request(path),
895 )
896 inspector = CustomSchema()
897 inspector.view = view
898
899 components = inspector.get_components(path, method)
900 assert components == {
901 'Request': {
902 'properties': {
903 'text': {
904 'type': 'string'
905 }
906 },
907 'required': ['text'],
908 'type': 'object'
909 },
910 'Response': {
911 'properties': {
912 'text': {
913 'type': 'boolean'
914 }
915 },
916 'required': ['text'],
917 'type': 'object'
918 }
919 }
920
921 operation = inspector.get_operation(path, method)
922 assert operation == {
923 'operationId': 'createExample',
924 'description': '',
925 'parameters': [],
926 'requestBody': {
927 'content': {
928 'application/json': {
929 'schema': {
930 '$ref': '#/components/schemas/Request'
931 }
932 },
933 'application/x-www-form-urlencoded': {
934 'schema': {
935 '$ref': '#/components/schemas/Request'
936 }
937 },
938 'multipart/form-data': {
939 'schema': {
940 '$ref': '#/components/schemas/Request'
941 }
942 }
943 }
944 },
945 'responses': {
946 '201': {
947 'content': {
948 'application/json': {
949 'schema': {
950 '$ref': '#/components/schemas/Response'
951 }
952 }
953 },
954 'description': ''
955 }
956 },
957 'tags': ['']
958 }
959
960 def test_repeat_operation_ids(self):
961 router = routers.SimpleRouter()
962 router.register('account', views.ExampleGenericViewSet, basename="account")
963 urlpatterns = router.urls
964
965 generator = SchemaGenerator(patterns=urlpatterns)
966
967 request = create_request('/')
968 schema = generator.get_schema(request=request)
969 schema_str = str(schema)
970 assert schema_str.count("operationId") == 2
971 assert schema_str.count("newExample") == 1
972 assert schema_str.count("oldExample") == 1
973
974 def test_duplicate_operation_id(self):
975 patterns = [
976 path('duplicate1/', views.ExampleOperationIdDuplicate1.as_view()),
977 path('duplicate2/', views.ExampleOperationIdDuplicate2.as_view()),
978 ]
979
980 generator = SchemaGenerator(patterns=patterns)
981 request = create_request('/')
982
983 with warnings.catch_warnings(record=True) as w:
984 warnings.simplefilter('always')
985 generator.get_schema(request=request)
986
987 assert len(w) == 1
988 assert issubclass(w[-1].category, UserWarning)
989 assert 'You have a duplicated operationId' in str(w[-1].message)
990
991 def test_operation_id_viewset(self):
992 router = routers.SimpleRouter()
993 router.register('account', views.ExampleViewSet, basename="account")
994 urlpatterns = router.urls
995
996 generator = SchemaGenerator(patterns=urlpatterns)
997
998 request = create_request('/')
999 schema = generator.get_schema(request=request)
1000 assert schema['paths']['/account/']['get']['operationId'] == 'listExampleViewSets'
1001 assert schema['paths']['/account/']['post']['operationId'] == 'createExampleViewSet'
1002 assert schema['paths']['/account/{id}/']['get']['operationId'] == 'retrieveExampleViewSet'
1003 assert schema['paths']['/account/{id}/']['put']['operationId'] == 'updateExampleViewSet'
1004 assert schema['paths']['/account/{id}/']['patch']['operationId'] == 'partialUpdateExampleViewSet'
1005 assert schema['paths']['/account/{id}/']['delete']['operationId'] == 'destroyExampleViewSet'
1006
1007 def test_serializer_datefield(self):
1008 path = '/'
1009 method = 'GET'
1010 view = create_view(
1011 views.ExampleGenericAPIView,
1012 method,
1013 create_request(path),
1014 )
1015 inspector = AutoSchema()
1016 inspector.view = view
1017
1018 components = inspector.get_components(path, method)
1019 component = components['Example']
1020 properties = component['properties']
1021 assert properties['date']['type'] == properties['datetime']['type'] == 'string'
1022 assert properties['date']['format'] == 'date'
1023 assert properties['datetime']['format'] == 'date-time'
1024
1025 def test_serializer_hstorefield(self):
1026 path = '/'
1027 method = 'GET'
1028 view = create_view(
1029 views.ExampleGenericAPIView,
1030 method,
1031 create_request(path),
1032 )
1033 inspector = AutoSchema()
1034 inspector.view = view
1035
1036 components = inspector.get_components(path, method)
1037 component = components['Example']
1038 properties = component['properties']
1039 assert properties['hstore']['type'] == 'object'
1040
1041 def test_serializer_callable_default(self):
1042 path = '/'
1043 method = 'GET'
1044 view = create_view(
1045 views.ExampleGenericAPIView,
1046 method,
1047 create_request(path),
1048 )
1049 inspector = AutoSchema()
1050 inspector.view = view
1051
1052 components = inspector.get_components(path, method)
1053 component = components['Example']
1054 properties = component['properties']
1055 assert 'default' not in properties['uuid_field']
1056
1057 def test_serializer_validators(self):
1058 path = '/'
1059 method = 'GET'
1060 view = create_view(
1061 views.ExampleValidatedAPIView,
1062 method,
1063 create_request(path),
1064 )
1065 inspector = AutoSchema()
1066 inspector.view = view
1067
1068 components = inspector.get_components(path, method)
1069 component = components['ExampleValidated']
1070 properties = component['properties']
1071
1072 assert properties['integer']['type'] == 'integer'
1073 assert properties['integer']['maximum'] == 99
1074 assert properties['integer']['minimum'] == -11
1075
1076 assert properties['string']['minLength'] == 2
1077 assert properties['string']['maxLength'] == 10
1078
1079 assert properties['lst']['minItems'] == 2
1080 assert properties['lst']['maxItems'] == 10
1081
1082 assert properties['regex']['pattern'] == r'[ABC]12{3}'
1083 assert properties['regex']['description'] == 'must have an A, B, or C followed by 1222'
1084
1085 assert properties['decimal1']['type'] == 'number'
1086 assert properties['decimal1']['multipleOf'] == .01
1087 assert properties['decimal1']['maximum'] == 10000
1088 assert properties['decimal1']['minimum'] == -10000
1089
1090 assert properties['decimal2']['type'] == 'number'
1091 assert properties['decimal2']['multipleOf'] == .0001
1092
1093 assert properties['decimal3'] == {
1094 'type': 'string', 'format': 'decimal', 'maximum': 1000000, 'minimum': -1000000, 'multipleOf': 0.01
1095 }
1096 assert properties['decimal4'] == {
1097 'type': 'string', 'format': 'decimal', 'maximum': 1000000, 'minimum': -1000000, 'multipleOf': 0.01
1098 }
1099 assert properties['decimal5'] == {
1100 'type': 'string', 'format': 'decimal', 'maximum': 10000, 'minimum': -10000, 'multipleOf': 0.01
1101 }
1102
1103 assert properties['email']['type'] == 'string'
1104 assert properties['email']['format'] == 'email'
1105 assert properties['email']['default'] == '[email protected]'
1106
1107 assert properties['url']['type'] == 'string'
1108 assert properties['url']['nullable'] is True
1109 assert properties['url']['default'] == 'http://www.example.com'
1110 assert '\\Z' not in properties['url']['pattern']
1111
1112 assert properties['uuid']['type'] == 'string'
1113 assert properties['uuid']['format'] == 'uuid'
1114
1115 assert properties['ip4']['type'] == 'string'
1116 assert properties['ip4']['format'] == 'ipv4'
1117
1118 assert properties['ip6']['type'] == 'string'
1119 assert properties['ip6']['format'] == 'ipv6'
1120
1121 assert properties['ip']['type'] == 'string'
1122 assert 'format' not in properties['ip']
1123
1124 def test_overridden_tags(self):
1125 class ExampleStringTagsViewSet(views.ExampleGenericAPIView):
1126 schema = AutoSchema(tags=['example1', 'example2'])
1127
1128 url_patterns = [
1129 path('test/', ExampleStringTagsViewSet.as_view()),
1130 ]
1131 generator = SchemaGenerator(patterns=url_patterns)
1132 schema = generator.get_schema(request=create_request('/'))
1133 assert schema['paths']['/test/']['get']['tags'] == ['example1', 'example2']
1134
1135 def test_overridden_get_tags_method(self):
1136 class MySchema(AutoSchema):
1137 def get_tags(self, path, method):
1138 if path.endswith('/new/'):
1139 tags = ['tag1', 'tag2']
1140 elif path.endswith('/old/'):
1141 tags = ['tag2', 'tag3']
1142 else:
1143 tags = ['tag4', 'tag5']
1144
1145 return tags
1146
1147 class ExampleStringTagsViewSet(views.ExampleGenericViewSet):
1148 schema = MySchema()
1149
1150 router = routers.SimpleRouter()
1151 router.register('example', ExampleStringTagsViewSet, basename="example")
1152 generator = SchemaGenerator(patterns=router.urls)
1153 schema = generator.get_schema(request=create_request('/'))
1154 assert schema['paths']['/example/new/']['get']['tags'] == ['tag1', 'tag2']
1155 assert schema['paths']['/example/old/']['get']['tags'] == ['tag2', 'tag3']
1156
1157 def test_auto_generated_apiview_tags(self):
1158 class RestaurantAPIView(views.ExampleGenericAPIView):
1159 schema = AutoSchema(operation_id_base="restaurant")
1160 pass
1161
1162 class BranchAPIView(views.ExampleGenericAPIView):
1163 pass
1164
1165 url_patterns = [
1166 path('any-dash_underscore/', RestaurantAPIView.as_view()),
1167 path('restaurants/branches/', BranchAPIView.as_view())
1168 ]
1169 generator = SchemaGenerator(patterns=url_patterns)
1170 schema = generator.get_schema(request=create_request('/'))
1171 assert schema['paths']['/any-dash_underscore/']['get']['tags'] == ['any-dash-underscore']
1172 assert schema['paths']['/restaurants/branches/']['get']['tags'] == ['restaurants']
1173
1174
1175 @pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.')
1176 @override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.openapi.AutoSchema'})
1177 class TestGenerator(TestCase):
1178
1179 def test_override_settings(self):
1180 assert isinstance(views.ExampleListView.schema, AutoSchema)
1181
1182 def test_paths_construction(self):
1183 """Construction of the `paths` key."""
1184 patterns = [
1185 path('example/', views.ExampleListView.as_view()),
1186 ]
1187 generator = SchemaGenerator(patterns=patterns)
1188 generator._initialise_endpoints()
1189
1190 paths = generator.get_schema()["paths"]
1191
1192 assert '/example/' in paths
1193 example_operations = paths['/example/']
1194 assert len(example_operations) == 2
1195 assert 'get' in example_operations
1196 assert 'post' in example_operations
1197
1198 def test_prefixed_paths_construction(self):
1199 """Construction of the `paths` key maintains a common prefix."""
1200 patterns = [
1201 path('v1/example/', views.ExampleListView.as_view()),
1202 path('v1/example/{pk}/', views.ExampleDetailView.as_view()),
1203 ]
1204 generator = SchemaGenerator(patterns=patterns)
1205 generator._initialise_endpoints()
1206
1207 paths = generator.get_schema()["paths"]
1208
1209 assert '/v1/example/' in paths
1210 assert '/v1/example/{id}/' in paths
1211
1212 def test_mount_url_prefixed_to_paths(self):
1213 patterns = [
1214 path('example/', views.ExampleListView.as_view()),
1215 path('example/{pk}/', views.ExampleDetailView.as_view()),
1216 ]
1217 generator = SchemaGenerator(patterns=patterns, url='/api')
1218 generator._initialise_endpoints()
1219
1220 paths = generator.get_schema()["paths"]
1221
1222 assert '/api/example/' in paths
1223 assert '/api/example/{id}/' in paths
1224
1225 def test_schema_construction(self):
1226 """Construction of the top level dictionary."""
1227 patterns = [
1228 path('example/', views.ExampleListView.as_view()),
1229 ]
1230 generator = SchemaGenerator(patterns=patterns)
1231
1232 request = create_request('/')
1233 schema = generator.get_schema(request=request)
1234
1235 assert 'openapi' in schema
1236 assert 'paths' in schema
1237
1238 def test_schema_rendering_to_json(self):
1239 patterns = [
1240 path('example/', views.ExampleGenericAPIView.as_view()),
1241 ]
1242 generator = SchemaGenerator(patterns=patterns)
1243
1244 request = create_request('/')
1245 schema = generator.get_schema(request=request)
1246 ret = JSONOpenAPIRenderer().render(schema)
1247
1248 assert b'"openapi": "' in ret
1249 assert b'"default": "0.0"' in ret
1250
1251 def test_schema_rendering_to_yaml(self):
1252 patterns = [
1253 path('example/', views.ExampleGenericAPIView.as_view()),
1254 ]
1255 generator = SchemaGenerator(patterns=patterns)
1256
1257 request = create_request('/')
1258 schema = generator.get_schema(request=request)
1259 ret = OpenAPIRenderer().render(schema)
1260 assert b"openapi: " in ret
1261 assert b"default: '0.0'" in ret
1262
1263 def test_schema_rendering_timedelta_to_yaml_with_validator(self):
1264
1265 patterns = [
1266 path('example/', views.ExampleValidatedAPIView.as_view()),
1267 ]
1268 generator = SchemaGenerator(patterns=patterns)
1269
1270 request = create_request('/')
1271 schema = generator.get_schema(request=request)
1272 ret = OpenAPIRenderer().render(schema)
1273 assert b"openapi: " in ret
1274 assert b"duration:\n type: string\n minimum: \'10.0\'\n" in ret
1275
1276 def test_schema_with_no_paths(self):
1277 patterns = []
1278 generator = SchemaGenerator(patterns=patterns)
1279
1280 request = create_request('/')
1281 schema = generator.get_schema(request=request)
1282
1283 assert schema['paths'] == {}
1284
1285 def test_schema_information(self):
1286 """Construction of the top level dictionary."""
1287 patterns = [
1288 path('example/', views.ExampleListView.as_view()),
1289 ]
1290 generator = SchemaGenerator(patterns=patterns, title='My title', version='1.2.3', description='My description')
1291
1292 request = create_request('/')
1293 schema = generator.get_schema(request=request)
1294
1295 assert schema['info']['title'] == 'My title'
1296 assert schema['info']['version'] == '1.2.3'
1297 assert schema['info']['description'] == 'My description'
1298
1299 def test_schema_information_empty(self):
1300 """Construction of the top level dictionary."""
1301 patterns = [
1302 path('example/', views.ExampleListView.as_view()),
1303 ]
1304 generator = SchemaGenerator(patterns=patterns)
1305
1306 request = create_request('/')
1307 schema = generator.get_schema(request=request)
1308
1309 assert schema['info']['title'] == ''
1310 assert schema['info']['version'] == ''
1311
1312 def test_serializer_model(self):
1313 """Construction of the top level dictionary."""
1314 patterns = [
1315 path('example/', views.ExampleGenericAPIViewModel.as_view()),
1316 ]
1317
1318 generator = SchemaGenerator(patterns=patterns)
1319
1320 request = create_request('/')
1321 schema = generator.get_schema(request=request)
1322
1323 assert 'components' in schema
1324 assert 'schemas' in schema['components']
1325 assert 'ExampleModel' in schema['components']['schemas']
1326
1327 def test_authtoken_serializer(self):
1328 patterns = [
1329 path('api-token-auth/', obtain_auth_token)
1330 ]
1331 generator = SchemaGenerator(patterns=patterns)
1332
1333 request = create_request('/')
1334 schema = generator.get_schema(request=request)
1335
1336 route = schema['paths']['/api-token-auth/']['post']
1337 body_schema = route['requestBody']['content']['application/json']['schema']
1338
1339 assert body_schema == {
1340 '$ref': '#/components/schemas/AuthToken'
1341 }
1342 assert schema['components']['schemas']['AuthToken'] == {
1343 'type': 'object',
1344 'properties': {
1345 'username': {'type': 'string', 'writeOnly': True},
1346 'password': {'type': 'string', 'writeOnly': True},
1347 'token': {'type': 'string', 'readOnly': True},
1348 },
1349 'required': ['username', 'password']
1350 }
1351
1352 def test_component_name(self):
1353 patterns = [
1354 path('example/', views.ExampleAutoSchemaComponentName.as_view()),
1355 ]
1356
1357 generator = SchemaGenerator(patterns=patterns)
1358
1359 request = create_request('/')
1360 schema = generator.get_schema(request=request)
1361
1362 assert 'components' in schema
1363 assert 'schemas' in schema['components']
1364 assert 'Ulysses' in schema['components']['schemas']
1365
1366 def test_duplicate_component_name(self):
1367 patterns = [
1368 path('duplicate1/', views.ExampleAutoSchemaDuplicate1.as_view()),
1369 path('duplicate2/', views.ExampleAutoSchemaDuplicate2.as_view()),
1370 ]
1371
1372 generator = SchemaGenerator(patterns=patterns)
1373 request = create_request('/')
1374
1375 with warnings.catch_warnings(record=True) as w:
1376 warnings.simplefilter('always')
1377 schema = generator.get_schema(request=request)
1378
1379 assert len(w) == 1
1380 assert issubclass(w[-1].category, UserWarning)
1381 assert 'has been overridden with a different value.' in str(w[-1].message)
1382
1383 assert 'components' in schema
1384 assert 'schemas' in schema['components']
1385 assert 'Duplicate' in schema['components']['schemas']
1386
1387 def test_component_should_not_be_generated_for_delete_method(self):
1388 class ExampleView(generics.DestroyAPIView):
1389 schema = AutoSchema(operation_id_base='example')
1390
1391 url_patterns = [
1392 path('example/', ExampleView.as_view()),
1393 ]
1394 generator = SchemaGenerator(patterns=url_patterns)
1395 schema = generator.get_schema(request=create_request('/'))
1396 assert 'components' not in schema
1397 assert 'content' not in schema['paths']['/example/']['delete']['responses']['204']