def test_defines_a_query_only_schema(): BlogSchema = GraphQLSchema(BlogQuery) assert BlogSchema.get_query_type() == BlogQuery article_field = BlogQuery.fields['article'] assert article_field.type == BlogArticle assert article_field.type.name == 'Article' # assert article_field.name == 'article' article_field_type = article_field.type assert isinstance(article_field_type, GraphQLObjectType) title_field = article_field_type.fields['title'] # assert title_field.name == 'title' assert title_field.type == GraphQLString assert title_field.type.name == 'String' author_field = article_field_type.fields['author'] author_field_type = author_field.type assert isinstance(author_field_type, GraphQLObjectType) recent_article_field = author_field_type.fields['recentArticle'] assert recent_article_field.type == BlogArticle feed_field = BlogQuery.fields['feed'] assert feed_field.type.of_type == BlogArticle
def test_includes_interfaces_thunk_subtypes_in_the_type_map(): SomeInterface = GraphQLInterfaceType( name='SomeInterface', fields={ 'f': GraphQLField(GraphQLInt) } ) SomeSubtype = GraphQLObjectType( name='SomeSubtype', fields={ 'f': GraphQLField(GraphQLInt) }, interfaces=lambda: [SomeInterface], is_type_of=lambda: True ) schema = GraphQLSchema(query=GraphQLObjectType( name='Query', fields={ 'iface': GraphQLField(SomeInterface) } ), types=[SomeSubtype]) assert schema.get_type_map()['SomeSubtype'] is SomeSubtype
def test_defines_a_mutation_schema(): BlogSchema = GraphQLSchema(BlogQuery, BlogMutation) assert BlogSchema.get_mutation_type() == BlogMutation write_mutation = BlogMutation.fields['writeArticle'] assert write_mutation.type == BlogArticle assert write_mutation.type.name == 'Article'
def test_defines_a_subscription_schema(): BlogSchema = GraphQLSchema( query=BlogQuery, subscription=BlogSubscription ) assert BlogSchema.get_subscription_type() == BlogSubscription subscription = BlogSubscription.fields['articleSubscribe'] assert subscription.type == BlogArticle assert subscription.type.name == 'Article'
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
) SubscriptionType = GraphQLObjectType( name='Subscription', fields={ 'subscribeToEnum': GraphQLField( type=ColorType, args={ 'color': GraphQLArgument(ColorType) }, resolver=lambda value, info, **args: args.get('color') ) } ) Schema = GraphQLSchema(query=QueryType, mutation=MutationType, subscription=SubscriptionType) def test_accepts_enum_literals_as_input(): result = graphql(Schema, '{ colorInt(fromEnum: GREEN) }') assert not result.errors assert result.data == { 'colorInt': 1 } def test_enum_may_be_output_type(): result = graphql(Schema, '{ colorEnum(fromInt: 1) }') assert not result.errors assert result.data == { 'colorEnum': 'GREEN'
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 = graphql_sync(schema, query) assert result == ( { "pets": [ { "name": "Odie", "woofs": True }, { "name": "Garfield", "meows": False }, ] }, None, )
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 = graphql_sync(schema, query) assert result == ( { "pets": [ { "name": "Odie", "woofs": True }, { "name": "Garfield", "meows": False }, ] }, None, )
def builds_a_schema_with_an_enum(): food_enum = GraphQLEnumType( "Food", { "VEGETABLES": GraphQLEnumValue(1, description="Foods that are vegetables."), "FRUITS": GraphQLEnumValue(2), "OILS": GraphQLEnumValue(3, deprecation_reason="Too fatty."), }, description="Varieties of food stuffs", ) schema = GraphQLSchema( GraphQLObjectType( "EnumFields", { "food": GraphQLField( food_enum, args={ "kind": GraphQLArgument(food_enum, description="what kind of food?") }, description="Repeats the arg you give it", ) }, )) introspection = introspection_from_schema(schema) client_schema = build_client_schema(introspection) second_introspection = introspection_from_schema(client_schema) assert second_introspection == introspection # It's also an Enum type on the client. client_food_enum = assert_enum_type(client_schema.get_type("Food")) # Client types do not get server-only values, so they are set to None # rather than using the integers defined in the "server" schema. values = { name: value.to_kwargs() for name, value in client_food_enum.values.items() } assert values == { "VEGETABLES": { "value": None, "description": "Foods that are vegetables.", "deprecation_reason": None, "extensions": None, "ast_node": None, }, "FRUITS": { "value": None, "description": None, "deprecation_reason": None, "extensions": None, "ast_node": None, }, "OILS": { "value": None, "description": None, "deprecation_reason": "Too fatty.", "extensions": None, "ast_node": None, }, }
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 = graphql_sync(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], }
def nonNullPromiseNest(self): return resolved(NullingData()) DataType = GraphQLObjectType('DataType', lambda: { 'sync': GraphQLField(GraphQLString), 'nonNullSync': GraphQLField(GraphQLNonNull(GraphQLString)), 'promise': GraphQLField(GraphQLString), 'nonNullPromise': GraphQLField(GraphQLNonNull(GraphQLString)), 'nest': GraphQLField(DataType), 'nonNullNest': GraphQLField(GraphQLNonNull(DataType)), 'promiseNest': GraphQLField(DataType), 'nonNullPromiseNest': GraphQLField(GraphQLNonNull(DataType)) }) schema = GraphQLSchema(DataType) def order_errors(error): locations = error['locations'] return (locations[0]['column'], locations[0]['line']) def check(doc, data, expected): ast = parse(doc) response = execute(schema, ast, data) if response.errors: result = { 'data': response.data, 'errors': [format_error(e) for e in response.errors]
WrappedDirectiveInputType = GraphQLInputObjectType( 'WrappedDirInput', {'field': GraphQLInputField(GraphQLString)}) Directive = GraphQLDirective(name='dir', locations=[DirectiveLocation.OBJECT], args={ 'arg': GraphQLArgument(DirectiveInputType), 'argList': GraphQLArgument( GraphQLList(WrappedDirectiveInputType)) }) Schema = GraphQLSchema(query=GraphQLObjectType( 'Query', {'getObject': GraphQLField(InterfaceType, resolve=lambda: {})}), directives=[Directive]) def describe_type_system_schema(): def describe_type_map(): def includes_input_types_only_used_in_directives(): assert 'DirInput' in Schema.type_map assert 'WrappedDirInput' in Schema.type_map def describe_validity(): def describe_when_not_assumed_valid(): def configures_the_schema_to_still_needing_validation(): # noinspection PyProtectedMember assert GraphQLSchema( assume_valid=False)._validation_errors is None
def configures_the_schema_to_have_no_errors(): # noinspection PyProtectedMember assert GraphQLSchema(assume_valid=True).validation_errors == []
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, description="Sample schema", ) kwargs = schema.to_kwargs() types = kwargs.pop("types") assert types == list(schema.type_map.values()) assert kwargs == { "query": BlogQuery, "mutation": BlogMutation, "subscription": BlogSubscription, "directives": specified_directives, "description": "Sample schema", "extensions": None, "ast_node": None, "extension_ast_nodes": [], "assume_valid": False, } assert print_schema(schema) == dedent(''' """Sample schema""" schema { query: Query mutation: Mutation subscription: Subscription } type Query { article(id: String): Article feed: [Article] } 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 Subscription { articleSubscribe(id: String): Article } ''')
def configures_the_schema_to_still_needing_validation(): # noinspection PyProtectedMember assert GraphQLSchema( assume_valid=False).validation_errors is None
def rejects_a_schema_with_incorrectly_typed_description(): with raises(TypeError) as exc_info: # noinspection PyTypeChecker GraphQLSchema(description=[]) # type: ignore assert str(exc_info.value) == "Schema description must be a string."
'complicatedArgs': GraphQLField(ComplicatedArgs), }) test_schema = GraphQLSchema( query=QueryRoot, directives=[ GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDirective(name='onQuery', locations=[DirectiveLocation.QUERY]), GraphQLDirective(name='onMutation', locations=[DirectiveLocation.MUTATION]), GraphQLDirective(name='onSubscription', locations=[DirectiveLocation.SUBSCRIPTION]), GraphQLDirective(name='onField', locations=[DirectiveLocation.FIELD]), GraphQLDirective(name='onFragmentDefinition', locations=[DirectiveLocation.FRAGMENT_DEFINITION]), GraphQLDirective(name='onFragmentSpread', locations=[DirectiveLocation.FRAGMENT_SPREAD]), GraphQLDirective(name='onInlineFragment', locations=[DirectiveLocation.INLINE_FRAGMENT]), GraphQLDirective(name='OnSchema', locations=[DirectiveLocation.SCHEMA]), GraphQLDirective(name='onScalar', locations=[DirectiveLocation.SCALAR]), GraphQLDirective(name='onObject', locations=[DirectiveLocation.OBJECT]), GraphQLDirective(name='onFieldDefinition', locations=[DirectiveLocation.FIELD_DEFINITION]), GraphQLDirective(name='onArgumentDefinition', locations=[DirectiveLocation.ARGUMENT_DEFINITION]), GraphQLDirective(name='onInterface', locations=[DirectiveLocation.INTERFACE]), GraphQLDirective(name='onUnion', locations=[DirectiveLocation.UNION]), GraphQLDirective(name='onEnum', locations=[DirectiveLocation.ENUM]), GraphQLDirective(name='onEnumValue', locations=[DirectiveLocation.ENUM_VALUE]), GraphQLDirective(name='onInputObject', locations=[DirectiveLocation.INPUT_OBJECT]), GraphQLDirective(name='onInputFieldDefinition', locations=[DirectiveLocation.INPUT_FIELD_DEFINITION]), ], types=[Cat, Dog, Human, Alien] ) def expect_valid(schema, rules, query):
def builds_a_schema_with_a_recursive_type_reference(): recur_type = GraphQLObjectType( 'Recur', lambda: {'recur': GraphQLField(recur_type)}) schema = GraphQLSchema(recur_type) check_schema(schema)
NumberHolderType, args={"newNumber": GraphQLArgument(GraphQLInt)}, resolver=lambda obj, info, **args: obj.fail_to_change_the_number( args["newNumber"]), ), "promiseAndFailToChangeTheNumber": GraphQLField( NumberHolderType, args={"newNumber": GraphQLArgument(GraphQLInt)}, resolver=lambda obj, info, **args: obj. promise_and_fail_to_change_the_number(args["newNumber"]), ), }, ) schema = GraphQLSchema(QueryType, MutationType) def assert_evaluate_mutations_serially(executor=None): # type: (Union[None, AsyncioExecutor, ThreadExecutor]) -> None doc = """mutation M { first: immediatelyChangeTheNumber(newNumber: 1) { theNumber }, second: promiseToChangeTheNumber(newNumber: 2) { theNumber }, third: immediatelyChangeTheNumber(newNumber: 3) { theNumber } fourth: promiseToChangeTheNumber(newNumber: 4) {