From 05e4b9021582da45c75d4b9fb56126ce115fd900 Mon Sep 17 00:00:00 2001 From: "T. Franzel" Date: Fri, 13 Nov 2020 01:34:04 +0100 Subject: [PATCH] add option to disable Null/Blank enum choice feature #185 --- drf_spectacular/hooks.py | 9 +++++---- drf_spectacular/settings.py | 2 ++ tests/test_postprocessing.py | 10 ++++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/drf_spectacular/hooks.py b/drf_spectacular/hooks.py index f477b219..cc4f09e2 100644 --- a/drf_spectacular/hooks.py +++ b/drf_spectacular/hooks.py @@ -115,10 +115,11 @@ def create_enum_component(name, schema): components = [ create_enum_component(enum_name, schema=enum_schema) ] - if '' in prop_enum_original_list: - components.append(create_enum_component('BlankEnum', schema={'enum': ['']})) - if None in prop_enum_original_list: - components.append(create_enum_component('NullEnum', schema={'enum': [None]})) + if spectacular_settings.ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE: + if '' in prop_enum_original_list: + components.append(create_enum_component('BlankEnum', schema={'enum': ['']})) + if None in prop_enum_original_list: + components.append(create_enum_component('NullEnum', schema={'enum': [None]})) if len(components) == 1: prop_schema.update(components[0].ref) diff --git a/drf_spectacular/settings.py b/drf_spectacular/settings.py index 119c094d..0fb98589 100644 --- a/drf_spectacular/settings.py +++ b/drf_spectacular/settings.py @@ -60,6 +60,8 @@ # enum name overrides. dict with keys "YourEnum" and their choice values "field.choices" 'ENUM_NAME_OVERRIDES': {}, + # Adds "blank" and "null" enum choices where appropriate. disable on client generation issues + 'ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE': True, # function that returns a list of all classes that should be excluded from doc string extraction 'GET_LIB_DOC_EXCLUDES': 'drf_spectacular.plumbing.get_lib_doc_excludes', diff --git a/tests/test_postprocessing.py b/tests/test_postprocessing.py index cadcabae..eb2ec0cd 100644 --- a/tests/test_postprocessing.py +++ b/tests/test_postprocessing.py @@ -55,6 +55,16 @@ def test_postprocessing(no_warnings): assert_schema(schema, 'tests/test_postprocessing.yml') +@mock.patch( + 'drf_spectacular.settings.spectacular_settings.ENUM_ADD_EXPLICIT_BLANK_NULL_CHOICE', False +) +def test_no_blank_and_null_in_enum_choices(no_warnings): + schema = generate_schema('a', AViewset) + assert 'NullEnum' not in schema['components']['schemas'] + assert 'BlankEnum' not in schema['components']['schemas'] + assert 'oneOf' not in schema['components']['schemas']['B']['properties']['language'] + + @mock.patch('drf_spectacular.settings.spectacular_settings.ENUM_NAME_OVERRIDES', { 'LanguageEnum': 'tests.test_postprocessing.language_choices' })