Exemplo n.º 1
0
    def _inject_introspection_fields(self) -> None:
        """
        Injects introspection fields to the query type and to defined object
        and union types.
        """
        query_type = self.type_definitions.get(self.query_operation_name)
        if not query_type:
            return

        query_type.add_field(
            SCHEMA_ROOT_FIELD_DEFINITION(
                gql_type=GraphQLNonNull("__Schema", schema=self)
            )
        )
        query_type.add_field(prepare_type_root_field(self))

        for type_definition in self.type_definitions.values():
            try:
                type_definition.add_field(
                    TYPENAME_ROOT_FIELD_DEFINITION(
                        gql_type=GraphQLNonNull(gql_type="String", schema=self)
                    )
                )
            except AttributeError:
                pass
Exemplo n.º 2
0
def test_graphql_non_null_eq():
    non_null = GraphQLNonNull(gql_type="Name", description="description")

    ## Same
    assert non_null == non_null
    assert non_null == GraphQLNonNull(gql_type="Name",
                                      description="description")
    # Currently we ignore the description in comparing
    assert non_null == GraphQLNonNull(gql_type="Name")

    ## Different
    assert non_null != GraphQLNonNull(gql_type="OtherName")
Exemplo n.º 3
0
def schema_type_from_ast(
    schema: "GraphQLSchema",
    type_node: Union["ListTypeNode", "NonNullTypeNode", "NamedTypeNode"],
) -> Optional[Union["GraphQLList", "GraphQLNonNull", "GraphQLType"]]:
    """
    Given a Schema and an AST node describing a type, return a GraphQLType
    definition which applies to that type.
    :param schema: schema instance to use
    :param type_node: AST node describing a type
    :type schema: GraphQLSchema
    :type type_node: Union[ListTypeNode, NonNullTypeNode, NamedTypeNode]
    :return: a GraphQLType definition which applies to that type or None
    :rtype: Optional[Union[GraphQLList, GraphQLNonNull, GraphQLType]]
    """
    if isinstance(type_node, ListTypeNode):
        inner_type = schema_type_from_ast(schema, type_node.type)
        return GraphQLList(inner_type) if inner_type else None
    if isinstance(type_node, NonNullTypeNode):
        inner_type = schema_type_from_ast(schema, type_node.type)
        return GraphQLNonNull(inner_type) if inner_type else None
    if isinstance(type_node, NamedTypeNode):
        try:
            return schema.find_type(type_node.name.value)
        except KeyError:
            pass
        return None
    raise TypeError(f"Unexpected type kind: {type_node.__class__.__name__}")
Exemplo n.º 4
0
    def inject_introspection(self) -> None:
        self._gql_types[self.query_type].add_field(
            SCHEMA_ROOT_FIELD_DEFINITION(
                gql_type=GraphQLNonNull("__Schema", schema=self)))
        self._gql_types[self.query_type].add_field(
            prepare_type_root_field(self))

        for gql_type in self._gql_types.values():
            try:
                __typename = TYPENAME_ROOT_FIELD_DEFINITION(
                    schema=self,
                    gql_type=GraphQLNonNull(gql_type="String", schema=self),
                )
                gql_type.add_field(__typename)
            except AttributeError:
                pass
Exemplo n.º 5
0
def test_resolver_factory__list_and_null_coercer():
    from tartiflette.utils.coercer import _list_and_null_coercer
    from tartiflette.utils.coercer import _list_coercer, _not_null_coercer
    from tartiflette.types.list import GraphQLList
    from tartiflette.types.non_null import GraphQLNonNull

    def lol():
        pass

    assert _list_and_null_coercer("aType", lol) is lol
    assert _list_and_null_coercer(None, lol) is lol

    a = _list_and_null_coercer(GraphQLList(gql_type="aType"), lol)

    assert a.func is _list_coercer
    assert lol in a.args

    a = _list_and_null_coercer(GraphQLNonNull(gql_type="aType"), lol)

    assert a.func is _not_null_coercer
    assert lol in a.args

    a = _list_and_null_coercer(
        GraphQLList(gql_type=GraphQLNonNull(gql_type="aType")), lol
    )

    assert a.func is _list_coercer
    a1, = a.args
    assert a1.func is _not_null_coercer
    assert lol in a1.args

    a = _list_and_null_coercer(
        GraphQLNonNull(
            gql_type=GraphQLList(gql_type=GraphQLNonNull(gql_type="aType"))
        ),
        lol,
    )

    assert a.func is _not_null_coercer
    a1, = a.args
    assert a1.func is _list_coercer
    a1, = a1.args
    assert a1.func is _not_null_coercer
    assert lol in a1.args
