def test_does_not_mutate_passed_field_definitions(): fields = { 'field1': GraphQLField(GraphQLString), 'field2': GraphQLField(GraphQLString, args={'id': GraphQLArgument(GraphQLString)}), } TestObject1 = GraphQLObjectType(name='Test1', fields=fields) TestObject2 = GraphQLObjectType(name='Test1', fields=fields) assert TestObject1.fields == TestObject2.fields assert fields == { 'field1': GraphQLField(GraphQLString), 'field2': GraphQLField(GraphQLString, args={'id': GraphQLArgument(GraphQLString)}), } input_fields = { 'field1': GraphQLInputObjectField(GraphQLString), 'field2': GraphQLInputObjectField(GraphQLString), } TestInputObject1 = GraphQLInputObjectType(name='Test1', fields=input_fields) TestInputObject2 = GraphQLInputObjectType(name='Test2', fields=input_fields) assert TestInputObject1.fields == TestInputObject2.fields assert input_fields == { 'field1': GraphQLInputObjectField(GraphQLString), 'field2': GraphQLInputObjectField(GraphQLString), }
def test_builds_a_schema_with_an_input_object(): AddressType = GraphQLInputObjectType( name='Address', description='An input address', fields=OrderedDict([ ('street', GraphQLInputObjectField( GraphQLNonNull(GraphQLString), description='What street is this address?')), ('city', GraphQLInputObjectField( GraphQLNonNull(GraphQLString), description='The city the address is within?')), ('country', GraphQLInputObjectField( GraphQLString, description='The country (blank will assume USA).', default_value='USA')), ])) schema = GraphQLSchema(query=GraphQLObjectType( name='HasInputObjectFields', fields={ 'geocode': GraphQLField(description='Get a geocode from an address', type=GraphQLString, args={ 'address': GraphQLArgument( description='The address to lookup', type=AddressType) }) })) _test_schema(schema)
def test_includes_nested_input_objects_in_the_map(): NestedInputObject = GraphQLInputObjectType( name='NestedInputObject', fields={'value': GraphQLInputObjectField(GraphQLString)}) SomeInputObject = GraphQLInputObjectType( name='SomeInputObject', fields={'nested': GraphQLInputObjectField(NestedInputObject)}) SomeMutation = GraphQLObjectType( name='SomeMutation', fields={ 'mutateSomething': GraphQLField(type=BlogArticle, args={'input': GraphQLArgument(SomeInputObject)}) }) SomeSubscription = GraphQLObjectType( name='SomeSubscription', fields={ 'subscribeToSomething': GraphQLField(type=BlogArticle, args={'input': GraphQLArgument(SomeInputObject)}) }) schema = GraphQLSchema(query=BlogQuery, mutation=SomeMutation, subscription=SomeSubscription) assert schema.get_type_map()['NestedInputObject'] is NestedInputObject
def test_includes_nested_input_objects_in_the_map(): NestedInputObject = GraphQLInputObjectType( name="NestedInputObject", fields={"value": GraphQLInputObjectField(GraphQLString)}, ) SomeInputObject = GraphQLInputObjectType( name="SomeInputObject", fields={"nested": GraphQLInputObjectField(NestedInputObject)}, ) SomeMutation = GraphQLObjectType( name="SomeMutation", fields={ "mutateSomething": GraphQLField(type=BlogArticle, args={"input": GraphQLArgument(SomeInputObject)}) }, ) SomeSubscription = GraphQLObjectType( name="SomeSubscription", fields={ "subscribeToSomething": GraphQLField(type=BlogArticle, args={"input": GraphQLArgument(SomeInputObject)}) }, ) schema = GraphQLSchema(query=BlogQuery, mutation=SomeMutation, subscription=SomeSubscription) assert schema.get_type_map()["NestedInputObject"] is NestedInputObject
def test_does_not_mutate_passed_field_definitions(): fields = { "field1": GraphQLField(GraphQLString), "field2": GraphQLField( GraphQLString, args={"id": GraphQLArgument(GraphQLString)} ), } TestObject1 = GraphQLObjectType(name="Test1", fields=fields) TestObject2 = GraphQLObjectType(name="Test1", fields=fields) assert TestObject1.fields == TestObject2.fields assert fields == { "field1": GraphQLField(GraphQLString), "field2": GraphQLField( GraphQLString, args={"id": GraphQLArgument(GraphQLString)} ), } input_fields = { "field1": GraphQLInputObjectField(GraphQLString), "field2": GraphQLInputObjectField(GraphQLString), } TestInputObject1 = GraphQLInputObjectType(name="Test1", fields=input_fields) TestInputObject2 = GraphQLInputObjectType(name="Test2", fields=input_fields) assert TestInputObject1.fields == TestInputObject2.fields assert input_fields == { "field1": GraphQLInputObjectField(GraphQLString), "field2": GraphQLInputObjectField(GraphQLString), }
def test_builds_a_schema_with_field_arguments_with_default_values(): GeoType = GraphQLInputObjectType( name="Geo", fields=OrderedDict([ ("lat", GraphQLInputObjectField(GraphQLFloat)), ("lon", GraphQLInputObjectField(GraphQLFloat)), ]), ) schema = GraphQLSchema(query=GraphQLObjectType( name="ArgFields", fields=OrderedDict([ ( "defaultInt", GraphQLField( GraphQLString, args={ "intArg": GraphQLArgument(GraphQLInt, default_value=10) }, ), ), ('defaultNullInt', GraphQLField(GraphQLString, args={ 'intArg': GraphQLArgument(GraphQLInt, default_value=None) })), ( "defaultList", GraphQLField( GraphQLString, args={ "listArg": GraphQLArgument(GraphQLList(GraphQLInt), default_value=[1, 2, 3]) }, ), ), ( "defaultObject", GraphQLField( GraphQLString, args={ "objArg": GraphQLArgument( GeoType, default_value={ "lat": 37.485, "lon": -122.148 }, ) }, ), ), ]), )) _test_schema(schema)
def test_maps_argument_out_names_well_with_input(): # type: () -> None def resolver(source, info, **args): # type: (Optional[str], ResolveInfo, **Any) -> str return json.dumps([source, args], separators=(",", ":")) TestInputObject = GraphQLInputObjectType( "TestInputObject", lambda: OrderedDict([ ( "inputOne", GraphQLInputObjectField(GraphQLString, out_name="input_one"), ), ( "inputRecursive", GraphQLInputObjectField(TestInputObject, out_name="input_recursive"), ), ]), ) schema = _test_schema( GraphQLField( GraphQLString, args=OrderedDict([("aInput", GraphQLArgument(TestInputObject, out_name="a_input"))]), resolver=resolver, )) result = graphql(schema, "{ test }", None) assert not result.errors assert result.data == {"test": "[null,{}]"} result = graphql(schema, '{ test(aInput: {inputOne: "String!"} ) }', "Source!") assert not result.errors assert result.data == { "test": '["Source!",{"a_input":{"input_one":"String!"}}]' } result = graphql( schema, '{ test(aInput: {inputRecursive:{inputOne: "SourceRecursive!"}} ) }', "Source!", ) assert not result.errors assert result.data == { "test": '["Source!",{"a_input":{"input_recursive":{"input_one":"SourceRecursive!"}}}]' }
def test_builds_a_schema_with_an_input_object(): AddressType = GraphQLInputObjectType( name="Address", description="An input address", fields=OrderedDict( [ ( "street", GraphQLInputObjectField( GraphQLNonNull(GraphQLString), description="What street is this address?", ), ), ( "city", GraphQLInputObjectField( GraphQLNonNull(GraphQLString), description="The city the address is within?", ), ), ( "country", GraphQLInputObjectField( GraphQLString, description="The country (blank will assume USA).", default_value="USA", ), ), ] ), ) schema = GraphQLSchema( query=GraphQLObjectType( name="HasInputObjectFields", fields={ "geocode": GraphQLField( description="Get a geocode from an address", type=GraphQLString, args={ "address": GraphQLArgument( description="The address to lookup", type=AddressType ) }, ) }, ) ) _test_schema(schema)
def test_builds_a_schema_with_field_arguments_with_default_values(): GeoType = GraphQLInputObjectType( name='Geo', fields=OrderedDict([ ('lat', GraphQLInputObjectField(GraphQLFloat)), ('lon', GraphQLInputObjectField(GraphQLFloat)), ]) ) schema = GraphQLSchema( query=GraphQLObjectType( name='ArgFields', fields=OrderedDict([ ('defaultInt', GraphQLField( GraphQLString, args={ 'intArg': GraphQLArgument( GraphQLInt, default_value=10 ) } )), ('defaultList', GraphQLField( GraphQLString, args={ 'listArg': GraphQLArgument( GraphQLList(GraphQLInt), default_value=[1, 2, 3] ) } )), ('defaultObject', GraphQLField( GraphQLString, args={ 'objArg': GraphQLArgument( GeoType, default_value={'lat': 37.485, 'lon': -122.148} ) } )) ]) ) ) _test_schema(schema)
def test_maps_argument_out_names_well_with_input(): def resolver(source, args, *_): return json.dumps([source, args], separators=(',', ':')) TestInputObject = GraphQLInputObjectType( 'TestInputObject', lambda: OrderedDict([ ('inputOne', GraphQLInputObjectField(GraphQLString, out_name="input_one")), ('inputRecursive', GraphQLInputObjectField(TestInputObject, out_name="input_recursive")), ])) schema = _test_schema( GraphQLField(GraphQLString, args=OrderedDict([('aInput', GraphQLArgument(TestInputObject, out_name="a_input"))]), resolver=resolver)) result = graphql(schema, '{ test }', None) assert not result.errors assert result.data == {'test': '[null,{}]'} result = graphql(schema, '{ test(aInput: {inputOne: "String!"} ) }', 'Source!') assert not result.errors assert result.data == { 'test': '["Source!",{"a_input":{"input_one":"String!"}}]' } result = graphql( schema, '{ test(aInput: {inputRecursive:{inputOne: "SourceRecursive!"}} ) }', 'Source!') assert not result.errors assert result.data == { 'test': '["Source!",{"a_input":{"input_recursive":{"input_one":"SourceRecursive!"}}}]' }
def mutation_with_client_mutation_id(name, input_fields, output_fields, mutate_and_get_payload): augmented_input_fields = OrderedDict( resolve_maybe_thunk(input_fields), clientMutationId=GraphQLInputObjectField( GraphQLNonNull(GraphQLString))) augmented_output_fields = OrderedDict(resolve_maybe_thunk(output_fields), clientMutationId=GraphQLField( GraphQLNonNull(GraphQLString))) input_type = GraphQLInputObjectType( name + 'Input', fields=augmented_input_fields, ) output_type = GraphQLObjectType( name + 'Payload', fields=augmented_output_fields, ) def resolver(_root, info, **args): input_ = args.get('input') def on_resolve(payload): try: payload.clientMutationId = input_['clientMutationId'] except Exception: raise GraphQLError( 'Cannot set clientMutationId in the payload object {}'. format(repr(payload))) return payload return Promise.resolve(mutate_and_get_payload( info, **input_)).then(on_resolve) return GraphQLField(output_type, args=OrderedDict( (('input', GraphQLArgument(GraphQLNonNull(input_type))), )), resolver=resolver)
def internal_type(self, schema): return GraphQLInputObjectField(schema.T(self.type), default_value=self.default, description=self.description)
def mutate_and_get_payload(data, *_): shipName = data.get('shipName') factionId = data.get('factionId') newShip = createShip(shipName, factionId) return IntroduceShipMutation( shipId=newShip.id, factionId=factionId, ) shipMutation = mutation_with_client_mutation_id( 'IntroduceShip', input_fields={ 'shipName': GraphQLInputObjectField(GraphQLNonNull(GraphQLString)), 'factionId': GraphQLInputObjectField(GraphQLNonNull(GraphQLID)) }, output_fields={ 'ship': GraphQLField(shipType, resolver=lambda payload, *_: getShip(payload.shipId)), 'faction': GraphQLField( factionType, resolver=lambda payload, *_: getFaction(payload.factionId)) }, mutate_and_get_payload=mutate_and_get_payload) # This is the type that will be the root of our mutations, and the # entry point into performing writes in our schema.
GraphQLInputObjectField, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, GraphQLSchema, GraphQLString) TestComplexScalar = GraphQLScalarType( name='ComplexScalar', serialize=lambda v: 'SerializedValue' if v == 'DeserializedValue' else None, parse_value=lambda v: 'DeserializedValue' if v == 'SerializedValue' else None, parse_literal=lambda v: 'DeserializedValue' if v.value == 'SerializedValue' else None) TestInputObject = GraphQLInputObjectType( 'TestInputObject', OrderedDict([('a', GraphQLInputObjectField(GraphQLString)), ('b', GraphQLInputObjectField(GraphQLList(GraphQLString))), ('c', GraphQLInputObjectField(GraphQLNonNull(GraphQLString))), ('d', GraphQLInputObjectField(TestComplexScalar))])) stringify = lambda obj: json.dumps(obj, sort_keys=True) def input_to_json(obj, args, context, info): input = args.get('input') if input: return stringify(input) TestNestedInputObject = GraphQLInputObjectType( name='TestNestedInputObject',
DogOrHuman = GraphQLUnionType('DogOrHuman', [Dog, Human]) HumanOrAlien = GraphQLUnionType('HumanOrAlien', [Human, Alien]) FurColor = GraphQLEnumType( 'FurColor', { 'BROWN': GraphQLEnumValue(0), 'BLACK': GraphQLEnumValue(1), 'TAN': GraphQLEnumValue(2), 'SPOTTED': GraphQLEnumValue(3), }) ComplexInput = GraphQLInputObjectType( 'ComplexInput', { 'requiredField': GraphQLInputObjectField( GraphQLNonNull(GraphQLBoolean)), 'intField': GraphQLInputObjectField(GraphQLInt), 'stringField': GraphQLInputObjectField(GraphQLString), 'booleanField': GraphQLInputObjectField(GraphQLBoolean), 'stringListField': GraphQLInputObjectField(GraphQLList(GraphQLString)), }) ComplicatedArgs = GraphQLObjectType( 'ComplicatedArgs', { 'intArgField': GraphQLField(GraphQLString, {'intArg': GraphQLArgument(GraphQLInt)}), 'nonNullIntArgField': GraphQLField( GraphQLString, {'nonNullIntArg': GraphQLArgument(GraphQLNonNull(GraphQLInt))}), 'stringArgField':
"stars": GraphQLField( GraphQLNonNull(GraphQLInt), description="The number of stars this review gave, 1-5", ), "commentary": GraphQLField(GraphQLString, description="Comment about the movie"), }, ) reviewInputType = GraphQLInputObjectType( "ReviewInput", description="The input object sent when someone is creating a new review", fields={ "stars": GraphQLInputObjectField(GraphQLInt, description="0-5 stars"), "commentary": GraphQLInputObjectField( GraphQLString, description="Comment about the movie, optional"), }, ) queryType = GraphQLObjectType( "Query", fields=lambda: { "hero": GraphQLField( characterInterface, args={ "episode": GraphQLArgument(
HumanOrAlien = GraphQLUnionType("HumanOrAlien", [Human, Alien]) FurColor = GraphQLEnumType( "FurColor", { "BROWN": GraphQLEnumValue(0), "BLACK": GraphQLEnumValue(1), "TAN": GraphQLEnumValue(2), "SPOTTED": GraphQLEnumValue(3), }, ) ComplexInput = GraphQLInputObjectType( "ComplexInput", { "requiredField": GraphQLInputObjectField( GraphQLNonNull(GraphQLBoolean)), "intField": GraphQLInputObjectField(GraphQLInt), "stringField": GraphQLInputObjectField(GraphQLString), "booleanField": GraphQLInputObjectField(GraphQLBoolean), "stringListField": GraphQLInputObjectField(GraphQLList(GraphQLString)), }, ) ComplicatedArgs = GraphQLObjectType( "ComplicatedArgs", { "intArgField": GraphQLField(GraphQLString, {"intArg": GraphQLArgument(GraphQLInt)}), "nonNullIntArgField": GraphQLField( GraphQLString,
def test_introspects_on_input_object(): TestInputObject = GraphQLInputObjectType( "TestInputObject", OrderedDict([ ("a", GraphQLInputObjectField(GraphQLString, default_value="foo")), ("b", GraphQLInputObjectField(GraphQLList(GraphQLString))), ]), ) TestType = GraphQLObjectType( "TestType", { "field": GraphQLField( type_=GraphQLString, args={"complex": GraphQLArgument(TestInputObject)}, resolver=lambda obj, info, **args: json.dumps( args.get("complex")), ) }, ) schema = GraphQLSchema(TestType) request = """ { __schema { types { kind name inputFields { name type { ...TypeRef } defaultValue } } } } fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name } } } } """ result = graphql(schema, request) assert not result.errors assert { "kind": "INPUT_OBJECT", "name": "TestInputObject", "inputFields": [ { "name": "a", "type": { "kind": "SCALAR", "name": "String", "ofType": None }, "defaultValue": '"foo"', }, { "name": "b", "type": { "kind": "LIST", "name": None, "ofType": { "kind": "SCALAR", "name": "String", "ofType": None }, }, "defaultValue": None, }, ], } in result.data["__schema"]["types"]
class Result(object): def __init__(self, result, clientMutationId=None): self.clientMutationId = clientMutationId self.result = result simpleMutation = mutation_with_client_mutation_id( 'SimpleMutation', input_fields={}, output_fields={'result': GraphQLField(GraphQLInt)}, mutate_and_get_payload=lambda _info, **_input: Result(result=1)) simpleMutationWithThunkFields = mutation_with_client_mutation_id( 'SimpleMutationWithThunkFields', input_fields=lambda: {'inputData': GraphQLInputObjectField(GraphQLInt)}, output_fields=lambda: {'result': GraphQLField(GraphQLInt)}, mutate_and_get_payload=lambda _info, **input_: Result(result=input_[ 'inputData'])) simplePromiseMutation = mutation_with_client_mutation_id( 'SimplePromiseMutation', input_fields={}, output_fields={'result': GraphQLField(GraphQLInt)}, mutate_and_get_payload=lambda _info, **_input: Promise.resolve( Result(result=1))) simpleRootValueMutation = mutation_with_client_mutation_id( 'SimpleRootValueMutation', input_fields={}, output_fields={'result': GraphQLField(GraphQLInt)},
from graphql.execution import execute from graphql.language.parser import parse from graphql.type import (GraphQLArgument, GraphQLField, GraphQLInputObjectField, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, GraphQLSchema, GraphQLString) TestComplexScalar = GraphQLScalarType( name='ComplexScalar', serialize=lambda v: 'SerializedValue' if v == 'DeserializedValue' else None, parse_value=lambda v: 'DeserializedValue' if v == 'SerializedValue' else None, parse_literal=lambda v: 'DeserializedValue' if v.value == 'SerializedValue' else None ) TestInputObject = GraphQLInputObjectType('TestInputObject', { 'a': GraphQLInputObjectField(GraphQLString), 'b': GraphQLInputObjectField(GraphQLList(GraphQLString)), 'c': GraphQLInputObjectField(GraphQLNonNull(GraphQLString)), 'd': GraphQLInputObjectField(TestComplexScalar) }) stringify = lambda obj: json.dumps(obj, sort_keys=True) def input_to_json(obj, args, context, info): input = args.get('input') if input: return stringify(input) TestNestedInputObject = GraphQLInputObjectType(
parse_value=lambda v: "DeserializedValue" if v == "SerializedValue" else None, parse_literal=lambda v: "DeserializedValue" if v.value == "SerializedValue" else None, ) class my_special_dict(dict): pass TestInputObject = GraphQLInputObjectType( "TestInputObject", OrderedDict( [ ("a", GraphQLInputObjectField(GraphQLString)), ("b", GraphQLInputObjectField(GraphQLList(GraphQLString))), ("c", GraphQLInputObjectField(GraphQLNonNull(GraphQLString))), ("d", GraphQLInputObjectField(TestComplexScalar)), ] ), ) TestCustomInputObject = GraphQLInputObjectType( "TestCustomInputObject", OrderedDict([("a", GraphQLInputObjectField(GraphQLString))]), container_type=my_special_dict, )
def test_introspects_on_input_object(): TestInputObject = GraphQLInputObjectType( 'TestInputObject', OrderedDict([ ('a', GraphQLInputObjectField(GraphQLString, default_value='foo')), ('b', GraphQLInputObjectField(GraphQLList(GraphQLString))) ])) TestType = GraphQLObjectType( 'TestType', { 'field': GraphQLField(type=GraphQLString, args={'complex': GraphQLArgument(TestInputObject)}, resolver=lambda obj, args, context, info: json.dumps( args.get('complex'))) }) schema = GraphQLSchema(TestType) request = ''' { __schema { types { kind name inputFields { name type { ...TypeRef } defaultValue } } } } fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name } } } } ''' result = graphql(schema, request) assert not result.errors assert { 'kind': 'INPUT_OBJECT', 'name': 'TestInputObject', 'inputFields': [{ 'name': 'a', 'type': { 'kind': 'SCALAR', 'name': 'String', 'ofType': None }, 'defaultValue': '"foo"' }, { 'name': 'b', 'type': { 'kind': 'LIST', 'name': None, 'ofType': { 'kind': 'SCALAR', 'name': 'String', 'ofType': None } }, 'defaultValue': None }] } in result.data['__schema']['types']