Skip to content

Commit

Permalink
be gracious on Enums that are not recognized by DRF #500
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Sep 20, 2021
1 parent 7eada19 commit eabccef
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
9 changes: 5 additions & 4 deletions drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -970,10 +970,11 @@ def resolve_type_hint(hint):
schema.update(build_basic_type(type(args[0])))
return schema
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])
}
schema = {'enum': [item.value for item in hint]}
mixin_base_types = [t for t in hint.__mro__ if is_basic_type(t)]
if mixin_base_types:
schema.update(build_basic_type(mixin_base_types[0]))
return schema
elif hasattr(typing, 'TypedDict') and isinstance(hint, typing._TypedDictMeta):
return build_object_type(
properties={
Expand Down
17 changes: 13 additions & 4 deletions tests/test_plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,13 @@ class LanguageEnum(str, Enum):
DE = 'de'


# Make sure we can deal with plain Enums that are not handled by DRF.
# The second base class makes this work for DRF.
class InvalidLanguageEnum(Enum):
EN = 'en'
DE = 'de'


TYPE_HINT_TEST_PARAMS = [
(
typing.Optional[int],
Expand Down Expand Up @@ -139,13 +146,15 @@ class LanguageEnum(str, Enum):
), (
typing.Optional[typing.Union[str, int]],
{'oneOf': [{'type': 'string'}, {'type': 'integer'}], 'nullable': True}
), (
LanguageEnum,
{'enum': ['en', 'de'], 'type': 'string'}
), (
InvalidLanguageEnum,
{'enum': ['en', 'de']}
)
]

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

0 comments on commit eabccef

Please sign in to comment.