Esempio n. 1
0
    def prints_kitchen_sink(kitchen_sink_query):  # noqa: F811
        ast = parse(kitchen_sink_query)
        printed = print_ast(ast)
        assert printed == dedent(r'''
            query queryName($foo: ComplexType, $site: Site = MOBILE) @onQuery {
              whoever123is: node(id: [123, 456]) {
                id
                ... on User @onInlineFragment {
                  field2 {
                    id
                    alias: field1(first: 10, after: $foo) @include(if: $foo) {
                      id
                      ...frag @onFragmentSpread
                    }
                  }
                }
                ... @skip(unless: $foo) {
                  id
                }
                ... {
                  id
                }
              }
            }

            mutation likeStory @onMutation {
              like(story: 123) @onField {
                story {
                  id @onField
                }
              }
            }

            subscription StoryLikeSubscription($input: StoryLikeSubscribeInput) @onSubscription {
              storyLikeSubscribe(input: $input) {
                story {
                  likers {
                    count
                  }
                  likeSentence {
                    text
                  }
                }
              }
            }

            fragment frag on Friend @onFragmentDefinition {
              foo(
                size: $size
                bar: $b
                obj: {key: "value", block: """
                  block string uses \"""
                """}
              )
            }

            {
              unnamed(truthy: true, falsy: false, nullish: null)
              query
            }

            {
              __typename
            }
            '''

                                 # noqa: E501
                                 )
 def gets_a_mutation_type_for_an_operation_definition_node():
     test_schema = GraphQLSchema(mutation=mutation_type)
     doc = parse("mutation { field }")
     operation_node = get_operation_node(doc)
     assert get_operation_root_type(test_schema, operation_node) is mutation_type
Esempio n. 3
0
 def parses_kitchen_sink_schema(kitchen_sink_sdl):  # noqa: F811
     assert parse(kitchen_sink_sdl)
