Skip to content

Commit 0cef6fb

Browse files
committed
Improved Enum serialization tests
1 parent 14f14d3 commit 0cef6fb

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

graphql/pyutils/compat.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
try:
2828
from enum import Enum
2929
except ImportError:
30-
from .enum import Enum
30+
from .enum import Enum # type: ignore
3131

3232
if False:
3333
from typing import Callable

graphql/type/definition.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -516,7 +516,7 @@ def get_value(self, name):
516516
return self._name_lookup.get(name)
517517

518518
def serialize(self, value):
519-
# type: (str) -> Optional[str]
519+
# type: (Union[str, PyEnum]) -> Optional[str]
520520
if isinstance(value, PyEnum):
521521
# We handle PyEnum values
522522
value = value.value

graphql/type/tests/test_serialization.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import pytest
22

3-
from graphql.type import GraphQLBoolean, GraphQLFloat, GraphQLInt, GraphQLString
3+
from ..scalars import GraphQLBoolean, GraphQLFloat, GraphQLInt, GraphQLString
4+
from ..definition import GraphQLEnumType, GraphQLEnumValue
5+
from ...pyutils.compat import Enum
46

57

68
def test_serializes_output_int():
@@ -56,3 +58,26 @@ def test_serializes_output_boolean():
5658
assert GraphQLBoolean.serialize(0) is False
5759
assert GraphQLBoolean.serialize(True) is True
5860
assert GraphQLBoolean.serialize(False) is False
61+
62+
63+
def test_serializes_enum():
64+
class Color(Enum):
65+
RED = "RED"
66+
GREEN = "GREEN"
67+
BLUE = "BLUE"
68+
EXTRA = "EXTRA"
69+
70+
enum_type = GraphQLEnumType(
71+
"Color",
72+
values={
73+
"RED": GraphQLEnumValue("RED"),
74+
"GREEN": GraphQLEnumValue("GREEN"),
75+
"BLUE": GraphQLEnumValue("BLUE"),
76+
},
77+
)
78+
assert enum_type.serialize("RED") == "RED"
79+
assert enum_type.serialize("NON_EXISTING") is None
80+
assert enum_type.serialize(Color.RED) == "RED"
81+
assert enum_type.serialize(Color.RED.value) == "RED"
82+
assert enum_type.serialize(Color.EXTRA) is None
83+
assert enum_type.serialize(Color.EXTRA.value) is None

0 commit comments

Comments
 (0)