Exemplo n.º 6
0
def test_resolver_factory__get_type_coercers():
    from tartiflette.resolver.factory import _get_type_coercers
    from tartiflette.types.list import GraphQLList
    from tartiflette.types.non_null import GraphQLNonNull
    from tartiflette.resolver.factory import _list_coercer, _not_null_coercer

    assert _get_type_coercers("aType") == []
    assert _get_type_coercers(None) == []
    assert _get_type_coercers(GraphQLList(gql_type="aType")) == [_list_coercer]
    assert _get_type_coercers(
        GraphQLNonNull(gql_type="aType")) == [_not_null_coercer]
    assert _get_type_coercers(
        GraphQLList(gql_type=GraphQLNonNull(gql_type="aType"))) == [
            _list_coercer, _not_null_coercer
        ]
    assert _get_type_coercers(
        GraphQLNonNull(gql_type=GraphQLList(gql_type=GraphQLNonNull(
            gql_type="aType")))) == [
                _not_null_coercer, _list_coercer, _not_null_coercer
            ]
Exemplo n.º 7
0
def test_utils_coercers__get_type_coercers():
    from tartiflette.utils.coercer import _get_type_coercers
    from tartiflette.types.list import GraphQLList
    from tartiflette.types.non_null import GraphQLNonNull
    from tartiflette.utils.coercer import _list_coercer, _not_null_coercer

    assert _get_type_coercers("aType") == []
    assert _get_type_coercers(None) == []
    assert _get_type_coercers(GraphQLList(gql_type="aType")) == [_list_coercer]
    assert _get_type_coercers(
        GraphQLNonNull(gql_type="aType")) == [_not_null_coercer]
    assert _get_type_coercers(
        GraphQLList(gql_type=GraphQLNonNull(gql_type="aType"))) == [
            _list_coercer, _not_null_coercer
        ]
    assert _get_type_coercers(
        GraphQLNonNull(gql_type=GraphQLList(gql_type=GraphQLNonNull(
            gql_type="aType")))) == [
                _not_null_coercer, _list_coercer, _not_null_coercer
            ]
Exemplo n.º 8
0
def test_resolver_factory__resolver_executor_update_prop_contains_not_null(
        _resolver_executor_mock):
    from tartiflette.types.field import GraphQLField
    from tartiflette.types.non_null import GraphQLNonNull
    from tartiflette.types.list import GraphQLList

    _resolver_executor_mock._schema_field = GraphQLField("A", gql_type="F")

    assert not _resolver_executor_mock.contains_not_null
    _resolver_executor_mock._schema_field = GraphQLField(
        "A", gql_type=GraphQLNonNull(gql_type="F"))
    assert _resolver_executor_mock.contains_not_null

    _resolver_executor_mock._schema_field = GraphQLField(
        "A", gql_type=GraphQLList(gql_type=GraphQLNonNull(gql_type="F")))
    assert _resolver_executor_mock.contains_not_null

    _resolver_executor_mock._schema_field = GraphQLField(
        "A", gql_type=GraphQLList(gql_type="F"))
    assert not _resolver_executor_mock.contains_not_null
Exemplo n.º 9
0
def prepare_type_root_field(schema: "GraphQLSchema") -> "GraphQLField":
    return GraphQLField(
        name="__type",
        description="Request the type information of a single type.",
        arguments={
            "name": GraphQLArgument(
                name="name",
                gql_type=GraphQLNonNull("String", schema=schema),
                schema=schema,
            )
        },
        gql_type="__Type",
        resolver=__type_resolver,
        schema=schema,
    )