Esempio n. 4
0
    def correctly_assigns_ast_nodes_to_new_and_extended_types():
        schema = build_schema("""
            type Query

            scalar SomeScalar
            enum SomeEnum
            union SomeUnion
            input SomeInput
            type SomeObject
            interface SomeInterface

            directive @foo on SCALAR
            """)
        first_extension_ast = parse("""
            extend type Query {
              newField(testArg: TestInput): TestEnum
            }

            extend scalar SomeScalar @foo

            extend enum SomeEnum {
              NEW_VALUE
            }

            extend union SomeUnion = SomeObject

            extend input SomeInput {
              newField: String
            }

            extend interface SomeInterface {
              newField: String
            }

            enum TestEnum {
              TEST_VALUE
            }

            input TestInput {
              testInputField: TestEnum
            }
            """)
        extended_schema = extend_schema(schema, first_extension_ast)

        second_extension_ast = parse("""
            extend type Query {
              oneMoreNewField: TestUnion
            }

            extend scalar SomeScalar @test

            extend enum SomeEnum {
              ONE_MORE_NEW_VALUE
            }

            extend union SomeUnion = TestType

            extend input SomeInput {
              oneMoreNewField: String
            }

            extend interface SomeInterface {
              oneMoreNewField: String
            }

            union TestUnion = TestType

            interface TestInterface {
              interfaceField: String
            }

            type TestType implements TestInterface {
              interfaceField: String
            }

            directive @test(arg: Int) repeatable on FIELD | SCALAR
            """)
        extended_twice_schema = extend_schema(extended_schema,
                                              second_extension_ast)

        extend_in_one_go_schema = extend_schema(
            schema, concat_ast([first_extension_ast, second_extension_ast]))
        assert print_schema(extend_in_one_go_schema) == print_schema(
            extended_twice_schema)

        query = assert_object_type(extended_twice_schema.get_type("Query"))
        some_enum = assert_enum_type(
            extended_twice_schema.get_type("SomeEnum"))
        some_union = assert_union_type(
            extended_twice_schema.get_type("SomeUnion"))
        some_scalar = assert_scalar_type(
            extended_twice_schema.get_type("SomeScalar"))
        some_input = assert_input_object_type(
            extended_twice_schema.get_type("SomeInput"))
        some_interface = assert_interface_type(
            extended_twice_schema.get_type("SomeInterface"))

        test_input = assert_input_object_type(
            extended_twice_schema.get_type("TestInput"))
        test_enum = assert_enum_type(
            extended_twice_schema.get_type("TestEnum"))
        test_union = assert_union_type(
            extended_twice_schema.get_type("TestUnion"))
        test_type = assert_object_type(
            extended_twice_schema.get_type("TestType"))
        test_interface = assert_interface_type(
            extended_twice_schema.get_type("TestInterface"))
        test_directive = assert_directive(
            extended_twice_schema.get_directive("test"))

        assert test_type.extension_ast_nodes == ()
        assert test_enum.extension_ast_nodes == ()
        assert test_union.extension_ast_nodes == ()
        assert test_input.extension_ast_nodes == ()
        assert test_interface.extension_ast_nodes == ()

        assert query.extension_ast_nodes
        assert len(query.extension_ast_nodes) == 2
        assert some_scalar.extension_ast_nodes
        assert len(some_scalar.extension_ast_nodes) == 2
        assert some_enum.extension_ast_nodes
        assert len(some_enum.extension_ast_nodes) == 2
        assert some_union.extension_ast_nodes
        assert len(some_union.extension_ast_nodes) == 2
        assert some_input.extension_ast_nodes
        assert len(some_input.extension_ast_nodes) == 2
        assert some_interface.extension_ast_nodes
        assert len(some_interface.extension_ast_nodes) == 2

        assert {
            test_input.ast_node,
            test_enum.ast_node,
            test_union.ast_node,
            test_interface.ast_node,
            test_type.ast_node,
            test_directive.ast_node,
            *query.extension_ast_nodes,
            *some_scalar.extension_ast_nodes,
            *some_enum.extension_ast_nodes,
            *some_union.extension_ast_nodes,
            *some_input.extension_ast_nodes,
            *some_interface.extension_ast_nodes,
        } == {
            *first_extension_ast.definitions, *second_extension_ast.definitions
        }

        new_field = query.fields["newField"]
        expect_ast_node(new_field, "newField(testArg: TestInput): TestEnum")
        expect_ast_node(new_field.args["testArg"], "testArg: TestInput")
        expect_ast_node(query.fields["oneMoreNewField"],
                        "oneMoreNewField: TestUnion")

        expect_ast_node(some_enum.values["NEW_VALUE"], "NEW_VALUE")

        one_more_new_value = some_enum.values["ONE_MORE_NEW_VALUE"]
        expect_ast_node(one_more_new_value, "ONE_MORE_NEW_VALUE")
        expect_ast_node(some_input.fields["newField"], "newField: String")
        expect_ast_node(some_input.fields["oneMoreNewField"],
                        "oneMoreNewField: String")
        expect_ast_node(some_interface.fields["newField"], "newField: String")
        expect_ast_node(some_interface.fields["oneMoreNewField"],
                        "oneMoreNewField: String")

        expect_ast_node(test_input.fields["testInputField"],
                        "testInputField: TestEnum")

        expect_ast_node(test_enum.values["TEST_VALUE"], "TEST_VALUE")

        expect_ast_node(test_interface.fields["interfaceField"],
                        "interfaceField: String")
        expect_ast_node(test_type.fields["interfaceField"],
                        "interfaceField: String")
        expect_ast_node(test_directive.args["arg"], "arg: Int")
