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 __new__(mcs, name, bases, attrs): if attrs.pop('abstract', False): return super(ObjectTypeMeta, mcs).__new__(mcs, name, bases, attrs) name = attrs.pop('_name', name) class_ref = WeakRefHolder() registry = mcs._get_registry() declared_fields = get_declared_fields(name, yank_potential_fields(attrs, bases)) with no_implementation_registration(): object_type = GraphQLObjectType( name, fields=partial(mcs._build_field_map, class_ref, declared_fields), description=attrs.get('__doc__'), interfaces=mcs._get_interfaces() ) object_type.is_type_of = registry._create_is_type_of(object_type) cls = super(ObjectTypeMeta, mcs).__new__(mcs, name, bases, attrs) mcs._register(object_type, cls) cls._registry = registry cls.T = object_type class_ref.set(cls) return cls
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 build_single_field_schema(field: GraphQLField): query = GraphQLObjectType(name="Query", fields={"singleField": field}) return GraphQLSchema(query=query)
def function_1() -> None: pass def function_2() -> None: pass # Create an object directly at the top level of the file so that # 'test_gather_functions_to_model' can verify that we correctly identify the # resolver DirectObjectType = GraphQLObjectType( name="DirectObjectType", description="GraphQLObject directly created at top level", fields={ "no_resolver": GraphQLField(GraphQLNonNull(GraphQLID)), "resolver": GraphQLField(GraphQLBoolean, resolver=function_1), "lambda_resolver": GraphQLField(GraphQLBoolean, resolver=lambda x: x), }, ) BrokenObjectType = GraphQLObjectType(name="BrokenObjectType", description="Look ma, no fields", fields={}) def add_field(type: GraphQLType, name: str, resolver: Callable) -> None: # pyre-ignore[16]: Undefined attribute type._fields[name] = GraphQLField(GraphQLNonNull(GraphQLID), resolver=resolver)
def define_sample_schema(): BlogImage = GraphQLObjectType( "Image", { "url": GraphQLField(GraphQLString), "width": GraphQLField(GraphQLInt), "height": GraphQLField(GraphQLInt), }, ) BlogArticle: GraphQLObjectType 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), }, ) BlogQuery = GraphQLObjectType( "Query", { "article": GraphQLField(BlogArticle, args={"id": GraphQLArgument(GraphQLString)}), "feed": GraphQLField(GraphQLList(BlogArticle)), }, ) BlogMutation = GraphQLObjectType( "Mutation", {"writeArticle": GraphQLField(BlogArticle)}) BlogSubscription = GraphQLObjectType( "Subscription", { "articleSubscribe": GraphQLField(args={"id": GraphQLArgument(GraphQLString)}, type_=BlogArticle) }, ) schema = GraphQLSchema(BlogQuery, BlogMutation, BlogSubscription) kwargs = schema.to_kwargs() types = kwargs.pop("types") assert types == list(schema.type_map.values()) assert kwargs == { "query": BlogQuery, "mutation": BlogMutation, "subscription": BlogSubscription, "directives": None, "ast_node": None, "extensions": None, "extension_ast_nodes": None, "assume_valid": False, } assert print_schema(schema) == dedent(""" type Article { id: String isPublished: Boolean author: Author title: String body: String } type Author { id: String name: String pic(width: Int, height: Int): Image recentArticle: Article } type Image { url: String width: Int height: Int } type Mutation { writeArticle: Article } type Query { article(id: String): Article feed: [Article] } type Subscription { articleSubscribe(id: String): Article } """)
}) Dog = GraphQLObjectType('Dog', { 'name': GraphQLField(GraphQLString, { 'surname': GraphQLArgument(GraphQLBoolean), }), 'nickname': GraphQLField(GraphQLString), 'barkVolume': GraphQLField(GraphQLInt), 'barks': GraphQLField(GraphQLBoolean), 'doesKnowCommand': GraphQLField(GraphQLBoolean, {'dogCommand': GraphQLArgument(DogCommand)}), 'isHousetrained': GraphQLField(GraphQLBoolean, args={ 'atOtherHomes': GraphQLArgument(GraphQLBoolean, default_value=True) }), 'isAtLocation': GraphQLField(GraphQLBoolean, args={ 'x': GraphQLArgument(GraphQLInt), 'y': GraphQLArgument(GraphQLInt) }) }, interfaces=[Being, Pet, Canine], is_type_of=lambda: None) Cat = GraphQLObjectType(
def resolve_to_euros(_root, _info, money): amount = money.amount currency = money.currency if not amount or currency == "EUR": return amount if currency == "DM": return amount * 0.5 raise ValueError("Cannot convert to euros: " + inspect(money)) countriesBalance = GraphQLObjectType( name="CountriesBalance", fields={ "Belgium": GraphQLField( GraphQLNonNull(MoneyScalar), resolve=resolve_belgium_balance ), "Luxembourg": GraphQLField( GraphQLNonNull(MoneyScalar), resolve=resolve_luxembourg_balance ), }, ) queryType = GraphQLObjectType( name="RootQueryType", fields={ "balance": GraphQLField(MoneyScalar, resolve=resolve_balance), "toEuros": GraphQLField( GraphQLFloat, args={"money": GraphQLArgument(MoneyScalar)}, resolve=resolve_to_euros, ),
async def resolve_type_can_be_caught(): PetType = GraphQLInterfaceType( "Pet", {"name": GraphQLField(GraphQLString)}, resolve_type=is_type_of_error ) DogType = GraphQLObjectType( "Dog", { "name": GraphQLField(GraphQLString), "woofs": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], ) CatType = GraphQLObjectType( "Cat", { "name": GraphQLField(GraphQLString), "meows": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], ) schema = GraphQLSchema( GraphQLObjectType( "Query", { "pets": GraphQLField( GraphQLList(PetType), resolve=lambda *_: [Dog("Odie", True), Cat("Garfield", False)], ) }, ), types=[CatType, DogType], ) query = """{ pets { name ... on Dog { woofs } ... on Cat { meows } } }""" result = await graphql(schema, query) assert result == ( {"pets": [None, None]}, [ { "message": "We are testing this error", "locations": [(2, 11)], "path": ["pets", 0], }, { "message": "We are testing this error", "locations": [(2, 11)], "path": ["pets", 1], }, ], )
async def is_type_of_with_async_error(): PetType = GraphQLInterfaceType("Pet", {"name": GraphQLField(GraphQLString)}) DogType = GraphQLObjectType( "Dog", { "name": GraphQLField(GraphQLString), "woofs": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], is_type_of=is_type_of_error, ) CatType = GraphQLObjectType( "Cat", { "name": GraphQLField(GraphQLString), "meows": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], is_type_of=get_is_type_of(Cat), ) schema = GraphQLSchema( GraphQLObjectType( "Query", { "pets": GraphQLField( GraphQLList(PetType), resolve=lambda *_args: [ Dog("Odie", True), Cat("Garfield", False), ], ) }, ), types=[CatType, DogType], ) query = """ { pets { name ... on Dog { woofs } ... on Cat { meows } } } """ result = await graphql(schema, query) # Note: we get two errors, because first all types are resolved # and only then they are checked sequentially assert result.data == {"pets": [None, None]} assert list(map(format_error, result.errors)) == [ # type: ignore { "message": "We are testing this error", "locations": [{"line": 3, "column": 15}], "path": ["pets", 0], }, { "message": "We are testing this error", "locations": [{"line": 3, "column": 15}], "path": ["pets", 1], }, ]
def test_executes_arbitary_code(): # type: () -> None class Data(object): a = "Apple" b = "Banana" c = "Cookie" d = "Donut" e = "Egg" f = "Fish" def pic(self, size=50): # type: (int) -> str return "Pic of size: {}".format(size) def deep(self): # type: () -> DeepData return DeepData() def promise(self): # type: () -> Data # FIXME: promise is unsupported return Data() class DeepData(object): a = "Already Been Done" b = "Boring" c = ["Contrived", None, "Confusing"] def deeper(self): # type: () -> List[Optional[Data]] 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, info, size: obj.pic(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, ast, Data(), operation_name="Example", variable_values={"size": 100} ) assert not result.errors assert result.data == expected
def print_single_field_schema(field: GraphQLField): Query = GraphQLObjectType(name="Query", fields={"singleField": field}) return print_for_test(GraphQLSchema(query=Query))
def print_single_field_schema(field_config): Root = GraphQLObjectType(name='Root', fields={'singleField': field_config}) return print_for_test(GraphQLSchema(Root))
def test_print_introspection_schema(): Root = GraphQLObjectType(name="Root", fields={"onlyField": GraphQLField(GraphQLString)}) Schema = GraphQLSchema(Root) output = "\n" + print_introspection_schema(Schema) assert (output == """ schema { query: Root } directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT directive @deprecated(reason: String = "No longer supported") on FIELD_DEFINITION | ENUM_VALUE type __Directive { name: String! description: String locations: [__DirectiveLocation!]! args: [__InputValue!]! onOperation: Boolean! @deprecated(reason: "Use `locations`.") onFragment: Boolean! @deprecated(reason: "Use `locations`.") onField: Boolean! @deprecated(reason: "Use `locations`.") } enum __DirectiveLocation { QUERY MUTATION SUBSCRIPTION FIELD FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT SCHEMA SCALAR OBJECT FIELD_DEFINITION ARGUMENT_DEFINITION INTERFACE UNION ENUM ENUM_VALUE INPUT_OBJECT INPUT_FIELD_DEFINITION } type __EnumValue { name: String! description: String isDeprecated: Boolean! deprecationReason: String } type __Field { name: String! description: String args: [__InputValue!]! type: __Type! isDeprecated: Boolean! deprecationReason: String } type __InputValue { name: String! description: String type: __Type! defaultValue: String } type __Schema { types: [__Type!]! queryType: __Type! mutationType: __Type subscriptionType: __Type directives: [__Directive!]! } type __Type { kind: __TypeKind! name: String description: String fields(includeDeprecated: Boolean = false): [__Field!] interfaces: [__Type!] possibleTypes: [__Type!] enumValues(includeDeprecated: Boolean = false): [__EnumValue!] inputFields: [__InputValue!] ofType: __Type } enum __TypeKind { SCALAR OBJECT INTERFACE UNION ENUM INPUT_OBJECT LIST NON_NULL } """)
async def resolve_type_allows_resolving_with_type_name(): PetType = GraphQLInterfaceType( "Pet", {"name": GraphQLField(GraphQLString)}, resolve_type=get_type_resolver({ Dog: "Dog", Cat: "Cat" }), ) DogType = GraphQLObjectType( "Dog", { "name": GraphQLField(GraphQLString), "woofs": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], ) CatType = GraphQLObjectType( "Cat", { "name": GraphQLField(GraphQLString), "meows": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], ) schema = GraphQLSchema( GraphQLObjectType( "Query", { "pets": GraphQLField( GraphQLList(PetType), resolve=lambda *_: [Dog("Odie", True), Cat("Garfield", False)], ) }, ), types=[CatType, DogType], ) query = """{ pets { name ... on Dog { woofs } ... on Cat { meows } } }""" result = await graphql(schema, query) assert result == ( { "pets": [ { "name": "Odie", "woofs": True }, { "name": "Garfield", "meows": False }, ] }, None, )
async def resolve_type_on_interface_yields_useful_error(): PetType = GraphQLInterfaceType( "Pet", {"name": GraphQLField(GraphQLString)}, resolve_type=get_type_resolver(lambda: { Dog: DogType, Cat: CatType, Human: HumanType }), ) HumanType = GraphQLObjectType("Human", {"name": GraphQLField(GraphQLString)}) DogType = GraphQLObjectType( "Dog", { "name": GraphQLField(GraphQLString), "woofs": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], ) CatType = GraphQLObjectType( "Cat", { "name": GraphQLField(GraphQLString), "meows": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], ) schema = GraphQLSchema( GraphQLObjectType( "Query", { "pets": GraphQLField( GraphQLList(PetType), resolve=lambda *_args: [ Dog("Odie", True), Cat("Garfield", False), Human("Jon"), ], ) }, ), types=[CatType, DogType], ) query = """ { pets { name ... on Dog { woofs } ... on Cat { meows } } } """ result = await graphql(schema, query) assert result.data == { "pets": [ { "name": "Odie", "woofs": True }, { "name": "Garfield", "meows": False }, None, ] } assert len(result.errors) == 1 assert format_error(result.errors[0]) == { "message": "Runtime Object type 'Human'" " is not a possible type for 'Pet'.", "locations": [(3, 15)], "path": ["pets", 2], }
from pytest import raises from graphql.error import GraphQLError from graphql.language import ( parse, DocumentNode, OperationDefinitionNode, OperationTypeDefinitionNode, SchemaDefinitionNode, ) from graphql.type import GraphQLField, GraphQLObjectType, GraphQLSchema, GraphQLString from graphql.utilities import get_operation_root_type query_type = GraphQLObjectType("FooQuery", {"field": GraphQLField(GraphQLString)}) mutation_type = GraphQLObjectType("FooMutation", {"field": GraphQLField(GraphQLString)}) subscription_type = GraphQLObjectType("FooSubscription", {"field": GraphQLField(GraphQLString)}) def get_operation_node(doc: DocumentNode) -> OperationDefinitionNode: operation_node = doc.definitions[0] assert isinstance(operation_node, OperationDefinitionNode) return operation_node def describe_deprecated_get_operation_root_type(): def gets_a_query_type_for_an_unnamed_operation_definition_node():
def prints_introspection_schema(): Root = GraphQLObjectType( name="Root", fields={"onlyField": GraphQLField(GraphQLString)} ) Schema = GraphQLSchema(Root) output = print_introspection_schema(Schema) assert output == dedent( ''' schema { query: Root } """ Directs the executor to include this field or fragment only when the `if` argument is true. """ directive @include( """Included when true.""" if: Boolean! ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT """ Directs the executor to skip this field or fragment when the `if` argument is true. """ directive @skip( """Skipped when true.""" if: Boolean! ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT """Marks an element of a GraphQL schema as no longer supported.""" directive @deprecated( """ Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/). """ reason: String = "No longer supported" ) on FIELD_DEFINITION | ENUM_VALUE """ A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document. In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor. """ type __Directive { name: String! description: String locations: [__DirectiveLocation!]! args: [__InputValue!]! } """ A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies. """ enum __DirectiveLocation { """Location adjacent to a query operation.""" QUERY """Location adjacent to a mutation operation.""" MUTATION """Location adjacent to a subscription operation.""" SUBSCRIPTION """Location adjacent to a field.""" FIELD """Location adjacent to a fragment definition.""" FRAGMENT_DEFINITION """Location adjacent to a fragment spread.""" FRAGMENT_SPREAD """Location adjacent to an inline fragment.""" INLINE_FRAGMENT """Location adjacent to a variable definition.""" VARIABLE_DEFINITION """Location adjacent to a schema definition.""" SCHEMA """Location adjacent to a scalar definition.""" SCALAR """Location adjacent to an object type definition.""" OBJECT """Location adjacent to a field definition.""" FIELD_DEFINITION """Location adjacent to an argument definition.""" ARGUMENT_DEFINITION """Location adjacent to an interface definition.""" INTERFACE """Location adjacent to a union definition.""" UNION """Location adjacent to an enum definition.""" ENUM """Location adjacent to an enum value definition.""" ENUM_VALUE """Location adjacent to an input object type definition.""" INPUT_OBJECT """Location adjacent to an input object field definition.""" INPUT_FIELD_DEFINITION } """ One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string. """ type __EnumValue { name: String! description: String isDeprecated: Boolean! deprecationReason: String } """ Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type. """ type __Field { name: String! description: String args: [__InputValue!]! type: __Type! isDeprecated: Boolean! deprecationReason: String } """ Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value. """ type __InputValue { name: String! description: String type: __Type! """ A GraphQL-formatted string representing the default value for this input value. """ defaultValue: String } """ A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations. """ type __Schema { """A list of all types supported by this server.""" types: [__Type!]! """The type that query operations will be rooted at.""" queryType: __Type! """ If this server supports mutation, the type that mutation operations will be rooted at. """ mutationType: __Type """ If this server support subscription, the type that subscription operations will be rooted at. """ subscriptionType: __Type """A list of all directives supported by this server.""" directives: [__Directive!]! } """ The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum. Depending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types. """ type __Type { kind: __TypeKind! name: String description: String fields(includeDeprecated: Boolean = false): [__Field!] interfaces: [__Type!] possibleTypes: [__Type!] enumValues(includeDeprecated: Boolean = false): [__EnumValue!] inputFields: [__InputValue!] ofType: __Type } """An enum describing what kind of type a given `__Type` is.""" enum __TypeKind { """Indicates this type is a scalar.""" SCALAR """ Indicates this type is an object. `fields` and `interfaces` are valid fields. """ OBJECT """ Indicates this type is an interface. `fields` and `possibleTypes` are valid fields. """ INTERFACE """Indicates this type is a union. `possibleTypes` is a valid field.""" UNION """Indicates this type is an enum. `enumValues` is a valid field.""" ENUM """ Indicates this type is an input object. `inputFields` is a valid field. """ INPUT_OBJECT """Indicates this type is a list. `ofType` is a valid field.""" LIST """Indicates this type is a non-null. `ofType` is a valid field.""" NON_NULL } ''' # noqa: E501 )
GraphQLArgument, GraphQLBoolean, GraphQLField, GraphQLInt, GraphQLList, GraphQLObjectType, GraphQLSchema, GraphQLString, ) from graphql.subscription import subscribe EmailType = GraphQLObjectType( "Email", { "from": GraphQLField(GraphQLString), "subject": GraphQLField(GraphQLString), "message": GraphQLField(GraphQLString), "unread": GraphQLField(GraphQLBoolean), }, ) InboxType = GraphQLObjectType( "Inbox", { "total": GraphQLField(GraphQLInt, resolve=lambda inbox, _info: len(inbox["emails"])), "unread": GraphQLField( GraphQLInt, resolve=lambda inbox, _info: sum(1 for email in inbox["emails"]
def test_executor_properly_propogates_path_data(mocker): # type: (MockFixture) -> None time_mock = mocker.patch("time.time") time_mock.side_effect = range(0, 10000) 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, info, **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, info, **args: Article(args["id"]), ), "feed": GraphQLField( GraphQLList(BlogArticle), resolver=lambda *_: map(Article, range(1, 2 + 1)), ), }, ) BlogSchema = GraphQLSchema(BlogQuery) class Article(object): def __init__(self, id): # type: (int) -> None 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) class PathCollectorMiddleware(object): def __init__(self): # type: () -> None self.paths = [] def resolve( self, _next, # type: Callable root, # type: Optional[Article] info, # type: ResolveInfo *args, # type: Any **kwargs # type: Any ): # type: (...) -> Promise self.paths.append(info.path) return _next(root, info, *args, **kwargs) request = """ { feed { id ...articleFields author { id name nameAlias: name } }, } fragment articleFields on Article { title, body, hidden, } """ paths_middleware = PathCollectorMiddleware() result = execute(BlogSchema, parse(request), middleware=(paths_middleware,)) assert not result.errors assert result.data == { "feed": [ { "id": "1", "title": "My Article 1", "body": "This is a post", "author": { "id": "123", "name": "John Smith", "nameAlias": "John Smith", }, }, { "id": "2", "title": "My Article 2", "body": "This is a post", "author": { "id": "123", "name": "John Smith", "nameAlias": "John Smith", }, }, ] } traversed_paths = paths_middleware.paths assert traversed_paths == [ ["feed"], ["feed", 0, "id"], ["feed", 0, "title"], ["feed", 0, "body"], ["feed", 0, "author"], ["feed", 1, "id"], ["feed", 1, "title"], ["feed", 1, "body"], ["feed", 1, "author"], ["feed", 0, "author", "id"], ["feed", 0, "author", "name"], ["feed", 0, "author", "nameAlias"], ["feed", 1, "author", "id"], ["feed", 1, "author", "name"], ["feed", 1, "author", "nameAlias"], ]
async def resolve_is_type_of_in_parallel(): FooType = GraphQLInterfaceType("Foo", {"foo": GraphQLField(GraphQLString)}) barrier = Barrier(4) async def is_type_of_bar(obj, *_args): await barrier.wait() return obj["foo"] == "bar" BarType = GraphQLObjectType( "Bar", { "foo": GraphQLField(GraphQLString), "foobar": GraphQLField(GraphQLInt) }, interfaces=[FooType], is_type_of=is_type_of_bar, ) async def is_type_of_baz(obj, *_args): await barrier.wait() return obj["foo"] == "baz" BazType = GraphQLObjectType( "Baz", { "foo": GraphQLField(GraphQLString), "foobaz": GraphQLField(GraphQLInt) }, interfaces=[FooType], is_type_of=is_type_of_baz, ) schema = GraphQLSchema( GraphQLObjectType( "Query", { "foo": GraphQLField( GraphQLList(FooType), resolve=lambda *_args: [ { "foo": "bar", "foobar": 1 }, { "foo": "baz", "foobaz": 2 }, ], ) }, ), types=[BarType, BazType], ) ast = parse(""" { foo { foo ... on Bar { foobar } ... on Baz { foobaz } } } """) # raises TimeoutError if not parallel awaitable_result = execute(schema, ast) assert isinstance(awaitable_result, Awaitable) result = await asyncio.wait_for(awaitable_result, 1.0) assert result == ( { "foo": [{ "foo": "bar", "foobar": 1 }, { "foo": "baz", "foobaz": 2 }] }, None, )
async def resolve_type_on_union_yields_useful_error(): HumanType = GraphQLObjectType("Human", {"name": GraphQLField(GraphQLString)}) DogType = GraphQLObjectType( "Dog", { "name": GraphQLField(GraphQLString), "woofs": GraphQLField(GraphQLBoolean), }, ) CatType = GraphQLObjectType( "Cat", { "name": GraphQLField(GraphQLString), "meows": GraphQLField(GraphQLBoolean), }, ) PetType = GraphQLUnionType( "Pet", [DogType, CatType], resolve_type=get_type_resolver( {Dog: DogType, Cat: CatType, Human: HumanType} ), ) schema = GraphQLSchema( GraphQLObjectType( "Query", { "pets": GraphQLField( GraphQLList(PetType), resolve=lambda *_: [ Dog("Odie", True), Cat("Garfield", False), Human("Jon"), ], ) }, ) ) query = """ { pets { ... on Dog { name woofs } ... on Cat { name meows } } } """ result = await graphql(schema, query) assert result.data == { "pets": [ {"name": "Odie", "woofs": True}, {"name": "Garfield", "meows": False}, None, ] } assert result.errors assert len(result.errors) == 1 assert format_error(result.errors[0]) == { "message": "Runtime Object type 'Human'" " is not a possible type for 'Pet'.", "locations": [{"line": 3, "column": 15}], "path": ["pets", 2], }
QueryType = GraphQLObjectType( "Query", { "colorEnum": GraphQLField( ColorType, args={ "fromEnum": GraphQLArgument(ColorType), "fromInt": GraphQLArgument(GraphQLInt), "fromString": GraphQLArgument(GraphQLString), }, resolve=lambda _source, info, **args: args.get("fromInt") or args.get("fromString") or args.get("fromEnum"), ), "colorInt": GraphQLField( GraphQLInt, args={ "fromEnum": GraphQLArgument(ColorType), "fromInt": GraphQLArgument(GraphQLInt), }, resolve=lambda _source, info, **args: args.get("fromEnum"), ), "complexEnum": GraphQLField( ComplexEnum, args={ # Note: default_value is provided an *internal* representation for # Enums, rather than the string name. "fromEnum": GraphQLArgument(ComplexEnum, default_value=complex1), "provideGoodValue": GraphQLArgument(GraphQLBoolean), "provideBadValue": GraphQLArgument(GraphQLBoolean), }, resolve=lambda _source, info, **args: # Note: this is one of the references of the internal values # which ComplexEnum allows. complex2 if args.get("provideGoodValue") # Note: similar object, but not the same *reference* as # complex2 above. Enum internal values require object equality. else Complex2() if args.get("provideBadValue") else args.get("fromEnum"), ), }, )
async def is_type_of_used_to_resolve_runtime_type_for_interface(): PetType = GraphQLInterfaceType("Pet", {"name": GraphQLField(GraphQLString)}) DogType = GraphQLObjectType( "Dog", { "name": GraphQLField(GraphQLString), "woofs": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], is_type_of=get_is_type_of(Dog), ) CatType = GraphQLObjectType( "Cat", { "name": GraphQLField(GraphQLString), "meows": GraphQLField(GraphQLBoolean), }, interfaces=[PetType], is_type_of=get_is_type_of(Cat), ) schema = GraphQLSchema( GraphQLObjectType( "Query", { "pets": GraphQLField( GraphQLList(PetType), resolve=lambda *_args: [ Dog("Odie", True), Cat("Garfield", False), ], ) }, ), types=[CatType, DogType], ) query = """ { pets { name ... on Dog { woofs } ... on Cat { meows } } } """ result = await graphql(schema, query) assert result == ( { "pets": [ {"name": "Odie", "woofs": True}, {"name": "Garfield", "meows": False}, ] }, None, )
def test_executes_arbitary_code(): class Data(object): a = 'Apple' b = 'Banana' c = 'Cookie' d = 'Donut' e = 'Egg' @property def f(self): return resolved('Fish') def pic(self, size=50): return resolved('Pic of size: {}'.format(size)) def deep(self): return DeepData() def promise(self): return resolved(Data()) class DeepData(object): a = 'Already Been Done' b = 'Boring' c = ['Contrived', None, resolved('Confusing')] def deeper(self): return [Data(), None, resolved(Data())] ast = parse(''' 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, info, **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) def handle_result(result): assert not result.errors assert result.data == expected handle_result( execute(schema, ast, Data(), variable_values={'size': 100}, operation_name='Example', executor=ThreadExecutor())) handle_result( execute(schema, ast, Data(), variable_values={'size': 100}, operation_name='Example'))
) humanType = GraphQLObjectType( 'Human', description='A humanoid creature in the Star Wars universe.', fields=lambda: { 'id': GraphQLField( GraphQLNonNull(GraphQLString), description='The id of the human.', ), 'name': GraphQLField( GraphQLString, description='The name of the human.', ), 'friends': GraphQLField( GraphQLList(characterInterface), description='The friends of the human, or an empty list if they have none.', resolver=lambda human, *_: getFriends(human), ), 'appearsIn': GraphQLField( GraphQLList(episodeEnum), description='Which movies they appear in.', ), 'homePlanet': GraphQLField( GraphQLString, description='The home planet of the human, or null if unknown.', ) }, interfaces=[characterInterface] ) droidType = GraphQLObjectType(
def test_synchronous_error_nulls_out_error_subtrees(): ast = parse(''' { sync syncError syncReturnError syncReturnErrorList async asyncReject asyncEmptyReject asyncReturnError } ''') class Data: def sync(self): return 'sync' def syncError(self): raise Exception('Error getting syncError') def syncReturnError(self): return Exception("Error getting syncReturnError") def syncReturnErrorList(self): return [ 'sync0', Exception('Error getting syncReturnErrorList1'), 'sync2', Exception('Error getting syncReturnErrorList3') ] def async (self): return resolved('async') def asyncReject(self): return rejected(Exception('Error getting asyncReject')) def asyncEmptyReject(self): return rejected(Exception('An unknown error occurred.')) def asyncReturnError(self): return resolved(Exception('Error getting asyncReturnError')) schema = GraphQLSchema(query=GraphQLObjectType( name='Type', fields={ 'sync': GraphQLField(GraphQLString), 'syncError': GraphQLField(GraphQLString), 'syncReturnError': GraphQLField(GraphQLString), 'syncReturnErrorList': GraphQLField(GraphQLList(GraphQLString)), 'async': GraphQLField(GraphQLString), 'asyncReject': GraphQLField(GraphQLString), 'asyncEmptyReject': GraphQLField(GraphQLString), 'asyncReturnError': GraphQLField(GraphQLString), })) def sort_key(item): locations = item['locations'][0] return (locations['line'], locations['column']) def handle_results(result): assert result.data == { 'async': 'async', 'asyncEmptyReject': None, 'asyncReject': None, 'asyncReturnError': None, 'sync': 'sync', 'syncError': None, 'syncReturnError': None, 'syncReturnErrorList': ['sync0', None, 'sync2', None] } assert sorted(list(map(format_error, result.errors)), key=sort_key) == sorted( [{ 'locations': [{ 'line': 4, 'column': 9 }], 'message': 'Error getting syncError' }, { 'locations': [{ 'line': 5, 'column': 9 }], 'message': 'Error getting syncReturnError' }, { 'locations': [{ 'line': 6, 'column': 9 }], 'message': 'Error getting syncReturnErrorList1' }, { 'locations': [{ 'line': 6, 'column': 9 }], 'message': 'Error getting syncReturnErrorList3' }, { 'locations': [{ 'line': 8, 'column': 9 }], 'message': 'Error getting asyncReject' }, { 'locations': [{ 'line': 9, 'column': 9 }], 'message': 'An unknown error occurred.' }, { 'locations': [{ 'line': 10, 'column': 9 }], 'message': 'Error getting asyncReturnError' }], key=sort_key) handle_results(execute(schema, ast, Data(), executor=ThreadExecutor()))
from graphql.type import GraphQLField, GraphQLObjectType, GraphQLSchema, GraphQLString Query = GraphQLObjectType( "Query", lambda: {"hello": GraphQLField(GraphQLString, resolver=lambda *_: "World")}) schema = GraphQLSchema(Query)
GraphQLArgument, GraphQLEnumType, GraphQLEnumValue, GraphQLField, GraphQLInterfaceType, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLSchema, GraphQLString, ) # We need to have a root query that we can extend, according to th SDL spec # we can not have an empty query type. So we initialize it with `_empty` which # will never get used. root_query = GraphQLObjectType("Query", {"_empty": GraphQLField(GraphQLString)}) # In order to extend the schema we need to start with a valid schema # class instance. In graphql-core-next we can use a SDL file for the root # as well. Here we need a little hack to future proof the rest of our # application structure. root_schema = GraphQLSchema(query=root_query) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) schema_files = os.listdir(os.path.join(BASE_DIR, 'gql')) schema_files.sort() for filename in schema_files: with open(os.path.join(BASE_DIR, 'gql', filename)) as schema_file: schema_data = schema_file.read()
) def raises(*_): 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) c = Client(wsgi) response = c.get('/', {'query': '{test}'}) assert response.json == {'data': {'test': 'Hello World'}}
def _test_schema(field_type: GraphQLOutputType = GraphQLString): return GraphQLSchema(query=GraphQLObjectType( "Query", {"field": GraphQLField(field_type)}))
human_type = GraphQLObjectType( "Human", lambda: { "id": GraphQLField(GraphQLNonNull(GraphQLString), description="The id of the human."), "name": GraphQLField(GraphQLString, description="The name of the human."), "friends": GraphQLField( GraphQLList(character_interface), description="The friends of the human," " or an empty list if they have none.", resolve=lambda human, _info: get_friends(human), ), "appearsIn": GraphQLField(GraphQLList(episode_enum), description="Which movies they appear in."), "homePlanet": GraphQLField( GraphQLString, description="The home planet of the human, or null if unknown.", ), "secretBackstory": GraphQLField( GraphQLString, resolve=lambda human, _info: get_secret_backstory(human), description= "Where are they from and how they came to be who they are.", ), }, interfaces=[character_interface], description="A humanoid creature in the Star Wars universe.", )
def member_is_subtype_of_union(): member = GraphQLObjectType("Object", {"field": GraphQLField(GraphQLString)}) union = GraphQLUnionType("Union", [member]) schema = _test_schema(union) assert is_type_sub_type_of(schema, member, union)