def resolve(self, next, root, info, **kwargs):
     context = info.context
     result = next(root, info, **kwargs)
     return result.then(
         lambda resolved: self.__process_value(resolved, root, info, **kwargs),
         lambda error: Promise.rejected(error)
     )
Esempio n. 2
0
def test_promise_repr_rejected():
    err = Exception("Error!")
    promise = Promise.rejected(err)
    promise._wait()
    assert repr(promise) == "<Promise at {} rejected with {}>".format(
        hex(id(promise)), repr(err)
    )
Esempio n. 3
0
def complete_value(exe_context, return_type, field_asts, info, result):
    """
    Implements the instructions for completeValue as defined in the
    "Field entries" section of the spec.

    If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field
    error if that completion returns null, as per the "Nullability" section of the spec.

    If the field type is a List, then this recursively completes the value for the inner type on each item in the
    list.

    If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the
    `serialize` method of GraphQL type definition.

    If the field is an abstract type, determine the runtime type of the value and then complete based on that type.

    Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all
    sub-selections.
    """
    # If field type is NonNull, complete for inner type, and throw field error if result is null.

    if is_thenable(result):
        return promisify(result).then(
            lambda resolved: complete_value(
                exe_context,
                return_type,
                field_asts,
                info,
                resolved
            ),
            lambda error: Promise.rejected(GraphQLLocatedError(field_asts, original_error=error))
        )

    # print return_type, type(result)
    if isinstance(result, Exception):
        raise GraphQLLocatedError(field_asts, original_error=result)

    if isinstance(return_type, GraphQLNonNull):
        return complete_nonnull_value(exe_context, return_type, field_asts, info, result)

    # If result is null-like, return null.
    if result is None:
        return None

    # If field type is List, complete each item in the list with the inner type
    if isinstance(return_type, GraphQLList):
        return complete_list_value(exe_context, return_type, field_asts, info, result)

    # If field type is Scalar or Enum, serialize to a valid value, returning null if coercion is not possible.
    if isinstance(return_type, (GraphQLScalarType, GraphQLEnumType)):
        return complete_leaf_value(return_type, result)

    if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)):
        return complete_abstract_value(exe_context, return_type, field_asts, info, result)

    if isinstance(return_type, GraphQLObjectType):
        return complete_object_value(exe_context, return_type, field_asts, info, result)

    assert False, u'Cannot complete value of unexpected type "{}".'.format(return_type)
Esempio n. 4
0
def test_rejected():
    p = Promise.rejected(Exception("Static rejected"))
    assert p.is_rejected
    assert_exception(p.reason, Exception, "Static rejected")
 def resolve(self, next, root, info, **kwargs):
     result = next(root, info, **kwargs)
     return result.then(
         lambda resolved: self.__process_value(resolved, root, info, **
                                               kwargs),
         lambda error: Promise.rejected(error))
Esempio n. 6
0
def complete_value(
        exe_context,  # type: ExecutionContext
        return_type,  # type: Any
        field_asts,  # type: List[Field]
        info,  # type: ResolveInfo
        path,  # type: List[Union[int, str]]
        result,  # type: Any
):
    # type: (...) -> Any
    """
    Implements the instructions for completeValue as defined in the
    "Field entries" section of the spec.

    If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field
    error if that completion returns null, as per the "Nullability" section of the spec.

    If the field type is a List, then this recursively completes the value for the inner type on each item in the
    list.

    If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the
    `serialize` method of GraphQL type definition.

    If the field is an abstract type, determine the runtime type of the value and then complete based on that type.

    Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all
    sub-selections.
    """
    # If field type is NonNull, complete for inner type, and throw field error
    # if result is null.
    if is_thenable(result):
        return Promise.resolve(result).then(
            lambda resolved: complete_value(exe_context, return_type,
                                            field_asts, info, path, resolved),
            lambda error: Promise.rejected(  # type: ignore
                GraphQLLocatedError(  # type: ignore
                    field_asts,
                    original_error=error,
                    path=path)),
        )

    # print return_type, type(result)
    if isinstance(result, Exception):
        raise GraphQLLocatedError(field_asts, original_error=result, path=path)

    if isinstance(return_type, GraphQLNonNull):
        return complete_nonnull_value(exe_context, return_type, field_asts,
                                      info, path, result)

    # If result is null-like, return null.
    if result is None:
        return None

    # If field type is List, complete each item in the list with the inner type
    if isinstance(return_type, GraphQLList):
        return complete_list_value(exe_context, return_type, field_asts, info,
                                   path, result)

    # If field type is Scalar or Enum, serialize to a valid value, returning
    # null if coercion is not possible.
    if isinstance(return_type, (GraphQLScalarType, GraphQLEnumType)):
        return complete_leaf_value(return_type, path, result)

    if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)):
        return complete_abstract_value(exe_context, return_type, field_asts,
                                       info, path, result)

    if isinstance(return_type, GraphQLObjectType):
        return complete_object_value(exe_context, return_type, field_asts,
                                     info, path, result)

    assert False, u'Cannot complete value of unexpected type "{}".'.format(
        return_type)
Esempio n. 7
0
def test_rejected():
    p = Promise.rejected(Exception("Static rejected"))
    assert p.is_rejected
    with raises(Exception) as exc_info:
        p.get()
    assert str(exc_info.value) == "Static rejected"
Esempio n. 8
0
def test_promise_repr_rejected():
    err = Exception("Error!")
    promise = Promise.rejected(err)
    promise._wait()
    assert repr(promise) == "<Promise at {} rejected with {}>".format(hex(id(promise)), repr(err))
Esempio n. 9
0
def rejected(error):
    return Promise.rejected(error)
Esempio n. 10
0
def rejected(error):
    # type: (Exception) -> Promise
    return Promise.rejected(error)