Esempio n. 5
0
    def extends_different_types_multiple_times():
        schema = build_schema("""
            type Query {
              someScalar: SomeScalar
              someObject(someInput: SomeInput): SomeObject
              someInterface: SomeInterface
              someEnum: SomeEnum
              someUnion: SomeUnion
            }

            scalar SomeScalar

            type SomeObject implements SomeInterface {
              oldField: String
            }

            interface SomeInterface {
              oldField: String
            }

            enum SomeEnum {
              OLD_VALUE
            }

            union SomeUnion = SomeObject

            input SomeInput {
              oldField: String
            }
            """)
        new_types_sdl = dedent("""
            scalar NewScalar

            scalar AnotherNewScalar

            type NewObject {
              foo: String
            }

            type AnotherNewObject {
              foo: String
            }

            interface NewInterface {
              newField: String
            }

            interface AnotherNewInterface {
              anotherNewField: String
            }
            """)
        schema_with_new_types = extend_schema(schema, parse(new_types_sdl))
        expect_schema_changes(schema, schema_with_new_types, new_types_sdl)

        extend_ast = parse("""
            extend scalar SomeScalar @specifiedBy(url: "http://example.com/foo_spec")

            extend type SomeObject implements NewInterface {
                newField: String
            }

            extend type SomeObject implements AnotherNewInterface {
                anotherNewField: String
            }

            extend enum SomeEnum {
                NEW_VALUE
            }

            extend enum SomeEnum {
                ANOTHER_NEW_VALUE
            }

            extend union SomeUnion = NewObject

            extend union SomeUnion = AnotherNewObject

            extend input SomeInput {
                newField: String
            }

            extend input SomeInput {
                anotherNewField: String
            }
            """)
        extended_schema = extend_schema(schema_with_new_types, extend_ast)

        assert validate_schema(extended_schema) == []
        expect_schema_changes(
            schema,
            extended_schema,
            dedent("""
            scalar SomeScalar @specifiedBy(url: "http://example.com/foo_spec")

            type SomeObject implements SomeInterface & NewInterface & AnotherNewInterface {
              oldField: String
              newField: String
              anotherNewField: String
            }

            enum SomeEnum {
              OLD_VALUE
              NEW_VALUE
              ANOTHER_NEW_VALUE
            }

            union SomeUnion = SomeObject | NewObject | AnotherNewObject

            input SomeInput {
              oldField: String
              newField: String
              anotherNewField: String
            }

            """

                   # noqa: E501
                   ) + "\n\n" + new_types_sdl,
        )
Esempio n. 6
0
def extend_test_schema(sdl, **options) -> GraphQLSchema:
    original_print = print_schema(test_schema)
    ast = parse(sdl)
    extended_schema = extend_schema(test_schema, ast, **options)
    assert print_schema(test_schema) == original_print
    return extended_schema
Esempio n. 7
0
    def allows_to_disable_sdl_validation():
        schema = GraphQLSchema()
        extend_ast = parse("extend schema @unknown")

        extend_schema(schema, extend_ast, assume_valid=True)
        extend_schema(schema, extend_ast, assume_valid_sdl=True)
Esempio n. 8
0
from typing import cast

from graphql.error import GraphQLError, format_error
from graphql.language import parse, OperationDefinitionNode, Source
from graphql.pyutils import dedent

source = Source(dedent("""
    {
      field
    }
    """))

ast = parse(source)
operation_node = ast.definitions[0]
operation_node = cast(OperationDefinitionNode, operation_node)
assert operation_node and operation_node.kind == "operation_definition"
field_node = operation_node.selection_set.selections[0]
assert field_node


def describe_graphql_error():
    def is_a_class_and_is_a_subclass_of_exception():
        assert type(GraphQLError) is type
        assert issubclass(GraphQLError, Exception)
        assert isinstance(GraphQLError("str"), Exception)
        assert isinstance(GraphQLError("str"), GraphQLError)

    def has_a_name_message_and_stack_trace():
        e = GraphQLError("msg")
        assert e.__class__.__name__ == "GraphQLError"
        assert e.message == "msg"
