def test_cannot_use_client_schema_for_general_execution():
    customScalar = GraphQLScalarType(name='CustomScalar',
                                     serialize=lambda: None)

    schema = GraphQLSchema(query=GraphQLObjectType(
        name='Query',
        fields={
            'foo':
            GraphQLField(GraphQLString,
                         args=OrderedDict([('custom1',
                                            GraphQLArgument(customScalar)),
                                           ('custom2',
                                            GraphQLArgument(customScalar))]))
        }))

    introspection = graphql(schema, introspection_query)
    client_schema = build_client_schema(introspection.data)

    class data:
        foo = 'bar'

    result = graphql(
        client_schema,
        'query NoNo($v: CustomScalar) { foo(custom1: 123, custom2: $v) }',
        data, {'v': 'baz'})

    assert result.data == {'foo': None}
    assert [format_error(e) for e in result.errors] == [{
        'locations': [{
            'column': 32,
            'line': 1
        }],
        'message':
        'Client Schema cannot be used for execution.'
    }]
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_builds_a_schema_with_field_arguments():
    schema = GraphQLSchema(query=GraphQLObjectType(
        name='ArgFields',
        fields=OrderedDict([
            ('one',
             GraphQLField(GraphQLString,
                          description='A field with a single arg',
                          args={
                              'intArg':
                              GraphQLArgument(GraphQLInt,
                                              description='This is an int arg')
                          })),
            ('two',
             GraphQLField(GraphQLString,
                          description='A field with two args',
                          args=OrderedDict(
                              [('listArg',
                                GraphQLArgument(
                                    GraphQLList(GraphQLInt),
                                    description='This is a list of int arg')),
                               ('requiredArg',
                                GraphQLArgument(
                                    GraphQLNonNull(GraphQLBoolean),
                                    description='This is a required arg'))]))),
        ])))

    _test_schema(schema)
Example #4
0
def test_correctly_threads_arguments():
    doc = '''
        query Example {
            b(numArg: 123, stringArg: "foo")
        }
    '''

    def resolver(_, args, *_args):
        assert args['numArg'] == 123
        assert args['stringArg'] == 'foo'
        resolver.got_here = True

    resolver.got_here = False

    doc_ast = parse(doc)

    Type = GraphQLObjectType('Type', {
        'b': GraphQLField(
            GraphQLString,
            args={
                'numArg': GraphQLArgument(GraphQLInt),
                'stringArg': GraphQLArgument(GraphQLString),
            },
            resolver=resolver),
    })

    result = execute(GraphQLSchema(Type), None, doc_ast, 'Example', {})
    assert not result.errors
    assert resolver.got_here
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.get_fields() == TestObject2.get_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.get_fields() == TestInputObject2.get_fields()

    assert input_fields == {
        'field1': GraphQLInputObjectField(GraphQLString),
        'field2': GraphQLInputObjectField(GraphQLString),
    }
def test_builds_a_simple_schema_with_both_operation_types():
    QueryType = GraphQLObjectType(
        name='QueryType',
        description='This is a simple query type',
        fields={
            'string':
            GraphQLField(GraphQLString, description='This is a string field.')
        })
    MutationType = GraphQLObjectType(
        name='MutationType',
        description='This is a simple mutation type',
        fields={
            'setString':
            GraphQLField(GraphQLString,
                         description='Set the string field',
                         args={'value': GraphQLArgument(GraphQLString)})
        })
    SubscriptionType = GraphQLObjectType(
        name='SubscriptionType',
        description='This is a simple subscription type',
        fields={
            'string':
            GraphQLField(type=GraphQLString,
                         description='This is a string field')
        })

    schema = GraphQLSchema(QueryType, MutationType, SubscriptionType)
    _test_schema(schema)
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_does_not_sort_fields_and_argument_keys_when_using_ordered_dict():
    fields = OrderedDict([
        ('b', GraphQLField(GraphQLString)), ('c', GraphQLField(GraphQLString)),
        ('a', GraphQLField(GraphQLString)),
        ('d',
         GraphQLField(GraphQLString,
                      args=OrderedDict([('q', GraphQLArgument(GraphQLString)),
                                        ('x', GraphQLArgument(GraphQLString)),
                                        ('v', GraphQLArgument(GraphQLString)),
                                        ('a', GraphQLArgument(GraphQLString)),
                                        ('n', GraphQLArgument(GraphQLString))
                                        ])))
    ])

    test_object = GraphQLObjectType(name='Test', fields=fields)
    ordered_fields = test_object.get_fields()
    assert list(ordered_fields.keys()) == ['b', 'c', 'a', 'd']
    field_with_args = test_object.get_fields().get('d')
    assert [a.name for a in field_with_args.args] == ['q', 'x', 'v', 'a', 'n']
