Skip to content
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

Add support for x-enumDescriptions extension #1359

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,9 @@ def build_choice_field(field) -> _SchemaType:
if spectacular_settings.ENUM_GENERATE_CHOICE_DESCRIPTION:
schema['description'] = build_choice_description_list(field.choices.items())

if spectacular_settings.ENUM_GENERATE_X_ENUM_DESCRIPTIONS:
schema['x-enumDescriptions'] = dict(field.choices)

schema['x-spec-enum-id'] = list_hash([(k, v) for k, v in field.choices.items() if k not in ('', None)])

return schema
Expand Down
2 changes: 2 additions & 0 deletions drf_spectacular/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@
'ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE': True,
# Add/Append a list of (``choice value`` - choice name) to the enum description string.
'ENUM_GENERATE_CHOICE_DESCRIPTION': True,
# Add x-enumDescriptions extension field to enum schemas.
'ENUM_GENERATE_X_ENUM_DESCRIPTIONS': False,
# Optional suffix for generated enum.
# e.g. {'ENUM_SUFFIX': "Type"} would produce an enum name 'StatusType'.
'ENUM_SUFFIX': 'Enum',
Expand Down
13 changes: 13 additions & 0 deletions tests/test_plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import typing
from datetime import datetime
from enum import Enum
from unittest import mock

if sys.version_info >= (3, 8):
from typing import TypedDict
Expand Down Expand Up @@ -424,6 +425,18 @@ def test_choicefield_empty_choices():
assert schema['type'] == 'string'


@mock.patch('drf_spectacular.settings.spectacular_settings.ENUM_GENERATE_X_ENUM_DESCRIPTIONS', True)
def test_choicefield_x_enumdescriptions():
schema = build_choice_field(serializers.ChoiceField(
[('bluepill', 'Blue Pill'), ('redpill', 'Red Pill')],
allow_null=True, allow_blank=True
))
assert schema['x-enumDescriptions'] == {
'bluepill': 'Blue Pill',
'redpill': 'Red Pill',
}


def test_safe_ref():
schema = build_basic_type(str)
schema['$ref'] = '#/components/schemas/Foo'
Expand Down
Loading