Ejemplo n.º 1
0
def is_schema_of_common_names(schema: GraphQLSchema) -> bool:
    """Check whether this schema uses the common naming convention.

    GraphQL schema define root types for each type of operation. These types are the
    same as any other type and can be named in any manner, however there is a common
    naming convention:

    schema {
      query: Query
      mutation: Mutation
      subscription: Subscription
    }

    When using this naming convention, the schema description can be omitted.
    """
    query_type = schema.get_query_type()
    if query_type and query_type.name != "Query":
        return False

    mutation_type = schema.get_mutation_type()
    if mutation_type and mutation_type.name != "Mutation":
        return False

    subscription_type = schema.get_subscription_type()
    return not subscription_type or subscription_type.name == "Subscription"
def execute_graphql(
    schema: GraphQLSchema,
    test_data: CommonTestData,
    client: OrientDB,
    sample_parameters: Dict[str, Any],
) -> FrozenSet[Tuple[FrozenSet[Tuple[str, Any]], int]]:
    """Compile GraphQL query to MATCH, execute it against the test_db, and return the results."""
    schema_based_type_equivalence_hints: Dict[
        Union[GraphQLInterfaceType, GraphQLObjectType], GraphQLUnionType
    ] = {}
    if test_data.type_equivalence_hints:
        # For test convenience, we accept the type equivalence hints in string form.
        # Here, we convert them to the required GraphQL types.
        for key, value in six.iteritems(test_data.type_equivalence_hints):
            key_type = schema.get_type(key)
            value_type = schema.get_type(value)
            if (
                key_type
                and value_type
                and (
                    isinstance(key_type, GraphQLInterfaceType)
                    or isinstance(key_type, GraphQLObjectType)
                )
                and isinstance(value_type, GraphQLUnionType)
            ):
                schema_based_type_equivalence_hints[key_type] = value_type
            else:
                raise AssertionError(
                    "Expected key_type to be of type GraphQLInterfaceType or GraphQLObject Type, "
                    "but received {}; and value_type to be of type GraphQLUnionType, but "
                    "received {}.".format(type(key_type), type(value_type))
                )

    common_schema_info = CommonSchemaInfo(schema, schema_based_type_equivalence_hints)
    result = graphql_to_match(common_schema_info, test_data.graphql_input, sample_parameters)

    # We need to preprocess the results to be agnostic of the returned order.
    # For this we perform the following steps
    # - convert lists (returned from @fold scopes) to tuples to make them hashable
    # - convert each row dict to a frozenset of its items
    # - create a Counter (multi-set) of the row frozensets
    # - convert the multi-set to a frozenset of its items
    row_dicts = [row.oRecordData for row in client.command(result.query)]
    if len(row_dicts) == 0:
        raise AssertionError("Zero records returned. Trivial snapshot not allowed.")
    row_dicts_using_tuples = [
        {
            column_name: convert_decimals_to_strings(
                tuple(value) if isinstance(value, list) else value
            )
            for column_name, value in row.items()
        }
        for row in row_dicts
    ]
    row_frozensets = [frozenset(row_dict.items()) for row_dict in row_dicts_using_tuples]
    rows_multiset = Counter(row_frozensets)
    row_counters_frozenset = frozenset(rows_multiset.items())

    return row_counters_frozenset
Ejemplo n.º 3
0
def print_schema_definition(schema: GraphQLSchema) -> Optional[str]:
    operation_types = []

    query_type = schema.get_query_type()
    if query_type:
        operation_types.append(f"  query: {query_type.name}")

    mutation_type = schema.get_mutation_type()
    if mutation_type:
        operation_types.append(f"  mutation: {mutation_type.name}")

    subscription_type = schema.get_subscription_type()
    if subscription_type:
        operation_types.append(f"  subscription: {subscription_type.name}")

    return "schema {\n" + "\n".join(operation_types) + "\n}"
Ejemplo n.º 4
0
def print_filtered_schema(
    schema: GraphQLSchema,
    directive_filter: Callable[[GraphQLDirective], bool],
    type_filter: Callable[[GraphQLNamedType], bool],
) -> str:
    directives = filter(directive_filter, schema.get_directives())
    types = filter(
        type_filter,
        cast(List[GraphQLNamedType],
             schema.get_type_map().values()))

    return "\n\n".join((
        *filter(None, (print_schema_definition(schema), )),
        *map(print_directive, directives),
        *map(print_type, types),
    ))
Ejemplo n.º 5
0
def graphql_ast_flatten_field(field: Field,
                              fragments: Dict[str, FragmentDefinition], schema,
                              root_schema: GraphQLSchema) -> List[str]:
    results = []
    # is_list = isinstance(schema, GraphQLList)
    list_count = 0
    while True:
        schema_changed = False
        if isinstance(schema, GraphQLNonNull):
            schema = schema.of_type
            schema_changed = True
        if isinstance(schema, GraphQLList):
            list_count += 1
            schema = schema.of_type
            schema_changed = True
        if not schema_changed:
            break
    if getattr(field, 'selection_set', None) is not None:
        for sub_field in field.selection_set.selections:
            if isinstance(sub_field, FragmentSpread):
                sub_field = fragments[sub_field.name.value]
                sub_field_schema = schema
            else:
                sub_field_schema = graphql_ast_get_subfield(
                    schema, sub_field.name.value)
                if type(sub_field_schema) == str:
                    sub_field_schema = root_schema.get_type(sub_field_schema)
            sub_field_results = graphql_ast_flatten_field(
                sub_field, fragments, sub_field_schema, root_schema)
            if isinstance(field, FragmentDefinition):
                results += sub_field_results
            else:
                for result in sub_field_results:
                    results.append(
                        f"{change_case(field.name.value)}{'[*]' * list_count}.{result}"
                    )
    else:
        results.append(change_case(field.name.value))
    return results
