Python graphene.Mutation() Examples
The following are 14
code examples of graphene.Mutation().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
graphene
, or try the search function
.
Example #1
Source File: dauphin_registry.py From dagster with Apache License 2.0 | 5 votes |
def create_schema(self): return DauphinSchema( query=self.getType('Query'), mutation=self.getTypeOrNull('Mutation'), subscription=self.getTypeOrNull('Subscription'), types=self.getAllImplementationTypes(), registry=self, )
Example #2
Source File: graphql_mutation_from_summary.py From graphql-over-kafka with MIT License | 5 votes |
def graphql_mutation_from_summary(summary): """ This function returns a graphql mutation corresponding to the provided summary. """ # get the name of the mutation from the summary mutation_name = summary['name'] # print(summary) # the treat the "type" string as a gra input_name = mutation_name + "Input" input_fields = build_native_type_dictionary(summary['inputs'], name=input_name, respect_required=True) # the inputs for the mutation are defined by a class record inputs = type('Input', (object,), input_fields) # the outputs for the mutation are attributes to the class record output_name = mutation_name + "Output" outputs = build_native_type_dictionary(summary['outputs'], name=output_name) # a no-op in order to satisfy the introspection query mutate = classmethod(lambda *_, **__ : 'hello') # create the appropriate mutation class record mutation = type(mutation_name, (graphene.Mutation,), { 'Input': inputs, 'mutate': mutate, **outputs }) # return the newly created mutation record return mutation
Example #3
Source File: example.py From DjangoChannelsGraphqlWs with MIT License | 4 votes |
def mutate(self, info, chatroom, text): """Mutation "resolver" - store and broadcast a message.""" # Use the username from the connection scope if authorized. username = ( info.context.user.username if info.context.user.is_authenticated else "Anonymous" ) # Store a message. chats[chatroom].append({"chatroom": chatroom, "text": text, "sender": username}) # Notify subscribers. OnNewChatMessage.new_chat_message(chatroom=chatroom, text=text, sender=username) return SendChatMessage(ok=True)
Example #4
Source File: test_confirm_subscriptions.py From DjangoChannelsGraphqlWs with MIT License | 4 votes |
def test_confirmation_enabled(gql): """Test subscription confirmation message received when enabled.""" print("Establish WebSocket GraphQL connections with subscription confirmation.") client = gql( mutation=Mutation, subscription=Subscription, consumer_attrs={"strict_ordering": True, "confirm_subscriptions": True}, ) await client.connect_and_init() print("Subscribe & check there is a subscription confirmation message.") sub_op_id = await client.send( msg_type="start", payload={ "query": "subscription op_name { on_trigger { is_ok } }", "operationName": "op_name", }, ) resp = await client.receive(assert_id=sub_op_id, assert_type="data") assert resp == {"data": None} print("Trigger the subscription.") mut_op_id = await client.send( msg_type="start", payload={ "query": """mutation op_name { trigger { is_ok } }""", "operationName": "op_name", }, ) await client.receive(assert_id=mut_op_id, assert_type="data") await client.receive(assert_id=mut_op_id, assert_type="complete") print("Check that subscription notification received.") resp = await client.receive(assert_id=sub_op_id, assert_type="data") assert resp["data"]["on_trigger"]["is_ok"] is True await client.assert_no_messages( "Unexpected message received at the end of the test!" ) await client.finalize()
Example #5
Source File: test_confirm_subscriptions.py From DjangoChannelsGraphqlWs with MIT License | 4 votes |
def test_confirmation_disabled(gql): """Test subscription confirmation message absent when disabled.""" print("Establish WebSocket GraphQL connections w/o a subscription confirmation.") client = gql( mutation=Mutation, subscription=Subscription, consumer_attrs={"strict_ordering": True, "confirm_subscriptions": False}, ) await client.connect_and_init() print("Subscribe & check there is no subscription confirmation message.") sub_op_id = await client.send( msg_type="start", payload={ "query": "subscription op_name { on_trigger { is_ok } }", "operationName": "op_name", }, ) await client.assert_no_messages("Subscribe responded with a message!") print("Trigger the subscription.") mut_op_id = await client.send( msg_type="start", payload={ "query": """mutation op_name { trigger { is_ok } }""", "operationName": "op_name", }, ) await client.receive(assert_id=mut_op_id, assert_type="data") await client.receive(assert_id=mut_op_id, assert_type="complete") print("Check that subscription notification received.") resp = await client.receive(assert_id=sub_op_id, assert_type="data") assert resp == {"data": {"on_trigger": {"is_ok": True}}} await client.assert_no_messages( "Unexpected message received at the end of the test!" ) await client.finalize()
Example #6
Source File: test_basic.py From DjangoChannelsGraphqlWs with MIT License | 4 votes |
def test_keepalive(gql): """Test that server sends keepalive messages.""" print("Establish & initialize WebSocket GraphQL connection.") client = gql( query=Query, mutation=Mutation, subscription=Subscription, consumer_attrs={"strict_ordering": True, "send_keepalive_every": 0.05}, ) await client.connect_and_init() async def receive_keep_alive(): response = await client.transport.receive() assert response["type"] == "ka", "Non keep alive response received!" await receive_keep_alive() print("Receive several keepalive messages.") for _ in range(3): await receive_keep_alive() print("Send connection termination message.") await client.send(msg_id=None, msg_type="connection_terminate") print("Disconnect and wait the application to finish gracefully.") await client.finalize() # ---------------------------------------------------------------------- GRAPHQL BACKEND
Example #7
Source File: test_middleware.py From DjangoChannelsGraphqlWs with MIT License | 4 votes |
def test_middleware_called_in_query(gql): """Check that middleware called during query request.""" middleware_called = False def middleware(next_middleware, root, info, *args, **kwds): nonlocal middleware_called middleware_called = True return next_middleware(root, info, *args, **kwds) print("Initialize WebSocket GraphQL connection with middleware enabled.") client = gql( query=Query, mutation=Mutation, subscription=Subscription, consumer_attrs={"strict_ordering": True, "middleware": [middleware]}, ) await client.connect_and_init() print("Make simple query and assert that middleware function called.") msg_id = await client.send(msg_type="start", payload={"query": "query { ok }"}) await client.receive(assert_id=msg_id, assert_type="data") await client.receive(assert_id=msg_id, assert_type="complete") assert middleware_called, "Middleware is not called!" print("Disconnect and wait the application to finish gracefully.") await client.finalize()
Example #8
Source File: test_middleware.py From DjangoChannelsGraphqlWs with MIT License | 4 votes |
def test_middleware_called_in_subscription(gql): """Check that middleware called during subscription processing. Middleware expected to be called two times: during subscribing to the subscription and during a notification. """ middleware_call_counter = 0 def middleware(next_middleware, root, info, *args, **kwds): nonlocal middleware_call_counter middleware_call_counter += 1 return next_middleware(root, info, *args, **kwds) print("Initialize WebSocket GraphQL connection with middleware enabled.") client = gql( query=Query, mutation=Mutation, subscription=Subscription, consumer_attrs={"strict_ordering": True, "middleware": [middleware]}, ) await client.connect_and_init() print("Subscribe to GraphQL subscription.") sub_id = await client.send( msg_type="start", payload={"query": "subscription { on_trigger{ ok } }"} ) await client.assert_no_messages() assert ( middleware_call_counter == 1 ), "Middleware is not called during subscribing to the subscription!" print("Manually trigger the subscription.") await OnTrigger.broadcast() # Receive subscription notification to guarantee that the # subscription processing has finished. await client.receive(assert_id=sub_id, assert_type="data") assert ( middleware_call_counter == 2 ), "Middleware is not called two times for subscription!" print("Disconnect and wait the application to finish gracefully.") await client.finalize()
Example #9
Source File: test_middleware.py From DjangoChannelsGraphqlWs with MIT License | 4 votes |
def test_middleware_invocation_order(gql): """Check that several middleware called in a proper order.""" middleware_invocation_log = [] def middleware1(next_middleware, root, info, *args, **kwds): middleware_invocation_log.append(1) return next_middleware(root, info, *args, **kwds) def middleware2(next_middleware, root, info, *args, **kwds): middleware_invocation_log.append(2) return next_middleware(root, info, *args, **kwds) print("Initialize WebSocket GraphQL connection with middleware enabled.") client = gql( query=Query, mutation=Mutation, subscription=Subscription, consumer_attrs={ "strict_ordering": True, "middleware": [middleware2, middleware1], }, ) await client.connect_and_init() print("Make simple query and assert that middleware function called.") msg_id = await client.send(msg_type="start", payload={"query": "query { ok }"}) await client.receive(assert_id=msg_id, assert_type="data") await client.receive(assert_id=msg_id, assert_type="complete") assert middleware_invocation_log == [1, 2], "Middleware invocation order is wrong!" print("Disconnect and wait the application to finish gracefully.") await client.finalize() # ---------------------------------------------------------------------- GRAPHQL BACKEND # Mute Pytest for the Graphene DSL for the GraphQL setup. # pylint: disable=arguments-differ,no-self-use
Example #10
Source File: test_concurrent.py From DjangoChannelsGraphqlWs with MIT License | 4 votes |
def test_concurrent_queries(gql): """Check a single hanging operation does not block other ones.""" print("Establish & initialize WebSocket GraphQL connection.") client = gql(query=Query, mutation=Mutation) await client.connect_and_init() print("Invoke a long operation which waits for the wakeup even.") long_op_id = await client.send( msg_type="start", payload={ "query": "mutation op_name { long_op { is_ok } }", "variables": {}, "operationName": "op_name", }, ) await client.assert_no_messages() print("Make several fast operations to check they are not blocked by the long one.") for _ in range(3): fast_op_id = await client.send( msg_type="start", payload={ "query": "query op_name { fast_op_sync }", "variables": {}, "operationName": "op_name", }, ) resp = await client.receive(assert_id=fast_op_id, assert_type="data") assert resp["data"] == {"fast_op_sync": True} await client.receive(assert_id=fast_op_id, assert_type="complete") print("Trigger the wakeup event to let long operation finish.") WAKEUP.set() resp = await client.receive(assert_id=long_op_id, assert_type="data") assert "errors" not in resp assert resp["data"] == {"long_op": {"is_ok": True}} await client.receive(assert_id=long_op_id, assert_type="complete") print("Disconnect and wait the application to finish gracefully.") await client.assert_no_messages( "Unexpected message received at the end of the test!" ) await client.finalize() # NOTE: Large `requests_number` values may lead to errors in `select`.
Example #11
Source File: dauphin_registry.py From dagster with Apache License 2.0 | 4 votes |
def __init__(self): self._typeMap = {} self.Field = create_registry_field(self) self.Argument = create_registry_argument(self) self.List = create_registry_list(self) self.NonNull = create_registry_nonnull(self) registering_metaclass = create_registering_metaclass(self) self.Union = create_union(registering_metaclass, self) self.Enum = create_enum(registering_metaclass) self.Mutation = graphene.Mutation # Not looping over GRAPHENE_TYPES in order to not fool lint self.ObjectType = create_registering_class(graphene.ObjectType, registering_metaclass) self.InputObjectType = create_registering_class( graphene.InputObjectType, registering_metaclass ) self.Interface = create_registering_class(graphene.Interface, registering_metaclass) self.Scalar = create_registering_class(graphene.Scalar, registering_metaclass) # Not looping over GRAPHENE_BUILTINS in order to not fool lint self.String = graphene.String self.addType(graphene.String) self.Int = graphene.Int self.addType(graphene.Int) self.Float = graphene.Float self.addType(graphene.Float) self.Boolean = graphene.Boolean self.addType(graphene.Boolean) self.ID = graphene.ID self.addType(graphene.ID) self.GenericScalar = GenericScalar self.addType(GenericScalar)
Example #12
Source File: test_mutation.py From graphene-mongo with MIT License | 4 votes |
def test_should_create(fixtures): class CreateArticle(graphene.Mutation): class Arguments: headline = graphene.String() article = graphene.Field(ArticleNode) def mutate(self, info, headline): article = Article(headline=headline) article.save() return CreateArticle(article=article) class Query(graphene.ObjectType): node = Node.Field() class Mutation(graphene.ObjectType): create_article = CreateArticle.Field() query = """ mutation ArticleCreator { createArticle( headline: "My Article" ) { article { headline } } } """ expected = {"createArticle": {"article": {"headline": "My Article"}}} schema = graphene.Schema(query=Query, mutation=Mutation) result = schema.execute(query) assert not result.errors assert result.data == expected
Example #13
Source File: test_mutation.py From graphene-mongo with MIT License | 4 votes |
def test_should_update(fixtures): class UpdateEditor(graphene.Mutation): class Arguments: id = graphene.ID() first_name = graphene.String() editor = graphene.Field(EditorNode) def mutate(self, info, id, first_name): editor = Editor.objects.get(id=id) editor.first_name = first_name editor.save() return UpdateEditor(editor=editor) class Query(graphene.ObjectType): node = Node.Field() class Mutation(graphene.ObjectType): update_editor = UpdateEditor.Field() query = """ mutation EditorUpdater { updateEditor( id: "1" firstName: "Tony" ) { editor { firstName } } } """ expected = {"updateEditor": {"editor": {"firstName": "Tony"}}} schema = graphene.Schema(query=Query, mutation=Mutation) result = schema.execute(query) # print(result.data) assert not result.errors assert result.data == expected
Example #14
Source File: actions.py From wagtail-graphql with MIT License | 4 votes |
def _add_form(cls: Type[AbstractForm], node: str, dict_params: dict) -> Type[graphene.Mutation]: if node in registry.forms: # pragma: no cover return registry.forms[node] registry.page_prefetch_fields.add(cls.__name__.lower()) dict_params['Meta'].interfaces += (Page,) dict_params['form_fields'] = graphene.List(FormField) def form_fields(self, _info): return list(FormField(name=field_.clean_name, field_type=field_.field_type, label=field_.label, required=field_.required, help_text=field_.help_text, choices=field_.choices, default_value=field_.default_value) for field_ in self.form_fields.all()) dict_params['resolve_form_fields'] = form_fields registry.pages[cls] = type(node, (DjangoObjectType,), dict_params) args = type("Arguments", (), {'values': GenericScalar(), "url": graphene.String(required=True)}) _node = node def mutate(_self, info, url, values): url_prefix = url_prefix_for_site(info) query = wagtailPage.objects.filter(url_path=url_prefix + url.rstrip('/') + '/') instance = with_page_permissions( info.context, query.specific() ).live().first() user = info.context.user # convert camelcase to dashes values = {camel_case_to_spaces(k).replace(' ', '-'): v for k, v in values.items()} form = instance.get_form(values, None, page=instance, user=user) if form.is_valid(): # form_submission instance.process_form_submission(form) return registry.forms[_node](result="OK") else: return registry.forms[_node](result="FAIL", errors=[FormError(*err) for err in form.errors.items()]) dict_params = { "Arguments": args, "mutate": mutate, "result": graphene.String(), "errors": graphene.List(FormError), } tp = type(node + "Mutation", (graphene.Mutation,), dict_params) # type: Type[graphene.Mutation] registry.forms[node] = tp return tp