Skip to content

Commit

Permalink
feat: add graphene_enum_values function & test it
Browse files Browse the repository at this point in the history
might be useful because Graphene 3 has changed from using enum values to
enums, for example:

```python
class TestEnum(graphene.Enum):
  FIRST = 'first'
  SECOND = 'second'
```

would've been serialized previously using the enum values, i.e.
'first' and 'second'. But with Graphene 3 they are serialized as
'TestEnum.FIRST' and 'TestEnum.SECOND'. This breaks functionality as
parts of the codebase are expecting the enum values as per Graphene 2.

Related https://github.com/graphql-python/graphene issues & PRs:
 - "Improve enum compatibility" PR:
   - graphql-python/graphene#1153
 - "graphene3: enum doesn't resolve to value" issue:
   - graphql-python/graphene#1277
 - "I would like my enum input values to be the enum instance instead
   of the enum values" issue:
   - graphql-python/graphene#1151

refs KK-1108
  • Loading branch information
karisal-anders committed Jul 11, 2024
1 parent 32f269d commit 6229ae4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
32 changes: 32 additions & 0 deletions common/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from enum import auto

import graphene
import pytest

from common.utils import graphene_enum_values


class TestGrapheneEnum(graphene.Enum):
FIRST_ENUM_NAME = "FIRST_ENUM_VALUE"
ENUM_NAME_1 = "ENUM_VALUE_1"
ENUM_NAME_2 = "ENUM_VALUE_2"
LAST_ENUM_NAME = "LAST_ENUM_VALUE"


class TestGrapheneEnumAuto(graphene.Enum):
_123 = auto()
test = auto()


@pytest.mark.parametrize(
"enum_class,expected_values",
[
(
TestGrapheneEnum,
["FIRST_ENUM_VALUE", "ENUM_VALUE_1", "ENUM_VALUE_2", "LAST_ENUM_VALUE"],
),
(TestGrapheneEnumAuto, [1, 2]),
],
)
def test_graphene_enum_values(enum_class, expected_values):
assert graphene_enum_values(enum_class) == expected_values
12 changes: 12 additions & 0 deletions common/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import binascii
from copy import deepcopy
from functools import wraps
from typing import Type

import graphene
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db import transaction
Expand Down Expand Up @@ -144,3 +146,13 @@ def strtobool(val):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))


def graphene_enum_values(enum_class: Type[graphene.Enum]) -> list:
"""
Get all values of an enumeration that is derived from graphene.Enum.
:param enum_class: The enumeration class, not an instance, but the class.
:return: A list of all values of the enumeration.
"""
return list(enum_class._meta.enum._value2member_map_.keys())

0 comments on commit 6229ae4

Please sign in to comment.