Beispiel #1
0
def _add_errors_to_execution_context(
    execution_context: ExecutionContext,
    raw_exception: Union[Exception, MultipleException],
    path: Union[str, List[str]],
    location: "Location",
) -> None:
    exceptions = (
        raw_exception.exceptions
        if isinstance(raw_exception, MultipleException)
        else [raw_exception]
    )

    for exception in exceptions:
        gql_error = (
            exception
            if is_coercible_exception(exception)
            else GraphQLError(
                str(exception), path, [location], original_error=exception
            )
        )

        gql_error.coerce_value = partial(
            gql_error.coerce_value, path=path, locations=[location]
        )

        execution_context.add_error(gql_error)
Beispiel #2
0
def test_executor_types_ec_add_error():
    from tartiflette.executors.types import ExecutionContext

    ec = ExecutionContext()
    e = Exception

    ec.add_error(e)

    assert e in ec.errors
Beispiel #3
0
    async def __call__(
        self,
        execution_ctx: ExecutionContext,
        request_ctx: Optional[Dict[str, Any]],
        parent_result: Optional[Any] = None,
        parent_marshalled: Optional[Any] = None,
    ) -> None:
        raw, coerced = await self.field_executor(
            parent_result,
            self.arguments,
            request_ctx,
            Info(
                query_field=self,
                schema_field=self.field_executor.schema_field,
                schema=self.schema,
                path=self.path,
                location=self.location,
                execution_ctx=execution_ctx,
            ),
        )

        if parent_marshalled is not None:
            parent_marshalled[self.alias] = coerced
        else:
            self.marshalled = coerced

        if isinstance(raw, Exception):
            try:
                if callable(raw.coerce_value):
                    gql_error = raw
            except (TypeError, AttributeError):
                gql_error = GraphQLError(str(raw), self.path, [self.location])

            gql_error.coerce_value = partial(
                gql_error.coerce_value,
                path=self.path,
                locations=[self.location],
            )

            if ((self.cant_be_null or self.contains_not_null) and self.parent
                    and self.cant_be_null):
                self.parent.bubble_error()
            execution_ctx.add_error(gql_error)
        elif self.children and raw is not None:
            await self._execute_children(execution_ctx,
                                         request_ctx,
                                         result=raw,
                                         coerced=coerced)
Beispiel #4
0
def test_executor_types_ec_instance():
    from tartiflette.executors.types import ExecutionContext

    ec = ExecutionContext()

    assert not ec.errors
    assert not ec.is_introspection
Beispiel #5
0
async def subscribe(
    operations: Dict[Optional[str], List["NodeOperationDefinition"]],
    operation_name: Optional[str],
    request_ctx: Optional[Dict[str, Any]],
    initial_value: Optional[Any],
    error_coercer: Callable[[Exception], dict],
) -> AsyncIterable[Dict[str, Any]]:
    # pylint: disable=too-many-locals
    execution_ctx = ExecutionContext()

    operation, errors = get_operation(operations, operation_name)

    if errors:
        yield {"data": None, "errors": [error_coercer(err) for err in errors]}

    root_nodes = operation.children

    source_event_stream = await root_nodes[0].create_source_event_stream(
        execution_ctx, request_ctx, parent_result=initial_value)

    async for message in source_event_stream:
        yield await execute_fields(
            root_nodes,
            execution_ctx,
            request_ctx,
            initial_value=message,
            error_coercer=error_coercer,
            allow_parallelization=operation.allow_parallelization,
        )
Beispiel #6
0
def _add_errors_to_execution_context(
    execution_context: ExecutionContext,
    raw_exception: Union[Exception, MultipleException],
    path: Union[str, List[str]],
    location: "Location",
) -> None:
    exceptions = (
        raw_exception.exceptions
        if isinstance(raw_exception, MultipleException)
        else [raw_exception]
    )

    for exception in exceptions:
        try:
            if callable(exception.coerce_value):
                gql_error = exception
        except (TypeError, AttributeError):
            gql_error = GraphQLError(str(exception), path, [location])

        gql_error.coerce_value = partial(
            gql_error.coerce_value, path=path, locations=[location]
        )

        execution_context.add_error(gql_error)
Beispiel #7
0
def test_add_errors_to_execution_context(
    raw_exception, expected_messages, expected_original_errors
):
    execution_context = ExecutionContext()

    location = Location(line=1, column=1)
    path = ["error", "path"]

    _add_errors_to_execution_context(
        execution_context, raw_exception, path, location
    )

    assert len(execution_context.errors) == len(expected_messages)

    for error, expected_message, expected_original_error in zip(
        execution_context.errors, expected_messages, expected_original_errors
    ):
        assert isinstance(error, GraphQLError)
        assert error.message == expected_message
        assert type(error.original_error) is expected_original_error
Beispiel #8
0
async def test_parser_node_nodefield__call__custom_exception():
    from tartiflette.parser.nodes.field import NodeField
    from tests.unit.utils import AsyncMock

    class CustomException(Exception):
        def coerce_value(self, *_args, path=None, locations=None, **_kwargs):
            return {"msg": "error", "type": "bad_request"}

    raw = CustomException("ninja")
    coerced = None

    class fex:
        async def __call__(self, *_, **__):
            return raw, coerced

    fe = fex()
    fe.schema_field = Mock()
    fe.cant_be_null = True

    nf = NodeField("B", None, fe, None, None, None, None)
    nf.children = [Mock()]
    nf._execute_children = AsyncMock()
    nf.parent = Mock()
    nf.parent.bubble_error = Mock()

    exectx = ExecutionContext()
    reqctx = Mock()

    prm = {}

    assert not bool(exectx.errors)

    await nf(exectx, reqctx, parent_marshalled=prm)

    assert bool(exectx.errors)

    assert exectx.errors[0] is raw
    assert exectx.errors[0].coerce_value() == {
        "msg": "error",
        "type": "bad_request",
    }
Beispiel #9
0
async def test_parser_node_nodefield__call__exception():
    from tartiflette.parser.nodes.field import NodeField
    from tests.unit.utils import AsyncMock

    raw = Exception("ninja")
    coerced = None

    class fex:
        async def __call__(self, *_, **__):
            return raw, coerced

    fe = fex()
    fe.schema_field = Mock()
    fe.cant_be_null = True

    nf = NodeField("B", None, fe, None, None, None, None)
    nf.children = [Mock()]
    nf._execute_children = AsyncMock()
    nf.parent = Mock()
    nf.parent.bubble_error = Mock()

    exectx = ExecutionContext()
    reqctx = Mock()

    prm = {}

    assert not bool(exectx.errors)

    await nf(exectx, reqctx, parent_marshalled=prm)

    assert bool(exectx.errors)

    assert exectx.errors[0] is not raw
    assert isinstance(exectx.errors[0], GraphQLError)
    assert exectx.errors[0].coerce_value() == {
        "message": "ninja",
        "path": None,
        "locations": [],
    }
Beispiel #10
0
async def execute(
    operations: Dict[Optional[str], List["NodeOperationDefinition"]],
    operation_name: Optional[str],
    request_ctx: Optional[Dict[str, Any]],
    initial_value: Optional[Any],
    error_coercer: Callable[[Exception], dict],
) -> dict:
    # pylint: disable=too-many-locals
    execution_ctx = ExecutionContext()

    operation, errors = get_operation(operations, operation_name)

    if errors:
        return {"data": None, "errors": [error_coercer(err) for err in errors]}

    return await execute_fields(
        operation.children,
        execution_ctx,
        request_ctx,
        initial_value=initial_value,
        error_coercer=error_coercer,
        allow_parallelization=operation.allow_parallelization,
    )