1
1
from graphql .type import GraphQLInputObjectField
2
2
3
3
import graphene
4
- from graphene import relay
4
+ from graphene import relay , with_context
5
5
from graphene .core .schema import Schema
6
6
7
7
my_id = 0
8
+ my_id_context = 0
8
9
9
10
10
11
class Query (graphene .ObjectType ):
@@ -25,8 +26,24 @@ def mutate_and_get_payload(cls, input, info):
25
26
return ChangeNumber (result = my_id )
26
27
27
28
29
+ class ChangeNumberContext (relay .ClientIDMutation ):
30
+ '''Result mutation'''
31
+ class Input :
32
+ to = graphene .Int ()
33
+
34
+ result = graphene .String ()
35
+
36
+ @classmethod
37
+ @with_context
38
+ def mutate_and_get_payload (cls , input , context , info ):
39
+ global my_id_context
40
+ my_id_context = input .get ('to' , my_id_context + context )
41
+ return ChangeNumber (result = my_id_context )
42
+
43
+
28
44
class MyResultMutation (graphene .ObjectType ):
29
45
change_number = graphene .Field (ChangeNumber )
46
+ change_number_context = graphene .Field (ChangeNumberContext )
30
47
31
48
32
49
schema = Schema (query = Query , mutation = MyResultMutation )
@@ -79,3 +96,39 @@ def test_execute_mutations():
79
96
result = schema .execute (query , root_value = object ())
80
97
assert not result .errors
81
98
assert result .data == expected
99
+
100
+
101
+ def test_context_mutations ():
102
+ query = '''
103
+ mutation M{
104
+ first: changeNumberContext(input: {clientMutationId: "mutation1"}) {
105
+ clientMutationId
106
+ result
107
+ },
108
+ second: changeNumberContext(input: {clientMutationId: "mutation2"}) {
109
+ clientMutationId
110
+ result
111
+ }
112
+ third: changeNumberContext(input: {clientMutationId: "mutation3", to: 5}) {
113
+ result
114
+ clientMutationId
115
+ }
116
+ }
117
+ '''
118
+ expected = {
119
+ 'first' : {
120
+ 'clientMutationId' : 'mutation1' ,
121
+ 'result' : '-1' ,
122
+ },
123
+ 'second' : {
124
+ 'clientMutationId' : 'mutation2' ,
125
+ 'result' : '-2' ,
126
+ },
127
+ 'third' : {
128
+ 'clientMutationId' : 'mutation3' ,
129
+ 'result' : '5' ,
130
+ }
131
+ }
132
+ result = schema .execute (query , root_value = object (), context_value = - 1 )
133
+ assert not result .errors
134
+ assert result .data == expected
0 commit comments