def test_sorts_fields_and_argument_keys_if_not_using_ordered_dict():
    fields = {
        'b': GraphQLField(GraphQLString),
        'c': GraphQLField(GraphQLString),
        'a': GraphQLField(GraphQLString),
        'd': GraphQLField(GraphQLString, args={
            'q': GraphQLArgument(GraphQLString),
            'x': GraphQLArgument(GraphQLString),
            'v': GraphQLArgument(GraphQLString),
            'a': GraphQLArgument(GraphQLString),
            'n': GraphQLArgument(GraphQLString)
        })
    }

    test_object = GraphQLObjectType(name='Test', fields=fields)
    ordered_fields = test_object.get_fields()
    assert list(ordered_fields.keys()) == ['a', 'b', 'c', 'd']
    field_with_args = test_object.get_fields().get('d')
    assert [a.name for a in field_with_args.args] == ['a', 'n', 'q', 'v', 'x']
def test_builds_a_schema_with_an_enum():
    FoodEnum = GraphQLEnumType(
        name='Food',
        description='Varieties of food stuffs',
        values=OrderedDict([
            ('VEGETABLES',
             GraphQLEnumValue(1, description='Foods that are vegetables.')),
            ('FRUITS', GraphQLEnumValue(2,
                                        description='Foods that are fruits.')),
            ('OILS', GraphQLEnumValue(3, description='Foods that are oils.')),
            ('DAIRY', GraphQLEnumValue(4,
                                       description='Foods that are dairy.')),
            ('MEAT', GraphQLEnumValue(5, description='Foods that are meat.')),
        ]))

    schema = GraphQLSchema(query=GraphQLObjectType(
        name='EnumFields',
        fields={
            'food':
            GraphQLField(FoodEnum,
                         description='Repeats the arg you give it',
                         args={
                             'kind':
                             GraphQLArgument(FoodEnum,
                                             description='what kind of food?')
                         })
        }))

    client_schema = _test_schema(schema)
    clientFoodEnum = client_schema.get_type('Food')
    assert isinstance(clientFoodEnum, GraphQLEnumType)

    assert clientFoodEnum.get_values() == [
        GraphQLEnumValue(name='VEGETABLES',
                         value='VEGETABLES',
                         description='Foods that are vegetables.',
                         deprecation_reason=None),
        GraphQLEnumValue(name='FRUITS',
                         value='FRUITS',
                         description='Foods that are fruits.',
                         deprecation_reason=None),
        GraphQLEnumValue(name='OILS',
                         value='OILS',
                         description='Foods that are oils.',
                         deprecation_reason=None),
        GraphQLEnumValue(name='DAIRY',
                         value='DAIRY',
                         description='Foods that are dairy.',
                         deprecation_reason=None),
        GraphQLEnumValue(name='MEAT',
                         value='MEAT',
                         description='Foods that are meat.',
                         deprecation_reason=None)
    ]
Example #12
0
 def decorate(get_node_by_id):
     return GraphQLField(node_interface,
                         description='Fetches an object given its ID',
                         args={
                             'id':
                             GraphQLArgument(
                                 GraphQLNonNull(GraphQLID),
                                 description='The ID of an object')
                         },
                         resolver=lambda obj, args, info: get_node_by_id(
                             args.get('id'), info))
Example #13
0
def test_does_not_include_arguments_that_were_not_set():
    schema = GraphQLSchema(
        GraphQLObjectType(
            'Type', {
                'field':
                GraphQLField(
                    GraphQLString,
                    resolver=lambda data, args, *_: args and json.dumps(
                        args, sort_keys=True, separators=(',', ':')),
                    args={
                        'a': GraphQLArgument(GraphQLBoolean),
                        'b': GraphQLArgument(GraphQLBoolean),
                        'c': GraphQLArgument(GraphQLBoolean),
                        'd': GraphQLArgument(GraphQLInt),
                        'e': GraphQLArgument(GraphQLInt),
                    })
            }))

    ast = parse('{ field(a: true, c: false, e: 0) }')
    result = execute(schema, None, ast)
    assert result.data == {'field': '{"a":true,"c":false,"e":0}'}
