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

Avoid ChoiceField duplicate enum values for allow_null, allow_blank #1085

Merged
merged 4 commits into from
Oct 22, 2023
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
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