Skip to content

Add type for choicefield #7161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jan 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions rest_framework/schemas/openapi.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import warnings
from collections import OrderedDict
from decimal import Decimal
from operator import attrgetter
from urllib.parse import urljoin

Expand Down Expand Up @@ -209,6 +211,34 @@ def _get_pagination_parameters(self, path, method):

return paginator.get_schema_operation_parameters(view)

def _map_choicefield(self, field):
choices = list(OrderedDict.fromkeys(field.choices)) # preserve order and remove duplicates
if all(isinstance(choice, bool) for choice in choices):
type = 'boolean'
elif all(isinstance(choice, int) for choice in choices):
type = 'integer'
elif all(isinstance(choice, (int, float, Decimal)) for choice in choices): # `number` includes `integer`
# Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21
type = 'number'
elif all(isinstance(choice, str) for choice in choices):
type = 'string'
else:
type = None

mapping = {
# The value of `enum` keyword MUST be an array and SHOULD be unique.
# Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.20
'enum': choices
}

# If We figured out `type` then and only then we should set it. It must be a string.
# Ref: https://swagger.io/docs/specification/data-models/data-types/#mixed-type
# It is optional but it can not be null.
# Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21
if type:
mapping['type'] = type
return mapping

def _map_field(self, field):

# Nested Serializers, `many` or not.
Expand Down Expand Up @@ -242,15 +272,11 @@ def _map_field(self, field):
if isinstance(field, serializers.MultipleChoiceField):
return {
'type': 'array',
'items': {
'enum': list(field.choices)
},
'items': self._map_choicefield(field)
}

if isinstance(field, serializers.ChoiceField):
return {
'enum': list(field.choices),
}
return self._map_choicefield(field)

# ListField.
if isinstance(field, serializers.ListField):
Expand Down
24 changes: 23 additions & 1 deletion tests/schemas/test_openapi.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import uuid

import pytest
from django.conf.urls import url
from django.test import RequestFactory, TestCase, override_settings
Expand Down Expand Up @@ -44,6 +46,8 @@ def test_pagination(self):

class TestFieldMapping(TestCase):
def test_list_field_mapping(self):
uuid1 = uuid.uuid4()
uuid2 = uuid.uuid4()
inspector = AutoSchema()
cases = [
(serializers.ListField(), {'items': {}, 'type': 'array'}),
Expand All @@ -53,7 +57,25 @@ def test_list_field_mapping(self):
(serializers.ListField(child=serializers.IntegerField(max_value=4294967295)),
{'items': {'type': 'integer', 'maximum': 4294967295, 'format': 'int64'}, 'type': 'array'}),
(serializers.ListField(child=serializers.ChoiceField(choices=[('a', 'Choice A'), ('b', 'Choice B')])),
{'items': {'enum': ['a', 'b']}, 'type': 'array'}),
{'items': {'enum': ['a', 'b'], 'type': 'string'}, 'type': 'array'}),
(serializers.ListField(child=serializers.ChoiceField(choices=[(1, 'One'), (2, 'Two')])),
{'items': {'enum': [1, 2], 'type': 'integer'}, 'type': 'array'}),
(serializers.ListField(child=serializers.ChoiceField(choices=[(1.1, 'First'), (2.2, 'Second')])),
{'items': {'enum': [1.1, 2.2], 'type': 'number'}, 'type': 'array'}),
(serializers.ListField(child=serializers.ChoiceField(choices=[(True, 'true'), (False, 'false')])),
{'items': {'enum': [True, False], 'type': 'boolean'}, 'type': 'array'}),
(serializers.ListField(child=serializers.ChoiceField(choices=[(uuid1, 'uuid1'), (uuid2, 'uuid2')])),
{'items': {'enum': [uuid1, uuid2]}, 'type': 'array'}),
(serializers.ListField(child=serializers.ChoiceField(choices=[(1, 'One'), ('a', 'Choice A')])),
{'items': {'enum': [1, 'a']}, 'type': 'array'}),
(serializers.ListField(child=serializers.ChoiceField(choices=[
(1, 'One'), ('a', 'Choice A'), (1.1, 'First'), (1.1, 'First'), (1, 'One'), ('a', 'Choice A'), (1, 'One')
])),
{'items': {'enum': [1, 'a', 1.1]}, 'type': 'array'}),
(serializers.ListField(child=serializers.ChoiceField(choices=[
(1, 'One'), (2, 'Two'), (3, 'Three'), (2, 'Two'), (3, 'Three'), (1, 'One'),
])),
{'items': {'enum': [1, 2, 3], 'type': 'integer'}, 'type': 'array'}),
(serializers.IntegerField(min_value=2147483648),
{'type': 'integer', 'minimum': 2147483648, 'format': 'int64'}),
]
Expand Down