예제 #1
0
        def with_extensions():
            interface_extensions = {"SomeInterfaceExt": "interface"}
            field_extensions = {"SomeFieldExt": "field"}
            arg_extensions = {"SomeArgExt": "arg"}

            some_interface = GraphQLInterfaceType(
                "SomeInterface",
                {
                    "someField": GraphQLField(
                        dummy_type,
                        {
                            "someArg": GraphQLArgument(
                                dummy_type, extensions=arg_extensions
                            )
                        },
                        extensions=field_extensions,
                    )
                },
                extensions=interface_extensions,
            )

            assert some_interface.extensions is interface_extensions
            some_field = some_interface.fields["someField"]
            assert some_field.extensions is field_extensions
            some_arg = some_field.args["someArg"]
            assert some_arg.extensions is arg_extensions

            assert some_interface.to_kwargs()["extensions"] is interface_extensions
            assert some_field.to_kwargs()["extensions"] is field_extensions
            assert some_arg.to_kwargs()["extensions"] is arg_extensions
예제 #2
0
    def prints_multiple_interfaces():
        foo_type = GraphQLInterfaceType(
            name="Foo", fields={"str": GraphQLField(GraphQLString)})

        baz_type = GraphQLInterfaceType(
            name="Baz", fields={"int": GraphQLField(GraphQLInt)})

        bar_type = GraphQLObjectType(
            name="Bar",
            fields={
                "str": GraphQLField(GraphQLString),
                "int": GraphQLField(GraphQLInt),
            },
            interfaces=[foo_type, baz_type],
        )

        schema = GraphQLSchema(types=[bar_type])
        output = print_for_test(schema)
        assert output == dedent("""
            type Bar implements Foo & Baz {
              str: String
              int: Int
            }

            interface Foo {
              str: String
            }

            interface Baz {
              int: Int
            }
            """)
예제 #3
0
 def includes_interfaces_thunk_subtypes_in_the_type_map():
     AnotherInterface = GraphQLInterfaceType("AnotherInterface", {})
     SomeInterface = GraphQLInterfaceType(
         "SomeInterface", {}, interfaces=lambda: [AnotherInterface])
     SomeSubtype = GraphQLObjectType("SomeSubtype", {},
                                     interfaces=lambda: [SomeInterface])
     schema = GraphQLSchema(types=[SomeSubtype], )
     assert schema.type_map["SomeInterface"] is SomeInterface
     assert schema.type_map["AnotherInterface"] is AnotherInterface
     assert schema.type_map["SomeSubtype"] is SomeSubtype
예제 #4
0
 def implementing_interface_is_subtype_of_interface():
     iface = GraphQLInterfaceType(
         "Interface", {"field": GraphQLField(GraphQLString)})
     iface2 = GraphQLInterfaceType(
         "Interface2", {"field": GraphQLField(GraphQLString)}, [iface])
     impl = GraphQLObjectType(
         "Object",
         {"field": GraphQLField(GraphQLString)},
         [iface2, iface],
     )
     schema = _test_schema(impl)
     assert is_type_sub_type_of(schema, iface2, iface)
