Skip to content

Commit 6aeea13

Browse files
committed
Rough implementation of compat middleware
1 parent ff68a33 commit 6aeea13

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

graphene/types/tests/test_enum.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from textwrap import dedent
2+
from graphql import OperationType
23

4+
from graphene.utils.str_converters import to_snake_case
35
from ..argument import Argument
6+
from ..definitions import GrapheneEnumType
47
from ..enum import Enum, PyEnum
58
from ..field import Field
69
from ..inputfield import InputField
@@ -393,3 +396,75 @@ class MyMutations(ObjectType):
393396
assert my_fav_color == Color.RED
394397

395398
assert results.data["setFavColor"]["favColor"] == Color.RED.name
399+
400+
401+
def get_underlying_type(_type):
402+
while hasattr(_type, "of_type"):
403+
_type = _type.of_type
404+
return _type
405+
406+
407+
def test_enum_mutation_compat():
408+
from enum import Enum as PyEnum
409+
410+
class Color(PyEnum):
411+
RED = 1
412+
GREEN = 2
413+
BLUE = 3
414+
415+
GColor = Enum.from_enum(Color)
416+
417+
my_fav_color = None
418+
419+
class Query(ObjectType):
420+
fav_color = GColor(required=True)
421+
422+
def resolve_fav_color(_, info):
423+
return my_fav_color
424+
425+
class SetFavColor(Mutation):
426+
class Arguments:
427+
fav_color = Argument(GColor, required=True)
428+
429+
Output = Query
430+
431+
def mutate(self, info, fav_color):
432+
nonlocal my_fav_color
433+
my_fav_color = fav_color
434+
return Query()
435+
436+
class MyMutations(ObjectType):
437+
set_fav_color = SetFavColor.Field()
438+
439+
def enum_compat_middleware(next, root, info, **args):
440+
operation = info.operation.operation
441+
if operation == OperationType.MUTATION:
442+
input_arguments = info.parent_type.fields[info.field_name].args
443+
for arg_name, arg in input_arguments.items():
444+
_type = get_underlying_type(arg.type)
445+
if isinstance(_type, GrapheneEnumType):
446+
# Convert inputs to value
447+
arg_name = to_snake_case(arg_name)
448+
input_value = args.get(arg_name, None)
449+
if input_value and isinstance(
450+
input_value, _type.graphene_type._meta.enum
451+
):
452+
args[arg_name] = args[arg_name].value
453+
454+
return next(root, info, **args)
455+
456+
schema = Schema(query=Query, mutation=MyMutations)
457+
458+
results = schema.execute(
459+
"""mutation {
460+
setFavColor(favColor: RED) {
461+
favColor
462+
}
463+
}""",
464+
middleware=[enum_compat_middleware],
465+
)
466+
assert not results.errors
467+
468+
assert my_fav_color == Color.RED.value
469+
470+
assert results.data["setFavColor"]["favColor"] == Color.RED.name

0 commit comments

Comments
 (0)