Exemplo n.º 10
0
def test_graphql_non_null_nested_repr():
    non_null = GraphQLNonNull(gql_type="Name", description="description")

    assert non_null.__repr__() == "GraphQLNonNull(gql_type='Name', " \
                                  "description='description')"
    assert non_null == eval(repr(non_null))

    # Test nested types
    non_null = GraphQLNonNull(gql_type=GraphQLNonNull(gql_type="Name"),
                              description="description")

    assert non_null.__repr__() == "GraphQLNonNull(gql_type=" \
                             "GraphQLNonNull(gql_type='Name', description=None), " \
                             "description='description')"
    assert non_null == eval(repr(non_null))
Exemplo n.º 11
0
def prepare_type_root_field(schema: "GraphQLSchema") -> "GraphQLField":
    """
    Factory to generate a `__type` field.
    :param schema: the GraphQLSchema instance linked to the engine
    :type schema: GraphQLSchema
    :return: the `__type` field
    :rtype: GraphQLField
    """
    return GraphQLField(
        name="__type",
        description="Request the type information of a single type.",
        arguments={
            "name":
            GraphQLArgument(name="name",
                            gql_type=GraphQLNonNull("String", schema=schema))
        },
        gql_type="__Type",
        resolver=__type_resolver,
    )
Exemplo n.º 12
0
def test_graphql_non_null_init():
    non_null = GraphQLNonNull(gql_type="Name", description="description")

    assert non_null.gql_type == "Name"
    assert non_null.description == "description"
Exemplo n.º 13
0
async def test_build_schema(monkeypatch, clean_registry):
    from tartiflette.resolver.factory import ResolverExecutorFactory
    from tartiflette.engine import _import_builtins

    resolver_excutor = Mock()
    monkeypatch.setattr(
        ResolverExecutorFactory,
        "get_resolver_executor",
        Mock(return_value=resolver_excutor),
    )

    from tartiflette.schema.bakery import SchemaBakery
    from tartiflette.types.argument import GraphQLArgument
    from tartiflette.types.field import GraphQLField
    from tartiflette.types.input_object import GraphQLInputObjectType
    from tartiflette.types.interface import GraphQLInterfaceType
    from tartiflette.types.list import GraphQLList
    from tartiflette.types.non_null import GraphQLNonNull
    from tartiflette.types.object import GraphQLObjectType
    from tartiflette.types.union import GraphQLUnionType

    schema_sdl = """
    schema @enable_cache {
        query: RootQuery
        mutation: RootMutation
        subscription: RootSubscription
    }

    union Group = Foo | Bar | Baz

    interface Something {
        oneField: [Int]
        anotherField: [String]
        aLastOne: [[Date!]]!
    }

    input UserInfo {
        name: String
        dateOfBirth: [Date]
        graphQLFan: Boolean!
    }

    # directive @partner(goo: Anything) on ENUM_VALUE

    \"\"\"
    This is a docstring for the Test Object Type.
    \"\"\"
    type Test implements Unknown & Empty{
        \"\"\"
        This is a field description :D
        \"\"\"
        field(input: InputObject): String!
        anotherField: [Int]
        fieldWithDefaultValueArg(test: String = "default"): ID
        simpleField: Date
    }
    """
    _, schema_sdl = await _import_builtins([], schema_sdl, "G")
    _, schema_E = await _import_builtins([], "", "E")
    clean_registry.register_sdl("G", schema_sdl)
    clean_registry.register_sdl("E", schema_E)
    generated_schema = SchemaBakery._preheat("G")
    expected_schema = SchemaBakery._preheat("E")
    expected_schema.query_type = "RootQuery"
    expected_schema.mutation_type = "RootMutation"
    expected_schema.subscription_type = "RootSubscription"

    expected_schema.add_definition(
        GraphQLUnionType(name="Group", gql_types=["Foo", "Bar", "Baz"]))
    expected_schema.add_definition(
        GraphQLInterfaceType(
            name="Something",
            fields=OrderedDict(
                oneField=GraphQLField(name="oneField",
                                      gql_type=GraphQLList(gql_type="Int")),
                anotherField=GraphQLField(
                    name="anotherField",
                    gql_type=GraphQLList(gql_type="String"),
                ),
                aLastOne=GraphQLField(
                    name="aLastOne",
                    gql_type=GraphQLNonNull(gql_type=GraphQLList(
                        gql_type=GraphQLList(gql_type=GraphQLNonNull(
                            gql_type="Date")))),
                ),
            ),
        ))
    expected_schema.add_definition(
        GraphQLInputObjectType(
            name="UserInfo",
            fields=OrderedDict([
                ("name", GraphQLArgument(name="name", gql_type="String")),
                (
                    "dateOfBirth",
                    GraphQLArgument(
                        name="dateOfBirth",
                        gql_type=GraphQLList(gql_type="Date"),
                    ),
                ),
                (
                    "graphQLFan",
                    GraphQLArgument(
                        name="graphQLFan",
                        gql_type=GraphQLNonNull(gql_type="Boolean"),
                    ),
                ),
            ]),
        ))
    expected_schema.add_definition(
        GraphQLObjectType(
            name="Test",
            fields=OrderedDict([
                (
                    "field",
                    GraphQLField(
                        name="field",
                        gql_type=GraphQLNonNull(gql_type="String"),
                        arguments=OrderedDict(input=GraphQLArgument(
                            name="input", gql_type="InputObject")),
                    ),
                ),
                (
                    "anotherField",
                    GraphQLField(
                        name="anotherField",
                        gql_type=GraphQLList(gql_type="Int"),
                    ),
                ),
                (
                    "fieldWithDefaultValueArg",
                    GraphQLField(
                        name="fieldWithDefaultValueArg",
                        gql_type="ID",
                        arguments=OrderedDict(test=GraphQLArgument(
                            name="test",
                            gql_type="String",
                            default_value="default",
                        )),
                    ),
                ),
                (
                    "simpleField",
                    GraphQLField(name="simpleField", gql_type="Date"),
                ),
            ]),
            interfaces=["Unknown", "Empty"],
        ))

    assert 5 < len(generated_schema._gql_types)
    assert len(expected_schema._gql_types) == len(generated_schema._gql_types)

    monkeypatch.undo()