Example #14
0
    def __getitem__(self, query):
        def resolve_at_root(root, args, *_):
            target_class = self._query_to_sqlalchemy_class[query]
            return target_class.query.get(args['id'])

        return GraphQLField(
            self._graphql_objects[query],
            args={
                'id':
                GraphQLArgument(
                    description='Used to identify a base-level %s schema' %
                    query,
                    type=GraphQLNonNull(GraphQLInt),
                ),
            },
            resolver=resolve_at_root)
Example #15
0
 def make_field(self):
     output_fields = self.get_output_fields()
     output_fields.update({
         'clientMutationId': GraphQLField(GraphQLString)
     })
     output_type = GraphQLObjectType(
         self.name + 'Payload',
         fields=output_fields)
     input_fields = self.get_input_fields()
     input_fields.update({
         'clientMutationId': GraphQLInputObjectField(GraphQLString)
     })
     input_arg = GraphQLArgument(GraphQLNonNull(GraphQLInputObjectType(
         name=self.name + 'Input',
         fields=input_fields)))
     return GraphQLField(
         output_type,
         args = {
             'input': input_arg,
         },
         resolver=self
     )
def test_executes_arbitary_code():
    class Data(object):
        a = 'Apple'
        b = 'Banana'
        c = 'Cookie'
        d = 'Donut'
        e = 'Egg'

        @property
        def f(self):
            return succeed('Fish')

        def pic(self, size=50):
            return succeed('Pic of size: {}'.format(size))

        def deep(self):
            return DeepData()

        def promise(self):
            return succeed(Data())

    class DeepData(object):
        a = 'Already Been Done'
        b = 'Boring'
        c = ['Contrived', None, succeed('Confusing')]

        def deeper(self):
            return [Data(), None, succeed(Data())]

    doc = '''
        query Example($size: Int) {
            a,
            b,
            x: c
            ...c
            f
            ...on DataType {
                pic(size: $size)
                promise {
                    a
                }
            }
            deep {
                a
                b
                c
                deeper {
                    a
                    b
                }
            }
        }
        fragment c on DataType {
            d
            e
        }
    '''

    expected = {
        'a': 'Apple',
        'b': 'Banana',
        'x': 'Cookie',
        'd': 'Donut',
        'e': 'Egg',
        'f': 'Fish',
        'pic': 'Pic of size: 100',
        'promise': {
            'a': 'Apple'
        },
        'deep': {
            'a':
            'Already Been Done',
            'b':
            'Boring',
            'c': ['Contrived', None, 'Confusing'],
            'deeper': [{
                'a': 'Apple',
                'b': 'Banana'
            }, None, {
                'a': 'Apple',
                'b': 'Banana'
            }]
        }
    }

    DataType = GraphQLObjectType(
        'DataType', lambda: {
            'a':
            GraphQLField(GraphQLString),
            'b':
            GraphQLField(GraphQLString),
            'c':
            GraphQLField(GraphQLString),
            'd':
            GraphQLField(GraphQLString),
            'e':
            GraphQLField(GraphQLString),
            'f':
            GraphQLField(GraphQLString),
            'pic':
            GraphQLField(
                args={'size': GraphQLArgument(GraphQLInt)},
                type=GraphQLString,
                resolver=lambda obj, args, *_: obj.pic(args['size']),
            ),
            'deep':
            GraphQLField(DeepDataType),
            'promise':
            GraphQLField(DataType),
        })

    DeepDataType = GraphQLObjectType(
        'DeepDataType', {
            'a': GraphQLField(GraphQLString),
            'b': GraphQLField(GraphQLString),
            'c': GraphQLField(GraphQLList(GraphQLString)),
            'deeper': GraphQLField(GraphQLList(DataType)),
        })

    schema = GraphQLSchema(query=DataType)
    executor = Executor()

    def handle_result(result):
        assert not result.errors
        assert result.data == expected

    raise_callback_results(
        executor.execute(schema, doc, Data(), {'size': 100}, 'Example'),
        handle_result)
    raise_callback_results(
        executor.execute(schema,
                         doc,
                         Data(), {'size': 100},
                         'Example',
                         execute_serially=True), handle_result)
Example #17
0
    if input:
        return stringify(input)