Esempio n. 9
0
def execute_query(query, root_value):
    return execute(schema, parse(query), root_value)
    def can_introspect_on_union_and_intersection_types():
        document = parse("""
            {
              Named: __type(name: "Named") {
                kind
                name
                fields { name }
                interfaces { name }
                possibleTypes { name }
                enumValues { name }
                inputFields { name }
              }
              Mammal: __type(name: "Mammal") {
                kind
                name
                fields { name }
                interfaces { name }
                possibleTypes { name }
                enumValues { name }
                inputFields { name }
              }
              Pet: __type(name: "Pet") {
                kind
                name
                fields { name }
                interfaces { name }
                possibleTypes { name }
                enumValues { name }
                inputFields { name }
              }
            }
            """)

        assert execute_sync(schema=schema, document=document) == (
            {
                "Named": {
                    "kind":
                    "INTERFACE",
                    "name":
                    "Named",
                    "fields": [{
                        "name": "name"
                    }],
                    "interfaces": [],
                    "possibleTypes": [
                        {
                            "name": "Dog"
                        },
                        {
                            "name": "Cat"
                        },
                        {
                            "name": "Person"
                        },
                    ],
                    "enumValues":
                    None,
                    "inputFields":
                    None,
                },
                "Mammal": {
                    "kind":
                    "INTERFACE",
                    "name":
                    "Mammal",
                    "fields": [
                        {
                            "name": "progeny"
                        },
                        {
                            "name": "mother"
                        },
                        {
                            "name": "father"
                        },
                    ],
                    "interfaces": [{
                        "name": "Life"
                    }],
                    "possibleTypes": [
                        {
                            "name": "Dog"
                        },
                        {
                            "name": "Cat"
                        },
                        {
                            "name": "Person"
                        },
                    ],
                    "enumValues":
                    None,
                    "inputFields":
                    None,
                },
                "Pet": {
                    "kind": "UNION",
                    "name": "Pet",
                    "fields": None,
                    "interfaces": None,
                    "possibleTypes": [{
                        "name": "Dog"
                    }, {
                        "name": "Cat"
                    }],
                    "enumValues": None,
                    "inputFields": None,
                },
            },
            None,
        )
    def allows_fragment_conditions_to_be_abstract_types():
        document = parse("""
            {
              __typename
              name
              pets {
                ...PetFields,
                ...on Mammal {
                  mother {
                    ...ProgenyFields
                  }
                }
              }
              friends { ...FriendFields }
            }

            fragment PetFields on Pet {
              __typename
              ... on Dog {
                name
                barks
              }
              ... on Cat {
                name
                meows
              }
            }

            fragment FriendFields on Named {
              __typename
              name
              ... on Dog {
                barks
              }
              ... on Cat {
                meows
              }
            }

            fragment ProgenyFields on Life {
              progeny {
                __typename
              }
            }
            """)

        assert execute_sync(schema=schema, document=document,
                            root_value=john) == (
                                {
                                    "__typename":
                                    "Person",
                                    "name":
                                    "John",
                                    "pets": [
                                        {
                                            "__typename": "Cat",
                                            "name": "Garfield",
                                            "meows": False,
                                            "mother": {
                                                "progeny": [{
                                                    "__typename": "Cat"
                                                }]
                                            },
                                        },
                                        {
                                            "__typename": "Dog",
                                            "name": "Odie",
                                            "barks": True,
                                            "mother": {
                                                "progeny": [{
                                                    "__typename": "Dog"
                                                }]
                                            },
                                        },
                                    ],
                                    "friends": [
                                        {
                                            "__typename": "Person",
                                            "name": "Liz"
                                        },
                                        {
                                            "__typename": "Dog",
                                            "name": "Odie",
                                            "barks": True
                                        },
                                    ],
                                },
                                None,
                            )
Esempio n. 12
0
 def correctly_prints_mutation_operation_without_name():
     mutation_ast = parse("mutation { id, name }")
     assert print_ast(mutation_ast) == "mutation {\n  id\n  name\n}\n"
Esempio n. 13
0
 def correctly_prints_query_operation_without_name():
     query_ast_shorthanded = parse("query { id, name }")
     assert print_ast(query_ast_shorthanded) == "{\n  id\n  name\n}\n"
Esempio n. 14
0
 def does_not_alter_ast(kitchen_sink_query):  # noqa: F811
     ast = parse(kitchen_sink_query)
     ast_before = deepcopy(ast)
     print_ast(ast)
     assert ast == ast_before
Esempio n. 15
0
 def _error_message(schema: GraphQLSchema, query_str: str):
     errors = validate(schema, parse(query_str), [FieldsOnCorrectTypeRule])
     assert len(errors) == 1
     return errors[0].message