Exemplo n.º 14
0
def test_build_schema():
    schema_sdl = """
    schema @enable_cache {
        query: RootQuery
        mutation: RootMutation
        subscription: RootSubscription
    }
    
    scalar Date
    
    union Group = Foo | Bar | Baz
    
    interface Something {
        oneField: [Int]
        anotherField: [String]
        aLastOne: [[Date!]]!
    }
    
    input UserInfo {
        name: String
        dateOfBirth: [Date]
        graphQLFan: Boolean!
    }
    
    # directive @partner(goo: Anything) on ENUM_VALUE
    
    \"\"\"
    This is a docstring for the Test Object Type.
    \"\"\"
    type Test implements Unknown & Empty @enable_cache {
        \"\"\"
        This is a field description :D
        \"\"\"
        field(input: InputObject): String! @deprecated(reason: "Useless field")
        anotherField: [Int] @something(
            lst: ["about" "stuff"]
            obj: {some: [4, 8, 16], complex: {about: 19.4}, another: EnumVal}
        )
        fieldWithDefaultValueArg(test: String = "default"): ID
        simpleField: Date
    }
    """

    generated_schema = build_graphql_schema_from_sdl(schema_sdl,
                                                     schema=GraphQLSchema())

    expected_schema = GraphQLSchema()
    expected_schema.query_type = "RootQuery"
    expected_schema.mutation_type = "RootMutation"
    expected_schema.subscription_type = "RootSubscription"

    expected_schema.add_definition(GraphQLScalarType(name="Date"))
    expected_schema.add_definition(GraphQLUnionType(name="Group", gql_types=[
        "Foo",
        "Bar",
        "Baz",
    ]))
    expected_schema.add_definition(GraphQLInterfaceType(name="Something", fields=OrderedDict(
        oneField=GraphQLField(name="oneField", gql_type=GraphQLList(gql_type="Int")),
        anotherField=GraphQLField(name="anotherField", gql_type=GraphQLList(gql_type="String")),
        aLastOne=GraphQLField(name="aLastOne", gql_type=GraphQLNonNull(gql_type=GraphQLList(gql_type=GraphQLList(gql_type=GraphQLNonNull(gql_type="Date"))))),
    )))
    expected_schema.add_definition(GraphQLInputObjectType(name="UserInfo", fields=OrderedDict([
        ('name', GraphQLArgument(name="name", gql_type="String")),
        ('dateOfBirth', GraphQLArgument(name="dateOfBirth", gql_type=GraphQLList(gql_type="Date"))),
        ('graphQLFan', GraphQLArgument(name="graphQLFan", gql_type=GraphQLNonNull(gql_type="Boolean"))),
    ])))
    expected_schema.add_definition(GraphQLObjectType(name="Test", fields=OrderedDict([
        ('field', GraphQLField(name="field", gql_type=GraphQLNonNull(gql_type="String"), arguments=OrderedDict(
            input=GraphQLArgument(name="input", gql_type="InputObject"),
        ))),
        ('anotherField', GraphQLField(name="anotherField", gql_type=GraphQLList(gql_type="Int"))),
        ('fieldWithDefaultValueArg', GraphQLField(name="fieldWithDefaultValueArg", gql_type="ID", arguments=OrderedDict(
            test=GraphQLArgument(name="test", gql_type="String", default_value="default"),
        ))),
        ('simpleField', GraphQLField(name="simpleField", gql_type="Date")),
    ]),
                                                               interfaces=[
                                                                   "Unknown",
                                                                   "Empty",
                                                               ]))

    assert expected_schema == generated_schema
    assert len(generated_schema._gql_types) > 5
    assert len(generated_schema._gql_types) == len(expected_schema._gql_types)
    # Only the default types should be in the schema
    assert len(DefaultGraphQLSchema._gql_types) == 5
