From dc5799e109d2e2cd7eed59282fe35a477942a56b Mon Sep 17 00:00:00 2001 From: Jason Kraus Date: Thu, 30 May 2019 13:36:48 -0700 Subject: [PATCH] detect if value is a string for enum conversion else use help text to generate name --- graphene_django/converter.py | 9 ++++++--- graphene_django/tests/test_converter.py | 19 +++++++++++++++++++ graphene_django/tests/test_types.py | 12 ++++++------ 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/graphene_django/converter.py b/graphene_django/converter.py index c40313d..8d39c6b 100644 --- a/graphene_django/converter.py +++ b/graphene_django/converter.py @@ -38,16 +38,19 @@ def convert_choice_name(name): def get_choices(choices): - converted_names = [] + converted_names = set() for value, help_text in choices: if isinstance(help_text, (tuple, list)): for choice in get_choices(help_text): yield choice else: - name = convert_choice_name(value) + if isinstance(value, str): + name = convert_choice_name(value) + else: + name = convert_choice_name(help_text) while name in converted_names: name += "_" + str(len(converted_names)) - converted_names.append(name) + converted_names.add(name) description = help_text yield name, value, description diff --git a/graphene_django/tests/test_converter.py b/graphene_django/tests/test_converter.py index bb176b3..c6ee128 100644 --- a/graphene_django/tests/test_converter.py +++ b/graphene_django/tests/test_converter.py @@ -177,6 +177,25 @@ def test_field_with_choices_gettext(): convert_django_field_with_choices(field) +def test_field_with_integer_choices(): + field = models.IntegerField( + help_text="Language", choices=((1, "Spanish"), (2, "English")) + ) + + class TranslatedChoicesModel(models.Model): + language = field + + class Meta: + app_label = "test" + + graphene_type = convert_django_field_with_choices(field) + #assert False, str(graphene_type._meta.enum.__members__) + assert graphene_type._meta.enum.__members__["SPANISH"].value == 1 + assert graphene_type._meta.enum.__members__["SPANISH"].description == "Spanish" + assert graphene_type._meta.enum.__members__["ENGLISH"].value == 2 + assert graphene_type._meta.enum.__members__["ENGLISH"].description == "English" + + def test_field_with_choices_collision(): field = models.CharField( help_text="Timezone", diff --git a/graphene_django/tests/test_types.py b/graphene_django/tests/test_types.py index 8a8643b..16e187a 100644 --- a/graphene_django/tests/test_types.py +++ b/graphene_django/tests/test_types.py @@ -136,8 +136,8 @@ type ArticleEdge { } enum ArticleImportance { - A_1 - A_2 + VERY_IMPORTANT + NOT_AS_IMPORTANT } enum ArticleLang { @@ -172,13 +172,13 @@ type Reporter { } enum ReporterAChoice { - A_1 - A_2 + THIS + THAT } enum ReporterReporterType { - A_1 - A_2 + REGULAR + CNN_REPORTER } type RootQuery {