Esempio n. 16
0
    async def nulls_out_error_subtrees():
        document = parse("""
            {
              syncOk
              syncError
              syncRawError
              syncReturnError
              syncReturnErrorList
              asyncOk
              asyncError
              asyncRawError
              asyncReturnError
              asyncReturnErrorWithExtensions
            }
            """)

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Type",
                {
                    "syncOk": GraphQLField(GraphQLString),
                    "syncError": GraphQLField(GraphQLString),
                    "syncRawError": GraphQLField(GraphQLString),
                    "syncReturnError": GraphQLField(GraphQLString),
                    "syncReturnErrorList": GraphQLField(
                        GraphQLList(GraphQLString)),
                    "asyncOk": GraphQLField(GraphQLString),
                    "asyncError": GraphQLField(GraphQLString),
                    "asyncErrorWithExtensions": GraphQLField(GraphQLString),
                    "asyncRawError": GraphQLField(GraphQLString),
                    "asyncReturnError": GraphQLField(GraphQLString),
                    "asyncReturnErrorWithExtensions":
                    GraphQLField(GraphQLString),
                },
            ))

        # noinspection PyPep8Naming,PyMethodMayBeStatic
        class Data:
            def syncOk(self, _info):
                return "sync ok"

            def syncError(self, _info):
                raise GraphQLError("Error getting syncError")

            def syncRawError(self, _info):
                raise Exception("Error getting syncRawError")

            def syncReturnError(self, _info):
                return Exception("Error getting syncReturnError")

            def syncReturnErrorList(self, _info):
                return [
                    "sync0",
                    Exception("Error getting syncReturnErrorList1"),
                    "sync2",
                    Exception("Error getting syncReturnErrorList3"),
                ]

            async def asyncOk(self, _info):
                return "async ok"

            async def asyncError(self, _info):
                raise Exception("Error getting asyncError")

            async def asyncRawError(self, _info):
                raise Exception("Error getting asyncRawError")

            async def asyncReturnError(self, _info):
                return GraphQLError("Error getting asyncReturnError")

            async def asyncReturnErrorWithExtensions(self, _info):
                return GraphQLError(
                    "Error getting asyncReturnErrorWithExtensions",
                    extensions={"foo": "bar"},
                )

        awaitable_result = execute(schema, document, Data())
        assert isinstance(awaitable_result, Awaitable)
        result = await awaitable_result

        assert result == (
            {
                "syncOk": "sync ok",
                "syncError": None,
                "syncRawError": None,
                "syncReturnError": None,
                "syncReturnErrorList": ["sync0", None, "sync2", None],
                "asyncOk": "async ok",
                "asyncError": None,
                "asyncRawError": None,
                "asyncReturnError": None,
                "asyncReturnErrorWithExtensions": None,
            },
            [
                {
                    "message": "Error getting syncError",
                    "locations": [(4, 15)],
                    "path": ["syncError"],
                },
                {
                    "message": "Error getting syncRawError",
                    "locations": [(5, 15)],
                    "path": ["syncRawError"],
                },
                {
                    "message": "Error getting syncReturnError",
                    "locations": [(6, 15)],
                    "path": ["syncReturnError"],
                },
                {
                    "message": "Error getting syncReturnErrorList1",
                    "locations": [(7, 15)],
                    "path": ["syncReturnErrorList", 1],
                },
                {
                    "message": "Error getting syncReturnErrorList3",
                    "locations": [(7, 15)],
                    "path": ["syncReturnErrorList", 3],
                },
                {
                    "message": "Error getting asyncError",
                    "locations": [(9, 15)],
                    "path": ["asyncError"],
                },
                {
                    "message": "Error getting asyncRawError",
                    "locations": [(10, 15)],
                    "path": ["asyncRawError"],
                },
                {
                    "message": "Error getting asyncReturnError",
                    "locations": [(11, 15)],
                    "path": ["asyncReturnError"],
                },
                {
                    "message": "Error getting asyncReturnErrorWithExtensions",
                    "locations": [(12, 15)],
                    "path": ["asyncReturnErrorWithExtensions"],
                    "extensions": {
                        "foo": "bar"
                    },
                },
            ],
        )
Esempio n. 17
0
        },
    ),
    types=[FooType, BarType],
    directives=specified_directives + (FooDirective, ),
)


def extend_test_schema(sdl, **options) -> GraphQLSchema:
    original_print = print_schema(test_schema)
    ast = parse(sdl)
    extended_schema = extend_schema(test_schema, ast, **options)
    assert print_schema(test_schema) == original_print
    return extended_schema


test_schema_ast = parse(print_schema(test_schema))
test_schema_definitions = [
    print_ast(node) for node in test_schema_ast.definitions
]


def print_test_schema_changes(extended_schema):
    ast = parse(print_schema(extended_schema))
    ast.definitions = [
        node for node in ast.definitions
        if print_ast(node) not in test_schema_definitions
    ]
    return print_ast(ast)