Ejemplo n.º 6
0
            type_=GraphQLString,
            args={"who": GraphQLArgument(GraphQLString)},
            resolve=lambda obj, info, who=None: "Hello %s" % (who or "World"),
        ),
    },
)

MutationRootType = GraphQLObjectType(
    name="MutationRoot",
    fields={
        "writeTest":
        GraphQLField(type_=QueryRootType, resolve=lambda *_: QueryRootType)
    },
)

Schema = GraphQLSchema(QueryRootType, MutationRootType)


# Schema with async methods
async def resolver_field_async_1(_obj, info):
    await asyncio.sleep(0.001)
    return "hey"


async def resolver_field_async_2(_obj, info):
    await asyncio.sleep(0.003)
    return "hey2"


def resolver_field_sync(_obj, info):
    return "hey3"
Ejemplo n.º 7
0
def resolve_raises(*_):
    raise Exception("Throws!")


QueryRootType = GraphQLObjectType(
    name='QueryRoot',
    fields={
        'thrower':
        GraphQLField(GraphQLNonNull(GraphQLString), resolver=resolve_raises),
        'request':
        GraphQLField(
            GraphQLNonNull(GraphQLString),
            resolver=lambda obj, args, context, info: context.args.get('q')),
        'test':
        GraphQLField(type=GraphQLString,
                     args={'who': GraphQLArgument(GraphQLString)},
                     resolver=lambda obj, args, context, info: 'Hello %s' %
                     (args.get('who') or 'World'))
    })

MutationRootType = GraphQLObjectType(name='MutationRoot',
                                     fields={
                                         'writeTest':
                                         GraphQLField(
                                             type=QueryRootType,
                                             resolver=lambda *_: QueryRootType)
                                     })

Schema = GraphQLSchema(QueryRootType, MutationRootType)
Ejemplo n.º 8
0
    name="MutationRoot",
    fields={
        "writeTest":
        GraphQLField(type_=QueryRootType, resolve=lambda *args: QueryRootType)
    },
)

SubscriptionsRootType = GraphQLObjectType(
    name="SubscriptionsRoot",
    fields={
        "subscriptionsTest":
        GraphQLField(type_=QueryRootType, resolve=lambda *args: QueryRootType)
    },
)

Schema = GraphQLSchema(QueryRootType, MutationRootType, SubscriptionsRootType)


# Schema with async methods
async def resolver_field_async_1(_obj, info):
    await asyncio.sleep(0.001)
    return "hey"


async def resolver_field_async_2(_obj, info):
    await asyncio.sleep(0.003)
    return "hey2"


def resolver_field_sync(_obj, info):
    return "hey3"
Ejemplo n.º 9
0
from queries import QueryRootType
from graphql.type.schema import GraphQLSchema

schema = GraphQLSchema(QueryRootType)
                                "Node",
                                {
                                    "id": GraphQLField(GraphQLID),
                                    "name": GraphQLField(GraphQLString),
                                },
                            ))
                    },
                )))
    },
)

schema = GraphQLSchema(
    GraphQLObjectType(
        "QueryRoot",
        {
            "someBox": GraphQLField(SomeBox),
            "connection": GraphQLField(Connection)
        },
    ),
    types=[IntBox, StringBox, NonNullStringBox1Impl, NonNullStringBox2Impl],
)


def test_conflicting_return_types_which_potentially_overlap():
    expect_fails_rule_with_schema(
        schema,
        OverlappingFieldsCanBeMerged,
        """
    {
        someBox {
            ...on IntBox {
                scalar
Ejemplo n.º 11
0
    'deepBox': GraphQLField(StringBox),
}, interfaces=[SomeBox, NonNullStringBox2])

Connection = GraphQLObjectType('Connection', {
    'edges': GraphQLField(GraphQLList(GraphQLObjectType('Edge', {
        'node': GraphQLField(GraphQLObjectType('Node', {
            'id': GraphQLField(GraphQLID),
            'name': GraphQLField(GraphQLString)
        }))
    })))
})

schema = GraphQLSchema(
    GraphQLObjectType('QueryRoot', {
        'someBox': GraphQLField(SomeBox),
        'connection': GraphQLField(Connection),
    }),
    types=[IntBox, StringBox, NonNullStringBox1Impl, NonNullStringBox2Impl]
)


def test_conflicting_return_types_which_potentially_overlap():
    expect_fails_rule_with_schema(schema, OverlappingFieldsCanBeMerged, '''
    {
        someBox {
            ...on IntBox {
                scalar
            }
            ...on NonNullStringBox1 {
                scalar
            }
from graphql.type.definition import GraphQLArgument, GraphQLField, GraphQLNonNull, GraphQLObjectType
from graphql.type.scalars import GraphQLString, GraphQLBoolean
from graphql.type.schema import GraphQLSchema

Query = GraphQLObjectType(
    name='Query',
    fields={
        'testString':
        GraphQLField(
            GraphQLNonNull(GraphQLString),
            resolver=lambda root, args, context, info: 'string returned')
    })

Subscription = GraphQLObjectType(
    name='Subscription',
    fields={
        'test_subscription':
        GraphQLField(type=GraphQLNonNull(GraphQLString),
                     resolver=lambda root, args, context, info: root),
        'test_filter_sub':
        GraphQLField(type=GraphQLNonNull(GraphQLString),
                     args={'filter_bool': GraphQLArgument(GraphQLBoolean)},
                     resolver=lambda root, args, context, info: 'SUCCESS'),
    })

Schema = GraphQLSchema(Query, subscription=Subscription)