Skip to content

Commit

Permalink
bugfix/generalize Union hint extraction #284
Browse files Browse the repository at this point in the history
  • Loading branch information
tfranzel committed Feb 7, 2021
1 parent 2eb7fe2 commit e59c332
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
14 changes: 8 additions & 6 deletions drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -835,12 +835,14 @@ def resolve_type_hint(hint):
k: resolve_type_hint(v) for k, v in typing.get_type_hints(hint).items()
}
)
elif origin is typing.Union and len(args) == 2 and isinstance(None, args[1]):
# Optional[*] is resolved to Union[*, None]
schema = resolve_type_hint(args[0])
schema['nullable'] = True
return schema
elif origin is typing.Union:
return {'oneOf': [resolve_type_hint(arg) for arg in args]}
type_args = [arg for arg in args if arg is not type(None)] # noqa: E721
if len(type_args) > 1:
schema = {'oneOf': [resolve_type_hint(arg) for arg in type_args]}
else:
schema = resolve_type_hint(type_args[0])
if type(None) in args:
schema['nullable'] = True
return schema
else:
raise UnableToProceedError()
6 changes: 6 additions & 0 deletions tests/test_plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ def test_detype_patterns_with_module_includes(no_warnings):
), (
typing.Union[int, str],
{'oneOf': [{'type': 'integer'}, {'type': 'string'}]}
), (
typing.Union[int, str, None],
{'oneOf': [{'type': 'integer'}, {'type': 'string'}], 'nullable': True}
), (
typing.Optional[typing.Union[int, str]],
{'oneOf': [{'type': 'integer'}, {'type': 'string'}], 'nullable': True}
)
]

Expand Down

0 comments on commit e59c332

Please sign in to comment.