def describe_extend_schema():
Esempio n. 18
0
    async def executes_arbitrary_code():

        # noinspection PyMethodMayBeStatic,PyMethodMayBeStatic
        class Data:
            def a(self, _info):
                return "Apple"

            def b(self, _info):
                return "Banana"

            def c(self, _info):
                return "Cookie"

            def d(self, _info):
                return "Donut"

            def e(self, _info):
                return "Egg"

            f = "Fish"

            # Called only by DataType::pic static resolver
            def pic(self, _info, size=50):
                return f"Pic of size: {size}"

            def deep(self, _info):
                return DeepData()

            def promise(self, _info):
                return promise_data()

        # noinspection PyMethodMayBeStatic,PyMethodMayBeStatic
        class DeepData:
            def a(self, _info):
                return "Already Been Done"

            def b(self, _info):
                return "Boring"

            def c(self, _info):
                return ["Contrived", None, "Confusing"]

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

        async def promise_data():
            await asyncio.sleep(0)
            return Data()

        DeepDataType: GraphQLObjectType

        DataType = GraphQLObjectType(
            "DataType",
            lambda: {
                "a":
                GraphQLField(GraphQLString),
                "b":
                GraphQLField(GraphQLString),
                "c":
                GraphQLField(GraphQLString),
                "d":
                GraphQLField(GraphQLString),
                "e":
                GraphQLField(GraphQLString),
                "f":
                GraphQLField(GraphQLString),
                "pic":
                GraphQLField(
                    GraphQLString,
                    args={"size": GraphQLArgument(GraphQLInt)},
                    resolve=lambda obj, info, size: obj.pic(info, size),
                ),
                "deep":
                GraphQLField(DeepDataType),
                "promise":
                GraphQLField(DataType),
            },
        )

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

        document = parse("""
            query ($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
            }
            """)

        awaitable_result = execute(GraphQLSchema(DataType),
                                   document,
                                   Data(),
                                   variable_values={"size": 100})
        assert isinstance(awaitable_result, Awaitable)
        result = await awaitable_result

        assert result == (
            {
                "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"
                        },
                    ],
                },
            },
            None,
        )
