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

Extend enum type hint support to more Enum subclasses #500

Merged
merged 1 commit into from
Sep 20, 2021
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
2 changes: 1 addition & 1 deletion drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -969,7 +969,7 @@ def resolve_type_hint(hint):
if all(type(args[0]) is type(choice) for choice in args):
schema.update(build_basic_type(type(args[0])))
return schema
elif inspect.isclass(hint) and issubclass(hint, Choices):
elif inspect.isclass(hint) and issubclass(hint, Enum):
return {
'enum': [item.value for item in hint],
**build_basic_type([t for t in hint.__mro__ if is_basic_type(t)][0])
Expand Down
11 changes: 11 additions & 0 deletions tests/test_plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import sys
import typing
from datetime import datetime
from enum import Enum

import pytest
from django import __version__ as DJANGO_VERSION
Expand Down Expand Up @@ -90,6 +91,11 @@ class NamedTupleB(typing.NamedTuple):
b: str


class LanguageEnum(str, Enum):
EN = 'en'
DE = 'de'


TYPE_HINT_TEST_PARAMS = [
(
typing.Optional[int],
Expand Down Expand Up @@ -136,6 +142,11 @@ class NamedTupleB(typing.NamedTuple):
)
]

TYPE_HINT_TEST_PARAMS.append((
LanguageEnum,
{'enum': ['en', 'de'], 'type': 'string'}
))

if DJANGO_VERSION > '3':
from django.db.models.enums import TextChoices # only available in Django>3

Expand Down
6 changes: 5 additions & 1 deletion tests/test_postprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ class LanguageEnum(Enum):
EN = 'en'


class LanguageStrEnum(str, Enum):
EN = 'en'


class LanguageChoices(TextChoices):
EN = 'en'

Expand Down Expand Up @@ -174,7 +178,7 @@ def partial_update(self, request):


def test_enum_override_variations(no_warnings):
enum_override_variations = ['language_list', 'LanguageEnum']
enum_override_variations = ['language_list', 'LanguageEnum', 'LanguageStrEnum']
if DJANGO_VERSION > '3':
enum_override_variations += ['LanguageChoices', 'LanguageChoices.choices']

Expand Down