Skip to content

Commit

Permalink
Improved Enum serialization tests
Browse files Browse the repository at this point in the history
  • Loading branch information
syrusakbary committed Jul 19, 2018
1 parent 14f14d3 commit 0cef6fb
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
2 changes: 1 addition & 1 deletion graphql/pyutils/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
try:
from enum import Enum
except ImportError:
from .enum import Enum
from .enum import Enum # type: ignore

if False:
from typing import Callable
Expand Down
2 changes: 1 addition & 1 deletion graphql/type/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ def get_value(self, name):
return self._name_lookup.get(name)

def serialize(self, value):
# type: (str) -> Optional[str]
# type: (Union[str, PyEnum]) -> Optional[str]
if isinstance(value, PyEnum):
# We handle PyEnum values
value = value.value
Expand Down
27 changes: 26 additions & 1 deletion graphql/type/tests/test_serialization.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import pytest

from graphql.type import GraphQLBoolean, GraphQLFloat, GraphQLInt, GraphQLString
from ..scalars import GraphQLBoolean, GraphQLFloat, GraphQLInt, GraphQLString
from ..definition import GraphQLEnumType, GraphQLEnumValue
from ...pyutils.compat import Enum


def test_serializes_output_int():
Expand Down Expand Up @@ -56,3 +58,26 @@ def test_serializes_output_boolean():
assert GraphQLBoolean.serialize(0) is False
assert GraphQLBoolean.serialize(True) is True
assert GraphQLBoolean.serialize(False) is False


def test_serializes_enum():
class Color(Enum):
RED = "RED"
GREEN = "GREEN"
BLUE = "BLUE"
EXTRA = "EXTRA"

enum_type = GraphQLEnumType(
"Color",
values={
"RED": GraphQLEnumValue("RED"),
"GREEN": GraphQLEnumValue("GREEN"),
"BLUE": GraphQLEnumValue("BLUE"),
},
)
assert enum_type.serialize("RED") == "RED"
assert enum_type.serialize("NON_EXISTING") is None
assert enum_type.serialize(Color.RED) == "RED"
assert enum_type.serialize(Color.RED.value) == "RED"
assert enum_type.serialize(Color.EXTRA) is None
assert enum_type.serialize(Color.EXTRA.value) is None

0 comments on commit 0cef6fb

Please sign in to comment.