Skip to content

Commit

Permalink
Avoid ChoiceField duplicate enum values for allow_null, allow_blank (#…
Browse files Browse the repository at this point in the history
…1085)

* Avoid duplicate enum values for allow_null, allow_blank

* imports/code style

* Chop down line length

* isort
  • Loading branch information
intgr authored Oct 22, 2023
1 parent c68d3b2 commit 6e48a70
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
4 changes: 2 additions & 2 deletions drf_spectacular/plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,9 +410,9 @@ def build_choice_field(field):
else:
type = None

if field.allow_blank:
if field.allow_blank and '' not in choices:
choices.append('')
if field.allow_null:
if field.allow_null and None not in choices:
choices.append(None)

schema = {
Expand Down
23 changes: 21 additions & 2 deletions tests/test_plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@

from drf_spectacular.openapi import AutoSchema
from drf_spectacular.plumbing import (
analyze_named_regex_pattern, build_basic_type, detype_pattern, follow_field_source,
force_instance, get_list_serializer, is_field, is_serializer, resolve_type_hint,
analyze_named_regex_pattern, build_basic_type, build_choice_field, detype_pattern,
follow_field_source, force_instance, get_list_serializer, is_field, is_serializer,
resolve_type_hint,
)
from drf_spectacular.validation import validate_schema
from tests import generate_schema
Expand Down Expand Up @@ -358,3 +359,21 @@ def test_analyze_named_regex_pattern(no_warnings, pattern, output):
def test_unknown_basic_type(capsys):
build_basic_type(object)
assert 'could not resolve type for "<class \'object\'>' in capsys.readouterr().err


def test_choicefield_choices_enum():
schema = build_choice_field(serializers.ChoiceField(['bluepill', 'redpill']))
assert schema['enum'] == ['bluepill', 'redpill']
assert schema['type'] == 'string'

schema = build_choice_field(serializers.ChoiceField(
['bluepill', 'redpill'], allow_null=True, allow_blank=True
))
assert schema['enum'] == ['bluepill', 'redpill', '', None]
assert schema['type'] == 'string'

schema = build_choice_field(serializers.ChoiceField(
choices=['bluepill', 'redpill', '', None], allow_null=True, allow_blank=True
))
assert schema['enum'] == ['bluepill', 'redpill', '', None]
assert 'type' not in schema

0 comments on commit 6e48a70

Please sign in to comment.