예제 #5
0
def test_prints_multiple_interfaces():
    FooType = GraphQLInterfaceType(
        name="Foo",
        resolve_type=lambda *_: None,
        fields={"str": GraphQLField(GraphQLString)},
    )
    BaazType = GraphQLInterfaceType(
        name="Baaz",
        resolve_type=lambda *_: None,
        fields={"int": GraphQLField(GraphQLInt)},
    )

    BarType = GraphQLObjectType(
        name="Bar",
        fields=OrderedDict(
            [("str", GraphQLField(GraphQLString)), ("int", GraphQLField(GraphQLInt))]
        ),
        interfaces=[FooType, BaazType],
    )

    Root = GraphQLObjectType(name="Root", fields={"bar": GraphQLField(BarType)})

    Schema = GraphQLSchema(Root, types=[BarType])
    output = print_for_test(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

interface Baaz {
  int: Int
}

type Bar implements Foo & Baaz {
  str: String
  int: Int
}

interface Foo {
  str: String
}

type Root {
  bar: Bar
}
"""
    )
    def prints_hierarchical_interface():
        foo_type = GraphQLInterfaceType(
            name="Foo", fields={"str": GraphQLField(GraphQLString)}
        )

        baz_type = GraphQLInterfaceType(
            name="Baz",
            interfaces=[foo_type],
            fields={
                "int": GraphQLField(GraphQLInt),
                "str": GraphQLField(GraphQLString),
            },
        )

        bar_type = GraphQLObjectType(
            name="Bar",
            fields={
                "str": GraphQLField(GraphQLString),
                "int": GraphQLField(GraphQLInt),
            },
            interfaces=[foo_type, baz_type],
        )

        query = GraphQLObjectType(name="Query", fields={"bar": GraphQLField(bar_type)})

        schema = GraphQLSchema(query, types=[bar_type])
        output = print_for_test(schema)
        assert output == dedent(
            """
            type Bar implements Foo & Baz {
              str: String
              int: Int
            }

            interface Baz implements Foo {
              int: Int
              str: String
            }

            interface Foo {
              str: String
            }

            type Query {
              bar: Bar
            }
            """
        )
예제 #7
0
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 prints_empty_types():
        schema = GraphQLSchema(
            types=[
                GraphQLEnumType("SomeEnum", cast(Dict[str, Any], {})),
                GraphQLInputObjectType("SomeInputObject", {}),
                GraphQLInterfaceType("SomeInterface", {}),
                GraphQLObjectType("SomeObject", {}),
                GraphQLUnionType("SomeUnion", []),
            ]
        )

        output = print_for_test(schema)
        assert output == dedent(
            """
            enum SomeEnum

            input SomeInputObject

            interface SomeInterface

            type SomeObject

            union SomeUnion
            """
        )
예제 #9
0
def node_definitions(id_fetcher, type_resolver=None, id_resolver=None):
    """
    Given a function to map from an ID to an underlying object, and a function
    to map from an underlying object to the concrete GraphQLObjectType it
    corresponds to, constructs a `Node` interface that objects can implement,
    and a field config for a `node` root field.

    If the type_resolver is omitted, object resolution on the interface will be
    handled with the `isTypeOf` method on object types, as with any GraphQL
    interface without a provided `resolveType` method.
    """
    node_interface = GraphQLInterfaceType(
        'Node',
        description='An object with an ID',
        fields=lambda: OrderedDict((('id',
                                     GraphQLField(
                                         GraphQLNonNull(GraphQLID),
                                         description='The id of the object.',
                                         resolver=id_resolver,
                                     )), )),
        resolve_type=type_resolver)
    node_field = GraphQLField(
        node_interface,
        description='Fetches an object given its ID',
        args=OrderedDict(
            (('id',
              GraphQLArgument(GraphQLNonNull(GraphQLID),
                              description='The ID of an object')), )),
        resolver=lambda _obj, info, id: id_fetcher(id, info))
    return node_interface, node_field
예제 #10
0
    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,
        )
예제 #11
0
def test_builds_a_schema_with_an_interface():
    FriendlyType = GraphQLInterfaceType(
        name='Friendly',
        resolve_type=lambda: None,
        fields=lambda: {
            'bestFriend':
            GraphQLField(FriendlyType,
                         description='The best friend of this friendly thing.')
        })

    DogType = GraphQLObjectType(
        name='DogType',
        interfaces=[FriendlyType],
        fields=lambda: {'bestFriend': GraphQLField(FriendlyType)})

    HumanType = GraphQLObjectType(
        name='Human',
        interfaces=[FriendlyType],
        fields=lambda: {'bestFriend': GraphQLField(FriendlyType)})

    schema = GraphQLSchema(query=GraphQLObjectType(
        name='WithInterface', fields={'friendly': GraphQLField(FriendlyType)}),
                           types=[DogType, HumanType])

    _test_schema(schema)
예제 #12
0
    def returning_invalid_value_from_resolve_type_yields_useful_error():
        fooInterface = GraphQLInterfaceType(
            'FooInterface', {'bar': GraphQLField(GraphQLString)},
            resolve_type=lambda *_args: [])

        fooObject = GraphQLObjectType('FooObject',
                                      {'bar': GraphQLField(GraphQLString)},
                                      interfaces=[fooInterface])

        schema = GraphQLSchema(GraphQLObjectType(
            'Query', {
                'foo': GraphQLField(fooInterface,
                                    resolve=lambda *_args: 'dummy')
            }),
                               types=[fooObject])

        result = graphql_sync(schema, '{ foo { bar } }')

        assert result == ({
            'foo': None
        }, [{
            'message':
            'Abstract type FooInterface must resolve to an Object type'
            " at runtime for field Query.foo with value 'dummy',"
            " received '[]'. Either the FooInterface type should provide"
            ' a "resolve_type" function or each possible type'
            ' should provide an "is_type_of" function.',
            'locations': [(1, 3)],
            'path': ['foo']
        }])
예제 #13
0
    def builds_a_schema_with_an_interface():
        friendly_type = GraphQLInterfaceType(
            "Friendly",
            lambda: {
                "bestFriend":
                GraphQLField(friendly_type,
                             description=
                             "The best friend of this friendly thing.")
            },
        )
        dog_type = GraphQLObjectType(
            "DogType",
            lambda: {"bestFriend": GraphQLField(friendly_type)},
            interfaces=[friendly_type],
        )
        human_type = GraphQLObjectType(
            "Human",
            lambda: {"bestFriend": GraphQLField(friendly_type)},
            interfaces=[friendly_type],
        )
        schema = GraphQLSchema(
            GraphQLObjectType("WithInterface",
                              {"friendly": GraphQLField(friendly_type)}),
            types=[dog_type, human_type],
        )

        check_schema(schema)
예제 #14
0
    def returning_invalid_value_from_resolve_type_yields_useful_error():
        fooInterface = GraphQLInterfaceType(
            "FooInterface",
            {"bar": GraphQLField(GraphQLString)},
            resolve_type=lambda *_args: [],
        )

        fooObject = GraphQLObjectType(
            "FooObject", {"bar": GraphQLField(GraphQLString)}, interfaces=[fooInterface]
        )

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Query",
                {"foo": GraphQLField(fooInterface, resolve=lambda *_args: "dummy")},
            ),
            types=[fooObject],
        )

        result = graphql_sync(schema, "{ foo { bar } }")

        assert result == (
            {"foo": None},
            [
                {
                    "message": "Abstract type FooInterface must resolve to an"
                    " Object type at runtime for field Query.foo with value 'dummy',"
                    " received '[]'. Either the FooInterface type should provide"
                    ' a "resolve_type" function or each possible type'
                    ' should provide an "is_type_of" function.',
                    "locations": [(1, 3)],
                    "path": ["foo"],
                }
            ],
        )
def test_prints_interface():
    FooType = GraphQLInterfaceType(
        name='Foo',
        resolve_type=lambda *_: None,
        fields={
            'str': GraphQLField(GraphQLString)
        }
    )

    BarType = GraphQLObjectType(
        name='Bar',
        fields={
            'str': GraphQLField(GraphQLString),
        },
        interfaces=[FooType]
    )

    Root = GraphQLObjectType(
        name='Root',
        fields={
            'bar': GraphQLField(BarType)
        }
    )

    Schema = GraphQLSchema(Root, types=[BarType])
    output = print_for_test(Schema)

    assert output == '''
예제 #16
0
def test_builds_a_schema_with_an_interface():
    FriendlyType = GraphQLInterfaceType(
        name="Friendly",
        resolve_type=lambda: None,
        fields=lambda: {
            "bestFriend":
            GraphQLField(FriendlyType,
                         description="The best friend of this friendly thing.")
        },
    )

    DogType = GraphQLObjectType(
        name="DogType",
        interfaces=[FriendlyType],
        fields=lambda: {"bestFriend": GraphQLField(FriendlyType)},
    )

    HumanType = GraphQLObjectType(
        name="Human",
        interfaces=[FriendlyType],
        fields=lambda: {"bestFriend": GraphQLField(FriendlyType)},
    )

    schema = GraphQLSchema(
        query=GraphQLObjectType(
            name="WithInterface",
            fields={"friendly": GraphQLField(FriendlyType)}),
        types=[DogType, HumanType],
    )

    _test_schema(schema)
예제 #17
0
    def prints_interface():
        FooType = GraphQLInterfaceType(
            name="Foo", fields={"str": GraphQLField(GraphQLString)}
        )

        BarType = GraphQLObjectType(
            name="Bar",
            fields={"str": GraphQLField(GraphQLString)},
            interfaces=[FooType],
        )

        Root = GraphQLObjectType(name="Root", fields={"bar": GraphQLField(BarType)})

        Schema = GraphQLSchema(Root, types=[BarType])
        output = print_for_test(Schema)
        assert output == dedent(
            """
            schema {
              query: Root
            }

            type Bar implements Foo {
              str: String
            }

            interface Foo {
              str: String
            }

            type Root {
              bar: Bar
            }
            """
        )
    def prints_interface():
        foo_type = GraphQLInterfaceType(
            name="Foo", fields={"str": GraphQLField(GraphQLString)})

        bar_type = GraphQLObjectType(
            name="Bar",
            fields={"str": GraphQLField(GraphQLString)},
            interfaces=[foo_type],
        )

        query = GraphQLObjectType(name="Query",
                                  fields={"bar": GraphQLField(bar_type)})

        schema = GraphQLSchema(query, types=[bar_type])
        output = print_for_test(schema)
        assert output == dedent("""
            type Bar implements Foo {
              str: String
            }

            interface Foo {
              str: String
            }

            type Query {
              bar: Bar
            }
            """)
예제 #19
0
    def uses_a_custom_type_resolver():
        document = parse("{ foo { bar } }")

        foo_interface = GraphQLInterfaceType(
            "FooInterface", {"bar": GraphQLField(GraphQLString)})

        foo_object = GraphQLObjectType("FooObject",
                                       {"bar": GraphQLField(GraphQLString)},
                                       [foo_interface])

        schema = GraphQLSchema(
            GraphQLObjectType("Query", {"foo": GraphQLField(foo_interface)}),
            types=[foo_object],
        )

        possible_types = None

        def type_resolver(_source, info, abstract_type):
            # Resolver should be able to figure out all possible types on its own
            nonlocal possible_types
            possible_types = info.schema.get_possible_types(abstract_type)
            return "FooObject"

        root_value = {"foo": {"bar": "bar"}}
        result = execute(schema,
                         document,
                         root_value,
                         type_resolver=type_resolver)

        assert result == ({"foo": {"bar": "bar"}}, None)
        assert possible_types == [foo_object]
 def implementation_is_subtype_of_interface():
     iface = GraphQLInterfaceType(
         'Interface', {'field': GraphQLField(GraphQLString)})
     impl = GraphQLObjectType(
         'Object',
         fields={'field': GraphQLField(GraphQLString)},
         interfaces=[iface])
     schema = test_schema(impl)
     assert is_type_sub_type_of(schema, impl, iface)
예제 #21
0
    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)) == [{
            'message':
            'We are testing this error',
            'locations': [(3, 15)],
            'path': ['pets', 0]
        }, {
            'message':
            'We are testing this error',
            'locations': [(3, 15)],
            'path': ['pets', 1]
        }]
예제 #22
0
 def schema_with_interface_field_of_type(field_type):
     BadInterfaceType = GraphQLInterfaceType('BadInterface', {
         'badField': GraphQLField(field_type)})
     BadImplementingType = GraphQLObjectType('BadImplementing', {
         'badField': GraphQLField(field_type)},
         interfaces=[BadInterfaceType])
     return GraphQLSchema(GraphQLObjectType('Query', {
         'f': GraphQLField(BadInterfaceType)}),
         types=[BadImplementingType, SomeObjectType])
예제 #23
0
 def rejects_an_interface_type_with_an_incorrect_type_for_resolve_type():
     with raises(TypeError) as exc_info:
         # noinspection PyTypeChecker
         GraphQLInterfaceType("AnotherInterface", {}, resolve_type={})
     msg = str(exc_info.value)
     assert msg == (
         "AnotherInterface must provide 'resolve_type' as a function,"
         " but got: {}."
     )
예제 #24
0
 def includes_interfaces_thunk_subtypes_in_the_type_map():
     SomeInterface = GraphQLInterfaceType('SomeInterface',
                                          {'f': GraphQLField(GraphQLInt)})
     SomeSubtype = GraphQLObjectType('SomeSubtype',
                                     {'f': GraphQLField(GraphQLInt)},
                                     interfaces=lambda: [SomeInterface])
     schema = GraphQLSchema(query=GraphQLObjectType(
         'Query', {'iface': GraphQLField(SomeInterface)}),
                            types=[SomeSubtype])
     assert schema.type_map['SomeSubtype'] is SomeSubtype
예제 #25
0
 def implementation_is_subtype_of_interface():
     iface = GraphQLInterfaceType(
         "Interface", {"field": GraphQLField(GraphQLString)})
     impl = GraphQLObjectType(
         "Object",
         fields={"field": GraphQLField(GraphQLString)},
         interfaces=[iface],
     )
     schema = _test_schema(impl)
     assert is_type_sub_type_of(schema, impl, iface)
예제 #26
0
        def without_extensions():
            some_interface = GraphQLInterfaceType(
                "SomeInterface",
                {
                    "someField": GraphQLField(
                        dummy_type, {"someArg": GraphQLArgument(dummy_type)}
                    )
                },
            )

            assert some_interface.extensions is None
            some_field = some_interface.fields["someField"]
            assert some_field.extensions is None
            some_arg = some_field.args["someArg"]
            assert some_arg.extensions is None

            assert some_interface.to_kwargs()["extensions"] is None
            assert some_field.to_kwargs()["extensions"] is None
            assert some_arg.to_kwargs()["extensions"] is None
예제 #27
0
    def accepts_an_interface_type_defining_resolve_type():
        AnotherInterfaceType = GraphQLInterfaceType(
            "AnotherInterface", {"f": GraphQLField(GraphQLString)})

        schema = schema_with_field_type(
            GraphQLObjectType("SomeObject", {"f": GraphQLField(GraphQLString)},
                              [AnotherInterfaceType]))

        assert (schema.query_type.fields["field"].type.interfaces[0] is
                AnotherInterfaceType)
예제 #28
0
    def accepts_an_interface_type_defining_resolve_type():
        AnotherInterfaceType = GraphQLInterfaceType(
            'AnotherInterface', {'f': GraphQLField(GraphQLString)})

        schema = schema_with_field_type(
            GraphQLObjectType('SomeObject', {'f': GraphQLField(GraphQLString)},
                              [AnotherInterfaceType]))

        assert schema.query_type.fields['field'].type.interfaces[
            0] is AnotherInterfaceType
예제 #29
0
    async def is_type_of_with_no_suitable_type(sync):
        # added in GraphQL-core to improve coverage
        pet_type = GraphQLInterfaceType("Pet",
                                        {"name": GraphQLField(GraphQLString)})

        dog_type = GraphQLObjectType(
            "Dog",
            {
                "name": GraphQLField(GraphQLString),
                "woofs": GraphQLField(GraphQLBoolean),
            },
            interfaces=[pet_type],
            is_type_of=get_is_type_of(Cat, sync),
        )

        schema = GraphQLSchema(
            GraphQLObjectType(
                "Query",
                {
                    "pets":
                    GraphQLField(
                        GraphQLList(pet_type),
                        resolve=lambda *_args: [Dog("Odie", True)],
                    )
                },
            ),
            types=[dog_type],
        )

        query = """
            {
              pets {
                name
                ... on Dog {
                  woofs
                }
              }
            }
            """

        message = (
            "Abstract type 'Pet' must resolve to an Object type at runtime"
            " for field 'Query.pets'."
            " Either the 'Pet' type should provide a 'resolve_type' function"
            " or each possible type should provide an 'is_type_of' function.")
        assert await execute_query(sync, schema, query) == (
            {
                "pets": [None]
            },
            [{
                "message": message,
                "locations": [(3, 15)],
                "path": ["pets", 0]
            }],
        )
예제 #30
0
    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)