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)
class TestNotNullListOfNotNullT_Array_T: # [T!]! Array<T> type = GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLInt))) test_contains_values = check([1, 2], {'data': {'nest': {'test': [1, 2]}}}) test_contains_null = check( [1, None, 2], { 'data': { 'nest': None }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'Cannot return null for non-nullable field DataType.test.' }] }) test_returns_null = check( None, { 'data': { 'nest': None }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'Cannot return null for non-nullable field DataType.test.' }] })
def test_stringifies_simple_types(): assert str(GraphQLInt) == 'Int' assert str(BlogArticle) == 'Article' assert str(InterfaceType) == 'Interface' assert str(UnionType) == 'Union' assert str(EnumType) == 'Enum' assert str(InputObjectType) == 'InputObject' assert str(GraphQLNonNull(GraphQLInt)) == 'Int!' assert str(GraphQLList(GraphQLInt)) == '[Int]' assert str(GraphQLNonNull(GraphQLList(GraphQLInt))) == '[Int]!' assert str(GraphQLList(GraphQLNonNull(GraphQLInt))) == '[Int!]' assert str(GraphQLList(GraphQLList(GraphQLInt))) == '[[Int]]'
class TestNotNullListOfNotNullT_Promise_Array_T: # [T!]! Promise<Array<T>> type = GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLInt))) test_contains_value = check(succeed([1, 2]), {'data': { 'nest': { 'test': [1, 2] } }}) test_contains_null = check( succeed([1, None, 2]), { 'data': { 'nest': None }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'Cannot return null for non-nullable field DataType.test.' }] }) test_returns_null = check( succeed(None), { 'data': { 'nest': None }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'Cannot return null for non-nullable field DataType.test.' }] }) test_rejected = check( lambda: fail(Exception('bad')), { 'data': { 'nest': None }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'bad' }] })
def test_builds_a_schema_with_complex_field_values(): schema = GraphQLSchema(query=GraphQLObjectType( name='ComplexFields', fields=OrderedDict( [('string', GraphQLField(GraphQLString) ), ('listOfString', GraphQLField(GraphQLList(GraphQLString))), ('nonNullString', GraphQLField(GraphQLNonNull(GraphQLString))), ('nonNullListOfString', GraphQLField(GraphQLNonNull(GraphQLList(GraphQLString)))), ('nonNullListOfNonNullString', GraphQLField( GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString)))) )]))) _test_schema(schema)
def test_non_nullable_list_of_non_nullables(): type = GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLInt))) # [T!]! # Contains values check(type, [1, 2], {'nest': {'test': [1, 2]}}) # Contains null result = run(type, [1, None, 2]) assert len(result.errors) == 1 assert result.errors[0]['message'] == 'Cannot return null for non-nullable type.' # TODO: check error location assert result.data == {'nest': None} # Returns null result = run(type, None) assert len(result.errors) == 1 assert result.errors[0]['message'] == 'Cannot return null for non-nullable type.' # TODO: check error location assert result.data == {'nest': None}
class Test_NotNullListOfT_Array_Promise_T: # [T]! Promise<Array<T>>> type = GraphQLNonNull(GraphQLList(GraphQLInt)) test_contains_values = check([succeed(1), succeed(2)], {'data': { 'nest': { 'test': [1, 2] } }}) test_contains_null = check( [succeed(1), succeed(None), succeed(2)], {'data': { 'nest': { 'test': [1, None, 2] } }}) test_contains_reject = check( lambda: [succeed(1), fail(Exception('bad')), succeed(2)], { 'data': { 'nest': { 'test': [1, None, 2] } }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'bad' }] })
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)
def test_identifies_output_types(): expected = ((GraphQLInt, True), (ObjectType, True), (InterfaceType, True), (UnionType, True), (EnumType, True), (InputObjectType, False)) for type, answer in expected: assert is_output_type(type) == answer assert is_output_type(GraphQLList(type)) == answer assert is_output_type(GraphQLNonNull(type)) == answer
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))
def test_prohibits_putting_non_object_types_in_unions(): bad_union_types = [ GraphQLInt, GraphQLNonNull(GraphQLInt), GraphQLList(GraphQLInt), InterfaceType, UnionType, EnumType, InputObjectType ] for x in bad_union_types: with raises(Exception) as excinfo: GraphQLUnionType('BadUnion', [x]) assert 'Union BadUnion may only contain object types, it cannot contain: ' + str(x) + '.' \ == str(excinfo.value)
def resolve_node_type(get_node_type): ''' Constructs the node interface. ''' return GraphQLInterfaceType('Node', description='An object with an ID', fields=lambda: { 'id': GraphQLField( GraphQLNonNull(GraphQLID), description='The id of the object.', ), }, resolve_type=get_node_type)
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)
def test_fails_on_a_deep_non_null(): schema = GraphQLSchema(query=GraphQLObjectType( name='Query', fields={ 'foo': GraphQLField( GraphQLList( GraphQLList(GraphQLList(GraphQLNonNull(GraphQLString))))) })) introspection = graphql(schema, introspection_query) with raises(Exception) as excinfo: build_client_schema(introspection.data) assert str( excinfo.value) == 'Decorated type deeper than introspection query.'
class TestListOfNotNullT_Array_Promise_T: # [T!] Array<Promise<T>> type = GraphQLList(GraphQLNonNull(GraphQLInt)) test_contains_values = check([succeed(1), succeed(2)], {'data': { 'nest': { 'test': [1, 2] } }}) test_contains_null = check( [succeed(1), succeed(None), succeed(2)], { 'data': { 'nest': { 'test': None } }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'Cannot return null for non-nullable field DataType.test.' }] }) test_contains_reject = check( lambda: [succeed(1), fail(Exception('bad')), succeed(2)], { 'data': { 'nest': { 'test': None } }, 'errors': [{ 'locations': [{ 'column': 10, 'line': 1 }], 'message': 'bad' }] })
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 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) ) },
# Test schema. SomeInterfaceType = GraphQLInterfaceType( name='SomeInterface', resolve_type=lambda: FooType, fields=lambda: OrderedDict([ ('name', GraphQLField(GraphQLString)), ('some', GraphQLField(SomeInterfaceType)), ])) FooType = GraphQLObjectType( name='Foo', interfaces=[SomeInterfaceType], fields=lambda: OrderedDict([ ('name', GraphQLField(GraphQLString)), ('some', GraphQLField(SomeInterfaceType)), ('tree', GraphQLField(GraphQLNonNull(GraphQLList(FooType)))), ])) BarType = GraphQLObjectType(name='Bar', interfaces=[SomeInterfaceType], fields=lambda: OrderedDict([ ('name', GraphQLField(GraphQLString)), ('some', GraphQLField(SomeInterfaceType)), ('foo', GraphQLField(FooType)), ])) BizType = GraphQLObjectType(name='Biz', fields=lambda: OrderedDict([ ('fizz', GraphQLField(GraphQLString)), ]))
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 ] } } } }
GraphQLNonNull, GraphQLScalarType, ) from graphql.core.error import GraphQLError, format_error 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, info): input = args.get('input') if input: return stringify(input) TestNestedInputObject = GraphQLInputObjectType( name='TestNestedInputObject', fields={
GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLArgument, GraphQLInputObjectField, GraphQLInputObjectType, GraphQLList, GraphQLString, GraphQLNonNull, ) from graphql.core.error import GraphQLError TestInputObject = GraphQLInputObjectType('TestInputObject', { 'a': GraphQLInputObjectField(GraphQLString), 'b': GraphQLInputObjectField(GraphQLList(GraphQLString)), 'c': GraphQLInputObjectField(GraphQLNonNull(GraphQLString)), }) TestType = GraphQLObjectType('TestType', { 'fieldWithObjectInput': GraphQLField( GraphQLString, args={'input': GraphQLArgument(TestInputObject)}, resolver=lambda obj, args, *_: json.dumps(args.get('input'))), 'fieldWithNullableStringInput': GraphQLField( GraphQLString, args={'input': GraphQLArgument(GraphQLString)}, resolver=lambda obj, args, *_: json.dumps(args.get('input'))), 'fieldWithNonNullableStringInput': GraphQLField( GraphQLString, args={'input': GraphQLArgument(GraphQLNonNull(GraphQLString))}, resolver=lambda obj, args, *_: json.dumps(args.get('input'))),
def test_prohibits_nesting_nonnull_inside_nonnull(): with raises(Exception) as excinfo: GraphQLNonNull(GraphQLNonNull(GraphQLInt)) assert 'nest' in str(excinfo.value)
}, ) 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': GraphQLField(GraphQLString, { 'stringArg': GraphQLArgument(GraphQLString)
'EMPIRE': GraphQLEnumValue( 5, description='Released in 1980.', ), 'JEDI': GraphQLEnumValue( 6, description='Released in 1983.', ) }) characterInterface = GraphQLInterfaceType( 'Character', description='A character in the Star Wars Trilogy', fields=lambda: { 'id': GraphQLField(GraphQLNonNull(GraphQLString), description='The id of the character.'), 'name': GraphQLField(GraphQLString, description='The name of the character.'), 'friends': GraphQLField( GraphQLList(characterInterface), description= 'The friends of the character, or an empty list if they have none.' ), 'appearsIn': GraphQLField(GraphQLList(episodeEnum), description='Which movies they appear in.'), }, resolve_type=lambda character, *_: humanType if starwars_fixtures.getHuman(character.id) else droidType,
def test_prints_non_null_list_non_null_string_field(): output = print_single_field_schema( GraphQLField(GraphQLNonNull(GraphQLList( GraphQLNonNull(GraphQLString))))) assert output == '''
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) c = Client(wsgi) response = c.get('/', {'query': '{test}'}) assert response.json == { 'data': {
def test_prohibits_nesting_nonnull_inside_nonnull(): with raises(Exception) as excinfo: GraphQLNonNull(GraphQLNonNull(GraphQLInt)) assert 'Can only create NonNull of a Nullable GraphQLType but got: Int!.' in str( excinfo.value)
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':
return None def nonNullSync(self): return None def nest(self): return NullingData() def nonNullNest(self): return NullingData() DataType = GraphQLObjectType( 'DataType', lambda: { 'sync': GraphQLField(GraphQLString), 'nonNullSync': GraphQLField(GraphQLNonNull(GraphQLString)), 'nest': GraphQLField(DataType), 'nonNullNest': GraphQLField(GraphQLNonNull(DataType)), }) schema = GraphQLSchema(DataType) def test_nulls_a_nullable_field_that_throws_sync(): doc = ''' query Q { sync } ''' ast = parse(doc) result = execute(schema, ThrowingData(), ast, 'Q', {})
def test_prints_string_field_with_non_null_int_arg(): output = print_single_field_schema( GraphQLField( type=GraphQLString, args={'argOne': GraphQLArgument(GraphQLNonNull(GraphQLInt))})) assert output == '''