Exemplo n.º 15
0
 def non_null_type(self, tree: Tree) -> SchemaNode:
     return SchemaNode(
         "non_null_type",
         GraphQLNonNull(gql_type=tree.children[0].value,
                        schema=self._schema),
     )
Exemplo n.º 16
0
 def non_null_type(self, tree: Tree) -> SchemaNode:
     return SchemaNode('non_null_type',
                       GraphQLNonNull(gql_type=tree.children[0].value))
Exemplo n.º 17
0
import pytest

from tartiflette.types.helpers import reduce_type
from tartiflette.types.list import GraphQLList
from tartiflette.types.non_null import GraphQLNonNull


@pytest.mark.parametrize(
    "gql_type,expected",
    [
        (GraphQLNonNull(gql_type="MyObject"), "MyObject"),
        (GraphQLList(gql_type="MyObject"), "MyObject"),
        (
            GraphQLList(gql_type=GraphQLNonNull(gql_type="MyObject")),
            "MyObject",
        ),
        (
            GraphQLNonNull(gql_type=GraphQLList(gql_type=GraphQLNonNull(
                gql_type="LeafType"))),
            "LeafType",
        ),
    ],
)
def test_reduce_type(gql_type, expected):
    reduced_gql_type = reduce_type(gql_type)
    assert reduced_gql_type == expected
Exemplo n.º 18
0
        lol,
    )

    assert a.func is _not_null_coercer
    a1, = a.args
    assert a1.func is _list_coercer
    a1, = a1.args
    assert a1.func is _not_null_coercer
    assert lol in a1.args


@pytest.mark.parametrize(
    "field_type,expected",
    [
        (GraphQLList(gql_type="aType"), True),
        (GraphQLNonNull(gql_type="aType"), False),
        (GraphQLNonNull(gql_type=GraphQLList(gql_type="aType")), True),
        (None, False),
    ],
)
def test_resolver_factory__shall_return_a_list(field_type, expected):
    from tartiflette.resolver.factory import _shall_return_a_list

    assert _shall_return_a_list(field_type) == expected


def test_resolver_factory__enum_coercer_none():
    from tartiflette.resolver.factory import _enum_coercer

    assert _enum_coercer(None, None, None, None) is None