Skip to content

Commit

Permalink
Avoid duplicate enum values for allow_null, allow_blank
Browse files Browse the repository at this point in the history
  • Loading branch information
intgr committed Oct 5, 2023
1 parent 6e4180b commit 94348c5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 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
22 changes: 21 additions & 1 deletion tests/test_plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from datetime import datetime
from enum import Enum

from rest_framework.fields import ChoiceField

if sys.version_info >= (3, 8):
from typing import TypedDict
else:
Expand All @@ -21,7 +23,7 @@
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,
force_instance, get_list_serializer, is_field, is_serializer, resolve_type_hint, build_choice_field,
)
from drf_spectacular.validation import validate_schema
from tests import generate_schema
Expand Down Expand Up @@ -358,3 +360,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(ChoiceField(['bluepill', 'redpill']))
assert schema['enum'] == ['bluepill', 'redpill']
assert schema['type'] == 'string'

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

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

0 comments on commit 94348c5

Please sign in to comment.