Esempio n. 11
0
def test_rejected():
    p = Promise.rejected(Exception("Static rejected"))
    assert p.is_rejected
    assert_exception(p.reason, Exception, "Static rejected")
    def subscribe(self, query, operation_name, callback, variables, context,
                  format_error, format_response):
        parsed_query = parse(query)
        rules = specified_rules + [SubscriptionHasSingleRootField]
        errors = validate(self.schema, parsed_query, rules=rules)

        if errors:
            return Promise.rejected(ValidationError(errors))

        args = {}

        subscription_name = ''

        for definition in parsed_query.definitions:

            if isinstance(definition, OperationDefinition):
                root_field = definition.selection_set.selections[0]
                subscription_name = root_field.name.value

                fields = self.schema.get_subscription_type().fields

                for arg in root_field.arguments:

                    arg_definition = [
                        arg_def for _, arg_def in fields.get(
                            subscription_name).args.iteritems()
                        if arg_def.out_name == arg.name.value
                    ][0]

                    args[arg_definition.out_name] = value_from_ast(
                        arg.value, arg_definition.type, variables=variables)

        if self.setup_funcs.get(to_snake_case(subscription_name)):
            trigger_map = self.setup_funcs[to_snake_case(subscription_name)](
                query=query,
                operation_name=operation_name,
                callback=callback,
                variables=variables,
                context=context,
                format_error=format_error,
                format_response=format_response,
                args=args,
                subscription_name=subscription_name)
        else:
            trigger_map = {}
            trigger_map[subscription_name] = {}

        external_subscription_id = self.max_subscription_id
        self.max_subscription_id += 1
        self.subscriptions[external_subscription_id] = []
        subscription_promises = []

        for trigger_name in trigger_map.viewkeys():
            try:
                channel_options = trigger_map[trigger_name].get(
                    'channel_options', {})
                filter = trigger_map[trigger_name].get('filter',
                                                       lambda arg1, arg2: True)

            # TODO: Think about this some more...the Apollo library
            # let's all messages through by default, even if
            # the users incorrectly uses the setup_funcs (does not
            # use 'filter' or 'channel_options' keys); I think it
            # would be better to raise an exception here
            except AttributeError:
                channel_options = {}

                def filter(arg1, arg2):
                    return True

            def on_message(root_value):
                def context_promise_handler(result):
                    if isinstance(context, FunctionType):
                        return context()
                    else:
                        return context

                def filter_func_promise_handler(context):
                    return Promise.all([context, filter(root_value, context)])

                def context_do_execute_handler(result):
                    context, do_execute = result
                    if not do_execute:
                        return
                    else:
                        return execute(self.schema, parsed_query, root_value,
                                       context, variables, operation_name)

                return Promise.resolve(True).then(
                    context_promise_handler).then(
                        filter_func_promise_handler).then(
                            context_do_execute_handler).then(
                                lambda result: callback(None, result)).catch(
                                    lambda error: callback(error, None))

            subscription_promises.append(
                self.pubsub.subscribe(
                    trigger_name, on_message,
                    channel_options).then(lambda id: self.subscriptions[
                        external_subscription_id].append(id)))

        return Promise.all(subscription_promises).then(
            lambda result: external_subscription_id)
Esempio n. 13
0
def complete_value(exe_context, return_type, field_asts, info, result):
    """
    Implements the instructions for completeValue as defined in the
    "Field entries" section of the spec.

    If the field type is Non-Null, then this recursively completes the value for the inner type. It throws a field
    error if that completion returns null, as per the "Nullability" section of the spec.

    If the field type is a List, then this recursively completes the value for the inner type on each item in the
    list.

    If the field type is a Scalar or Enum, ensures the completed value is a legal value of the type by calling the
    `serialize` method of GraphQL type definition.

    If the field is an abstract type, determine the runtime type of the value and then complete based on that type.

    Otherwise, the field type expects a sub-selection set, and will complete the value by evaluating all
    sub-selections.
    """
    # If field type is NonNull, complete for inner type, and throw field error if result is null.

    if is_thenable(result):
        return promisify(result).then(
            lambda resolved: complete_value(exe_context, return_type,
                                            field_asts, info, resolved),
            lambda error: Promise.rejected(
                GraphQLLocatedError(field_asts, original_error=error)))

    if isinstance(result, Exception):
        raise GraphQLLocatedError(field_asts, original_error=result)

    if isinstance(return_type, GraphQLNonNull):
        completed = complete_value(exe_context, return_type.of_type,
                                   field_asts, info, result)
        if completed is None:
            raise GraphQLError(
                'Cannot return null for non-nullable field {}.{}.'.format(
                    info.parent_type, info.field_name), field_asts)

        return completed

    # If result is null-like, return null.
    if result is None:
        return None

    # If field type is List, complete each item in the list with the inner type
    if isinstance(return_type, GraphQLList):
        return complete_list_value(exe_context, return_type, field_asts, info,
                                   result)

    # If field type is Scalar or Enum, serialize to a valid value, returning null if coercion is not possible.
    if isinstance(return_type, (GraphQLScalarType, GraphQLEnumType)):
        return complete_leaf_value(return_type, result)

    if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)):
        return complete_abstract_value(exe_context, return_type, field_asts,
                                       info, result)

    if isinstance(return_type, GraphQLObjectType):
        return complete_object_value(exe_context, return_type, field_asts,
                                     info, result)

    assert False, u'Cannot complete value of unexpected type "{}".'.format(
        return_type)
Esempio n. 14
0
def test_rejected():
    p = Promise.rejected(Exception("Static rejected"))
    assert p.is_rejected
    with raises(Exception) as exc_info:
        p.get()
    assert str(exc_info.value) == "Static rejected"