Esempio n. 19
0
    def correctly_assigns_ast_nodes_to_new_and_extended_types():
        extended_schema = extend_test_schema("""
            extend type Query {
              newField(testArg: TestInput): TestEnum
            }

            extend scalar SomeScalar @foo

            extend enum SomeEnum {
              NEW_VALUE
            }

            extend union SomeUnion = Bar

            extend input SomeInput {
              newField: String
            }

            extend interface SomeInterface {
              newField: String
            }

            enum TestEnum {
              TEST_VALUE
            }

            input TestInput {
              testInputField: TestEnum
            }
            """)
        ast = parse("""
            extend type Query {
              oneMoreNewField: TestUnion
            }

            extend scalar SomeScalar @test

            extend enum SomeEnum {
              ONE_MORE_NEW_VALUE
            }

            extend union SomeUnion = TestType

            extend input SomeInput {
              oneMoreNewField: String
            }

            extend interface SomeInterface {
              oneMoreNewField: String
            }

            union TestUnion = TestType

            interface TestInterface {
              interfaceField: String
            }

            type TestType implements TestInterface {
              interfaceField: String
            }

            directive @test(arg: Int) on FIELD | SCALAR
            """)
        extended_twice_schema = extend_schema(extended_schema, ast)

        query = assert_object_type(extended_twice_schema.get_type("Query"))
        some_enum = assert_enum_type(
            extended_twice_schema.get_type("SomeEnum"))
        some_union = assert_union_type(
            extended_twice_schema.get_type("SomeUnion"))
        some_scalar = assert_scalar_type(
            extended_twice_schema.get_type("SomeScalar"))
        some_input = assert_input_object_type(
            extended_twice_schema.get_type("SomeInput"))
        some_interface = assert_interface_type(
            extended_twice_schema.get_type("SomeInterface"))

        test_input = assert_input_object_type(
            extended_twice_schema.get_type("TestInput"))
        test_enum = assert_enum_type(
            extended_twice_schema.get_type("TestEnum"))
        test_union = assert_union_type(
            extended_twice_schema.get_type("TestUnion"))
        test_type = assert_object_type(
            extended_twice_schema.get_type("TestType"))
        test_interface = assert_interface_type(
            extended_twice_schema.get_type("TestInterface"))
        test_directive = assert_directive(
            extended_twice_schema.get_directive("test"))

        assert test_type.extension_ast_nodes is None
        assert test_enum.extension_ast_nodes is None
        assert test_union.extension_ast_nodes is None
        assert test_input.extension_ast_nodes is None
        assert test_interface.extension_ast_nodes is None

        assert len(query.extension_ast_nodes) == 2
        assert len(some_scalar.extension_ast_nodes) == 2
        assert len(some_enum.extension_ast_nodes) == 2
        assert len(some_union.extension_ast_nodes) == 2
        assert len(some_input.extension_ast_nodes) == 2
        assert len(some_interface.extension_ast_nodes) == 2

        definitions = [
            test_input.ast_node,
            test_enum.ast_node,
            test_union.ast_node,
            test_interface.ast_node,
            test_type.ast_node,
            test_directive.ast_node,
        ]
        for extension_ast_nodes in [
                query.extension_ast_nodes,
                some_scalar.extension_ast_nodes,
                some_enum.extension_ast_nodes,
                some_union.extension_ast_nodes,
                some_input.extension_ast_nodes,
                some_interface.extension_ast_nodes,
        ]:
            if extension_ast_nodes:
                definitions.extend(extension_ast_nodes)
        restored_extension_ast = DocumentNode(definitions=definitions)

        assert print_schema(extend_schema(
            test_schema,
            restored_extension_ast)) == print_schema(extended_twice_schema)

        new_field = query.fields["newField"]
        assert print_ast(
            new_field.ast_node) == "newField(testArg: TestInput): TestEnum"
        assert print_ast(
            new_field.args["testArg"].ast_node) == "testArg: TestInput"
        assert (print_ast(query.fields["oneMoreNewField"].ast_node) ==
                "oneMoreNewField: TestUnion")

        new_value = some_enum.values["NEW_VALUE"]
        assert some_enum
        assert print_ast(new_value.ast_node) == "NEW_VALUE"

        one_more_new_value = some_enum.values["ONE_MORE_NEW_VALUE"]
        assert one_more_new_value
        assert print_ast(one_more_new_value.ast_node) == "ONE_MORE_NEW_VALUE"
        assert print_ast(
            some_input.fields["newField"].ast_node) == "newField: String"
        assert (print_ast(some_input.fields["oneMoreNewField"].ast_node) ==
                "oneMoreNewField: String")
        assert (print_ast(
            some_interface.fields["newField"].ast_node) == "newField: String")
        assert (print_ast(some_interface.fields["oneMoreNewField"].ast_node) ==
                "oneMoreNewField: String")

        assert (print_ast(test_input.fields["testInputField"].ast_node) ==
                "testInputField: TestEnum")

        test_value = test_enum.values["TEST_VALUE"]
        assert test_value
        assert print_ast(test_value.ast_node) == "TEST_VALUE"

        assert (print_ast(test_interface.fields["interfaceField"].ast_node) ==
                "interfaceField: String")
        assert (print_ast(test_type.fields["interfaceField"].ast_node) ==
                "interfaceField: String")
        assert print_ast(test_directive.args["arg"].ast_node) == "arg: Int"
Esempio n. 20
0
def assert_syntax_error(text, message, location):
    with raises(GraphQLSyntaxError) as exc_info:
        parse(text)
    error = exc_info.value
    assert message in error.message
    assert error.locations == [location]
Esempio n. 21
0
        def does_not_automatically_include_common_root_type_names():
            schema = GraphQLSchema()
            extended_schema = extend_schema(schema, parse("type Mutation"))

            assert extended_schema.get_type("Mutation")
            assert extended_schema.mutation_type is None
Esempio n. 22
0
def execute_query(query, variable_values=None):
    document = parse(query)
    return execute(schema, document, variable_values=variable_values)
Esempio n. 23
0
 def returns_the_original_schema_when_there_are_no_type_definitions():
     schema = build_schema("type Query")
     extended_schema = extend_schema(schema, parse("{ field }"))
     assert extended_schema == schema
Esempio n. 24
0
    def does_not_include_illegal_mutation_fields_in_output():
        document = parse("mutation { thisIsIllegalDoNotIncludeMe }")

        result = execute(schema=schema, document=document)
        assert result == ({}, None)
 def gets_a_query_type_for_a_named_operation_definition_node():
     test_schema = GraphQLSchema(query_type)
     doc = parse("query Q { field }")
     operation_node = get_operation_node(doc)
     assert get_operation_root_type(test_schema, operation_node) is query_type