TestNestedInputObject = GraphQLInputObjectType(
    name='TestNestedInputObject',
    fields={
        'na': GraphQLInputObjectField(GraphQLNonNull(TestInputObject)),
        'nb': GraphQLInputObjectField(GraphQLNonNull(GraphQLString))
    }
)

TestType = GraphQLObjectType('TestType', {
    'fieldWithObjectInput': GraphQLField(
        GraphQLString,
        args={'input': GraphQLArgument(TestInputObject)},
        resolver=input_to_json),
    'fieldWithNullableStringInput': GraphQLField(
        GraphQLString,
        args={'input': GraphQLArgument(GraphQLString)},
        resolver=input_to_json),
    'fieldWithNonNullableStringInput': GraphQLField(
        GraphQLString,
        args={'input': GraphQLArgument(GraphQLNonNull(GraphQLString))},
        resolver=input_to_json),
    'fieldWithDefaultArgumentValue': GraphQLField(
        GraphQLString,
        args={'input': GraphQLArgument(GraphQLString, 'Hello World')},
        resolver=input_to_json),
    'fieldWithNestedInputObject': GraphQLField(
        GraphQLString,
Example #18
0
    'Image', {
        'url': GraphQLField(GraphQLString),
        'width': GraphQLField(GraphQLInt),
        'height': GraphQLField(GraphQLInt),
    })

BlogAuthor = GraphQLObjectType(
    'Author', lambda: {
        'id':
        GraphQLField(GraphQLString),
        'name':
        GraphQLField(GraphQLString),
        'pic':
        GraphQLField(BlogImage,
                     args={
                         'width': GraphQLArgument(GraphQLInt),
                         'height': GraphQLArgument(GraphQLInt),
                     }),
        'recentArticle':
        GraphQLField(BlogArticle)
    })

BlogArticle = GraphQLObjectType(
    'Article', lambda: {
        'id': GraphQLField(GraphQLString),
        'isPublished': GraphQLField(GraphQLBoolean),
        'author': GraphQLField(BlogAuthor),
        'title': GraphQLField(GraphQLString),
        'body': GraphQLField(GraphQLString),
    })
    def promise_and_fail_to_change_the_number(self, n):
        # TODO: async
        self.fail_to_change_the_number(n)


NumberHolderType = GraphQLObjectType('NumberHolder',
                                     {'theNumber': GraphQLField(GraphQLInt)})

QueryType = GraphQLObjectType('Query',
                              {'numberHolder': GraphQLField(NumberHolderType)})

MutationType = GraphQLObjectType(
    'Mutation', {
        'immediatelyChangeTheNumber':
        GraphQLField(NumberHolderType,
                     args={'newNumber': GraphQLArgument(GraphQLInt)},
                     resolver=lambda obj, args, *_: obj.
                     immediately_change_the_number(args['newNumber'])),
        'promiseToChangeTheNumber':
        GraphQLField(NumberHolderType,
                     args={'newNumber': GraphQLArgument(GraphQLInt)},
                     resolver=lambda obj, args, *_: obj.
                     promise_to_change_the_number(args['newNumber'])),
        'failToChangeTheNumber':
        GraphQLField(NumberHolderType,
                     args={'newNumber': GraphQLArgument(GraphQLInt)},
                     resolver=lambda obj, args, *_: obj.
                     fail_to_change_the_number(args['newNumber'])),
        'promiseAndFailToChangeTheNumber':
        GraphQLField(NumberHolderType,
                     args={'newNumber': GraphQLArgument(GraphQLInt)},
from graphql.core.language.parser import parse
from graphql.core.type import (GraphQLArgument, GraphQLBoolean,
                               GraphQLEnumType, GraphQLEnumValue, GraphQLField,
                               GraphQLFloat, GraphQLID,
                               GraphQLInputObjectField, GraphQLInputObjectType,
                               GraphQLInt, GraphQLInterfaceType, GraphQLList,
                               GraphQLNonNull, GraphQLObjectType,
                               GraphQLSchema, GraphQLString, GraphQLUnionType)
from graphql.core.type.directives import (GraphQLDirective,
                                          GraphQLIncludeDirective,
                                          GraphQLSkipDirective)
from graphql.core.validation import validate

Being = GraphQLInterfaceType('Being', {
    'name': GraphQLField(GraphQLString, {
        'surname': GraphQLArgument(GraphQLBoolean),
    })
})

Pet = GraphQLInterfaceType('Pet', {
    'name': GraphQLField(GraphQLString, {
        'surname': GraphQLArgument(GraphQLBoolean),
    }),
})

DogCommand = GraphQLEnumType('DogCommand', {
    'SIT': GraphQLEnumValue(0),
    'HEEL': GraphQLEnumValue(1),
    'DOWN': GraphQLEnumValue(2),
})
Example #21
0
            description='The primary function of the droid.',
        )
    },
    interfaces=[characterInterface])

queryType = GraphQLObjectType(
    'Query',
    fields=lambda: {
        'hero':
        GraphQLField(
            characterInterface,
            args={
                'episode':
                GraphQLArgument(
                    description=
                    'If omitted, returns the hero of the whole saga. If '
                    'provided, returns the hero of that particular episode.',
                    type=episodeEnum,
                )
            },
            resolver=lambda root, args, *_: starwars_fixtures.getHero(args[
                'episode']),
        ),
        'human':
        GraphQLField(
            humanType,
            args={
                'id':
                GraphQLArgument(
                    description='id of the human',
                    type=GraphQLNonNull(GraphQLString),
                )
Example #22
0
def test_executes_arbitary_code():
    class Data(object):
        a = 'Apple'
        b = 'Banana'
        c = 'Cookie'
        d = 'Donut'
        e = 'Egg'
        f = 'Fish'

        def pic(self, size=50):
            return 'Pic of size: {}'.format(size)

        def deep(self):
            return DeepData()

        def promise(self):
            # FIXME: promise is unsupported
            return Data()

    class DeepData(object):
        a = 'Already Been Done'
        b = 'Boring'
        c = ['Contrived', None, 'Confusing']

        def deeper(self):
            return [Data(), None, Data()]

    doc = '''
        query Example($size: Int) {
            a,
            b,
            x: c
            ...c
            f
            ...on DataType {
                pic(size: $size)
                promise {
                    a
                }
            }
            deep {
                a
                b
                c
                deeper {
                    a
                    b
                }
            }
        }
        fragment c on DataType {
            d
            e
        }
    '''

    ast = parse(doc)
    expected = {
        'a': 'Apple',
        'b': 'Banana',
        'x': 'Cookie',
        'd': 'Donut',
        'e': 'Egg',
        'f': 'Fish',
        'pic': 'Pic of size: 100',
        'promise': {'a': 'Apple'},
        'deep': {
            'a': 'Already Been Done',
            'b': 'Boring',
            'c': ['Contrived', None, 'Confusing'],
            'deeper': [
                {'a': 'Apple', 'b': 'Banana'},
                None,
                {'a': 'Apple', 'b': 'Banana'}]}
    }

    DataType = GraphQLObjectType('DataType', lambda: {
        'a': GraphQLField(GraphQLString),
        'b': GraphQLField(GraphQLString),
        'c': GraphQLField(GraphQLString),
        'd': GraphQLField(GraphQLString),
        'e': GraphQLField(GraphQLString),
        'f': GraphQLField(GraphQLString),
        'pic': GraphQLField(
            args={'size': GraphQLArgument(GraphQLInt)},
            type=GraphQLString,
            resolver=lambda obj, args, *_: obj.pic(args['size']),
        ),
        'deep': GraphQLField(DeepDataType),
        'promise': GraphQLField(DataType),
    })

    DeepDataType = GraphQLObjectType('DeepDataType', {
        'a': GraphQLField(GraphQLString),
        'b': GraphQLField(GraphQLString),
        'c': GraphQLField(GraphQLList(GraphQLString)),
        'deeper': GraphQLField(GraphQLList(DataType)),
    })

    schema = GraphQLSchema(query=DataType)

    result = execute(schema, Data(), ast, 'Example', {'size': 100})
    assert not result.errors
    assert result.data == expected
Example #23
0
from graphql.core.validation import validate
from graphql.core.language.parser import parse
from graphql.core.type import (GraphQLSchema, GraphQLObjectType, GraphQLField,
                               GraphQLArgument, GraphQLID, GraphQLNonNull,
                               GraphQLString, GraphQLInt, GraphQLFloat,
                               GraphQLBoolean, GraphQLInterfaceType,
                               GraphQLEnumType, GraphQLEnumValue,
                               GraphQLInputObjectField, GraphQLInputObjectType,
                               GraphQLUnionType, GraphQLList)
from graphql.core.error import format_error

Being = GraphQLInterfaceType(
    'Being', {
        'name':
        GraphQLField(GraphQLString, {
            'surname': GraphQLArgument(GraphQLBoolean),
        })
    })

Pet = GraphQLInterfaceType(
    'Pet', {
        'name':
        GraphQLField(GraphQLString, {
            'surname': GraphQLArgument(GraphQLBoolean),
        }),
    })

DogCommand = GraphQLEnumType(
    'DogCommand', {
        'SIT': GraphQLEnumValue(0),
        'HEEL': GraphQLEnumValue(1),
Example #24
0
def get_first(args, *keys):
    for key in keys:
        if key in args:
            return args[key]

    return None


QueryType = GraphQLObjectType(
    name='Query',
    fields={
        'colorEnum':
        GraphQLField(type=ColorType,
                     args={
                         'fromEnum': GraphQLArgument(ColorType),
                         'fromInt': GraphQLArgument(GraphQLInt),
                         'fromString': GraphQLArgument(GraphQLString)
                     },
                     resolver=lambda value, args, info: get_first(
                         args, 'fromInt', 'fromString', 'fromEnum')),
        'colorInt':
        GraphQLField(type=GraphQLInt,
                     args={
                         'fromEnum': GraphQLArgument(ColorType),
                         'fromInt': GraphQLArgument(GraphQLInt),
                     },
                     resolver=lambda value, args, info: get_first(
                         args, 'fromInt', 'fromEnum'))
    })
SomeUnionType = GraphQLUnionType(
    name='SomeUnion',
    resolve_type=lambda: FooType,
    types=[FooType, BizType],
)

test_schema = GraphQLSchema(query=GraphQLObjectType(
    name='Query',
    fields=lambda: OrderedDict([
        ('foo', GraphQLField(FooType)),
        ('someUnion', GraphQLField(SomeUnionType)),
        ('someInterface',
         GraphQLField(
             SomeInterfaceType,
             args={'id': GraphQLArgument(GraphQLNonNull(GraphQLID))},
         )),
    ])))


def test_returns_original_schema_if_no_type_definitions():
    ast = parse('{ field }')
    extended_schema = extend_schema(test_schema, ast)
    assert extended_schema == test_schema


def test_extends_without_altering_original_schema():
    ast = parse('''
      extend type Query {
        newField: String
      }
Example #26
0
def test_executes_using_a_schema():
    BlogImage = GraphQLObjectType(
        'BlogImage', {
            'url': GraphQLField(GraphQLString),
            'width': GraphQLField(GraphQLInt),
            'height': GraphQLField(GraphQLInt),
        })

    BlogAuthor = GraphQLObjectType(
        'Author', lambda: {
            'id':
            GraphQLField(GraphQLString),
            'name':
            GraphQLField(GraphQLString),
            'pic':
            GraphQLField(BlogImage,
                         args={
                             'width': GraphQLArgument(GraphQLInt),
                             'height': GraphQLArgument(GraphQLInt),
                         },
                         resolver=lambda obj, args, *_: obj.pic(
                             args['width'], args['height'])),
            'recentArticle':
            GraphQLField(BlogArticle),
        })

    BlogArticle = GraphQLObjectType(
        'Article', {
            'id': GraphQLField(GraphQLNonNull(GraphQLString)),
            'isPublished': GraphQLField(GraphQLBoolean),
            'author': GraphQLField(BlogAuthor),
            'title': GraphQLField(GraphQLString),
            'body': GraphQLField(GraphQLString),
            'keywords': GraphQLField(GraphQLList(GraphQLString)),
        })

    BlogQuery = GraphQLObjectType(
        'Query', {
            'article':
            GraphQLField(BlogArticle,
                         args={'id': GraphQLArgument(GraphQLID)},
                         resolver=lambda obj, args, *_: Article(args['id'])),
            'feed':
            GraphQLField(GraphQLList(BlogArticle),
                         resolver=lambda *_: map(Article, range(1, 10 + 1))),
        })

    BlogSchema = GraphQLSchema(BlogQuery)

    class Article(object):
        def __init__(self, id):
            self.id = id
            self.isPublished = True
            self.author = Author()
            self.title = 'My Article {}'.format(id)
            self.body = 'This is a post'
            self.hidden = 'This data is not exposed in the schema'
            self.keywords = ['foo', 'bar', 1, True, None]

    class Author(object):
        id = 123
        name = 'John Smith'

        def pic(self, width, height):
            return Pic(123, width, height)

        @property
        def recentArticle(self):
            return Article(1)

    class Pic(object):
        def __init__(self, uid, width, height):
            self.url = 'cdn://{}'.format(uid)
            self.width = str(width)
            self.height = str(height)

    request = '''
    {
        feed {
          id,
          title
        },
        article(id: "1") {
          ...articleFields,
          author {
            id,
            name,
            pic(width: 640, height: 480) {
              url,
              width,
              height
            },
            recentArticle {
              ...articleFields,
              keywords
            }
          }
        }
      }
      fragment articleFields on Article {
        id,
        isPublished,
        title,
        body,
        hidden,
        notdefined
      }
    '''

    # Note: this is intentionally not validating to ensure appropriate
    # behavior occurs when executing an invalid query.
    result = execute(BlogSchema, None, parse(request))
    assert not result.errors
    assert result.data == \
        {
            "feed": [
                {
                    "id": "1",
                    "title": "My Article 1"
                },
                {
                    "id": "2",
                    "title": "My Article 2"
                },
                {
                    "id": "3",
                    "title": "My Article 3"
                },
                {
                    "id": "4",
                    "title": "My Article 4"
                },
                {
                    "id": "5",
                    "title": "My Article 5"
                },
                {
                    "id": "6",
                    "title": "My Article 6"
                },
                {
                    "id": "7",
                    "title": "My Article 7"
                },
                {
                    "id": "8",
                    "title": "My Article 8"
                },
                {
                    "id": "9",
                    "title": "My Article 9"
                },
                {
                    "id": "10",
                    "title": "My Article 10"
                }
            ],
            "article": {
                "id": "1",
                "isPublished": True,
                "title": "My Article 1",
                "body": "This is a post",
                "author": {
                    "id": "123",
                    "name": "John Smith",
                    "pic": {
                        "url": "cdn://123",
                        "width": 640,
                        "height": 480
                    },
                    "recentArticle": {
                        "id": "1",
                        "isPublished": True,
                        "title": "My Article 1",
                        "body": "This is a post",
                        "keywords": [
                            "foo",
                            "bar",
                            "1",
                            "true",
                            None
                        ]
                    }
                }
            }
        }
Example #27
0
    raise Exception("Throws!")


def resolver(root, args, *_):
    return 'Hello ' + args.get('who', 'World')


TestSchema = GraphQLSchema(
    query=GraphQLObjectType(
        'Root',
        fields=lambda: {
            'test': GraphQLField(
                GraphQLString,
                args={
                    'who': GraphQLArgument(
                        type=GraphQLString
                    )
                },
                resolver=resolver
            ),
            'thrower': GraphQLField(
                GraphQLNonNull(GraphQLString),
                resolver=raises
            )
        }
    )
)


def test_GET_functionality_allows_GET_with_query_param():
    wsgi = graphql_wsgi(TestSchema)
Example #28
0
def test_introspects_on_input_object():
    TestInputObject = GraphQLInputObjectType(
        'TestInputObject', {
            '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, 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 sort_lists({'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 \
                  sort_lists(result.data['__schema']['types'])
Example #29
0
    'Image', {
        'url': GraphQLField(GraphQLString),
        'width': GraphQLField(GraphQLInt),
        'height': GraphQLField(GraphQLInt),
    })

BlogAuthor = GraphQLObjectType(
    'Author', lambda: {
        'id':
        GraphQLField(GraphQLString),
        'name':
        GraphQLField(GraphQLString),
        'pic':
        GraphQLField(BlogImage,
                     args={
                         'width': GraphQLArgument(GraphQLInt),
                         'height': GraphQLArgument(GraphQLInt),
                     }),
        'recentArticle':
        GraphQLField(BlogArticle)
    })

BlogArticle = GraphQLObjectType(
    'Article', lambda: {
        'id': GraphQLField(GraphQLString),
        'isPublished': GraphQLField(GraphQLBoolean),
        'author': GraphQLField(BlogAuthor),
        'title': GraphQLField(GraphQLString),
        'body': GraphQLField(GraphQLString),
    })
Example #30
0
 def internal_type(self, schema):
     return GraphQLArgument(schema.T(self.type), self.default,
                            self.description)