Esempio n. 26
0
    async def evaluates_mutations_correctly_in_presence_of_a_failed_mutation():
        document = parse("""
            mutation M {
              first: immediatelyChangeTheNumber(newNumber: 1) {
                theNumber
              },
              second: promiseToChangeTheNumber(newNumber: 2) {
                theNumber
              },
              third: failToChangeTheNumber(newNumber: 3) {
                theNumber
              }
              fourth: promiseToChangeTheNumber(newNumber: 4) {
                theNumber
              },
              fifth: immediatelyChangeTheNumber(newNumber: 5) {
                theNumber
              }
              sixth: promiseAndFailToChangeTheNumber(newNumber: 6) {
                theNumber
              }
            }
            """)

        root_value = Root(6)
        awaitable_result = execute(schema=schema,
                                   document=document,
                                   root_value=root_value)
        assert isinstance(awaitable_result, Awaitable)
        result = await awaitable_result

        assert result == (
            {
                "first": {
                    "theNumber": 1
                },
                "second": {
                    "theNumber": 2
                },
                "third": None,
                "fourth": {
                    "theNumber": 4
                },
                "fifth": {
                    "theNumber": 5
                },
                "sixth": None,
            },
            [
                {
                    "message": "Cannot change the number to 3",
                    "locations": [(9, 15)],
                    "path": ["third"],
                },
                {
                    "message": "Cannot change the number to 6",
                    "locations": [(18, 15)],
                    "path": ["sixth"],
                },
            ],
        )
 def gets_a_subscription_type_for_an_operation_definition_node():
     test_schema = GraphQLSchema(subscription=subscription_type)
     doc = parse("subscription { field }")
     operation_node = get_operation_node(doc)
     assert get_operation_root_type(test_schema, operation_node) is subscription_type
Esempio n. 28
0
    def extends_different_types_multiple_times():
        schema = build_schema("""
            type Query {
              someObject(someInput: SomeInput): SomeObject
              someInterface: SomeInterface
              someEnum: SomeEnum
              someUnion: SomeUnion
            }

            type SomeObject implements SomeInterface {
              oldField: String
            }

            interface SomeInterface {
              oldField: String
            }

            enum SomeEnum {
              OLD_VALUE
            }

            union SomeUnion = SomeObject

            input SomeInput {
              oldField: String
            }
            """)
        new_types_sdl = """
            interface AnotherNewInterface {
              anotherNewField: String
            }

            type AnotherNewObject {
              foo: String
            }

            interface NewInterface {
              newField: String
            }

            type NewObject {
              foo: String
            }
            """
        extend_ast = parse(new_types_sdl + """
            extend type SomeObject implements NewInterface {
                newField: String
            }

            extend type SomeObject implements AnotherNewInterface {
                anotherNewField: String
            }

            extend enum SomeEnum {
                NEW_VALUE
            }

            extend enum SomeEnum {
                ANOTHER_NEW_VALUE
            }

            extend union SomeUnion = NewObject

            extend union SomeUnion = AnotherNewObject

            extend input SomeInput {
                newField: String
            }

            extend input SomeInput {
                anotherNewField: String
            }
            """)
        extended_schema = extend_schema(schema, extend_ast)

        assert validate_schema(extended_schema) == []
        assert print_schema_changes(schema, extended_schema) == dedent(
            new_types_sdl + """
            enum SomeEnum {
              OLD_VALUE
              NEW_VALUE
              ANOTHER_NEW_VALUE
            }

            input SomeInput {
              oldField: String
              newField: String
              anotherNewField: String
            }

            type SomeObject implements SomeInterface & NewInterface & AnotherNewInterface {
              oldField: String
              newField: String
              anotherNewField: String
            }

            union SomeUnion = SomeObject | NewObject | AnotherNewObject
            """

            # noqa: E501
        )
Esempio n. 29
0
 def parses_variable_inline_values():
     parse("{ field(complex: { a: { b: [ $var ] } }) }")
Esempio n. 30
0
 def does_not_return_an_awaitable_for_validation_errors():
     doc = "fragment Example on Query { unknownField }"
     validation_errors = validate(schema, parse(doc))
     result = graphql_sync(schema, doc)
     assert result == (None, validation_errors)