Exemple #1
0
async def test_AsyncIORuntime_map_value_async_ok():
    def cb(x: int) -> int:
        return x * 2

    assert (await cast(
        Awaitable[int],
        AsyncIORuntime().map_value(AsyncIORuntime().ensure_wrapped(42), cb),
    ) == 84)
Exemple #2
0
async def test_AsyncIORuntime_nested_awaits():
    await assert_execution(
        schema,
        "{ nested }",
        expected_data={"nested": 42},
        runtime=AsyncIORuntime(),
    )
Exemple #3
0
async def test_AsyncIORuntime_simple_sync_field():
    await assert_execution(
        schema,
        "{ sync_a }",
        expected_data={"sync_a": 42},
        runtime=AsyncIORuntime(),
    )
Exemple #4
0
async def test_AsyncIORuntime_simple_field_with_io():
    await assert_execution(
        schema,
        "{ b(sleep: 0.001) }",
        expected_data={"b": 42},
        runtime=AsyncIORuntime(),
    )
Exemple #5
0
async def test_raises_on_unsupported_operations(starwars_schema):
    with pytest.raises(RuntimeError):
        subscribe(
            starwars_schema,
            parse("query { counter(delay: 0.001) }"),
            runtime=AsyncIORuntime(),
        )
Exemple #6
0
async def test_AsyncIORuntime_ensure_wrapped_awaitable():
    async def a():
        return 42

    awaitable = a()
    assert AsyncIORuntime().ensure_wrapped(awaitable) is awaitable
    assert await awaitable == 42
Exemple #7
0
async def test_AsyncIORuntime_field_with_sync_error():
    await assert_execution(
        schema,
        "{ sync_error }",
        expected_data={"sync_error": None},
        expected_errors=[("FOO", (2, 12), "sync_error")],
        runtime=AsyncIORuntime(),
    )
Exemple #8
0
async def test_raises_on_missing_subscription_resolver(starwars_schema):
    schema = subscription_schema(
        Field(
            "counter",
            NonNullType(Int),
            args=[Argument("delay", NonNullType(Float))],
            resolver=lambda event, *_, **__: event,
        )
    )

    with pytest.raises(RuntimeError):
        subscribe(
            schema,
            parse("subscription { counter(delay: 0.001) }"),
            runtime=AsyncIORuntime(),
        )
Exemple #9
0
async def test_raises_on_multiple_fields(starwars_schema):
    schema = subscription_schema(
        Field(
            "counter",
            NonNullType(Int),
            args=[Argument("delay", NonNullType(Float))],
            subscription_resolver=lambda *_, delay: AsyncCounter(delay, 10),
            resolver=lambda event, *_, **__: event,
        )
    )

    with pytest.raises(ExecutionError):
        subscribe(
            schema,
            parse(
                "subscription { counter(delay: 0.001), other: counter(delay: 0.001) }"
            ),
            runtime=AsyncIORuntime(),
        )
Exemple #10
0
async def test_simple_counter_subscription_with_error():
    def resolver(event, *_, **__):
        if event % 2:
            raise ResolverError("I don't like odd numbers.")
        return event

    schema = subscription_schema(
        Field(
            "counter",
            NonNullType(Int),
            args=[Argument("delay", NonNullType(Float))],
            subscription_resolver=lambda *_, delay: AsyncCounter(delay, 10),
            resolver=resolver,
        )
    )

    response_stream = await subscribe(
        schema,
        parse("subscription { counter(delay: 0.001) }"),
        runtime=AsyncIORuntime(),
    )

    assert [
        (
            {"data": {"counter": x}}
            if not x % 2
            else (
                {
                    "data": {"counter": None},  # type: ignore
                    "errors": [  # type: ignore
                        {
                            "locations": [{"column": 16, "line": 1}],
                            "message": "I don't like odd numbers.",
                            "path": ["counter"],
                        }
                    ],
                }
            )
        )
        for x in range(1, 11)
    ] == [r.response() for r in await collect_async_iterator(response_stream)]
Exemple #11
0
 async def run():
     try:
         result = await execute(
             self.schema,
             document,
             variables=variables,
             operation_name=operation_name,
             context_value=self.context,
             initial_value=self.root,
             runtime=AsyncIORuntime(),
         )
     except GraphQLResponseError as err:
         await self.send(
             ServerMessage.ERROR,
             id=msg_id,
             payload={"errors": [err.to_dict()]},
         )
     else:
         await self.send(ServerMessage.DATA,
                         id=msg_id,
                         payload=result.response())
         await self.send(ServerMessage.COMPLETE, id=msg_id)
Exemple #12
0
        async def run():
            try:
                iterator = await subscribe(
                    self.schema,
                    document,
                    variables=variables,
                    operation_name=operation_name,
                    context_value=self.context,
                    initial_value=self.root,
                    runtime=AsyncIORuntime(),
                )
            except GraphQLResponseError as err:
                await self.send(
                    ServerMessage.ERROR,
                    id=msg_id,
                    payload={"errors": [err.to_dict()]},
                )
            else:
                try:
                    async for result in iterator:
                        if msg_id not in self.operations:
                            break

                        await self.send(
                            ServerMessage.DATA,
                            id=msg_id,
                            payload=result.response(),
                        )
                except asyncio.CancelledError:
                    pass
                except Exception as err:
                    logger.error(
                        "Error in subscription %r: %r",
                        msg_id,
                        err,
                        exc_info=True,
                    )
                    raise
Exemple #13
0
async def test_simple_counter_subscription():
    schema = subscription_schema(
        Field(
            "counter",
            NonNullType(Int),
            args=[Argument("delay", NonNullType(Float))],
            resolver=lambda event, *_, **__: event,
        )
    )

    @schema.subscription("Subscription.counter")
    def counter_subscription(*_, delay):
        return AsyncCounter(delay, 10)

    response_stream = await subscribe(
        schema,
        parse("subscription { counter(delay: 0.001) }"),
        runtime=AsyncIORuntime(),
    )

    assert [{"data": {"counter": x}} for x in range(1, 11)] == [
        r.response() for r in await collect_async_iterator(response_stream)
    ]
Exemple #14
0
async def test_AsyncIORuntime_map_value_async_fail(raiser):
    with pytest.raises(ValueError):
        await AsyncIORuntime().map_value(AsyncIORuntime().ensure_wrapped(42),
                                         raiser(ValueError))
Exemple #15
0
async def test_AsyncIORuntime_gather_values_empty_input():
    assert AsyncIORuntime().gather_values([]) == []
Exemple #16
0
async def test_AsyncIORuntime_gather_values_sync_input():
    assert AsyncIORuntime().gather_values([1, 2, 3]) == [1, 2, 3]
Exemple #17
0
async def test_AsyncIORuntime_gather_values_surfaces_errors():
    def a():
        raise ValueError()

    with pytest.raises(ValueError):
        AsyncIORuntime().gather_values([a()])
Exemple #18
0
async def test_AsyncIORuntime_gather_values_async_input():
    assert await cast(
        Awaitable[int],
        AsyncIORuntime().gather_values(
            [1, AsyncIORuntime().ensure_wrapped(2), 3]),
    ) == [1, 2, 3]
Exemple #19
0
async def test_AsyncIORuntime_map_value_sync_ok():
    assert AsyncIORuntime().map_value(42, lambda x: x * 2) == 84
Exemple #20
0
async def test_AsyncIORuntime_map_value_async_caught(raiser):
    assert (await AsyncIORuntime().map_value(
        AsyncIORuntime().ensure_wrapped(42),
        raiser(ValueError),
        (ValueError, lambda _: 42),
    ) == 42)
Exemple #21
0
async def test_AsyncIORuntime_runtime_error():
    with pytest.raises(RuntimeError):
        await assert_execution(schema, "{ c }", runtime=AsyncIORuntime())
Exemple #22
0
async def test_AsyncIORuntime_map_value_sync_fail(raiser):
    with pytest.raises(ValueError):
        AsyncIORuntime().map_value(42, raiser(ValueError))
Exemple #23
0
async def test_AsyncIORuntime_map_value_sync_caught(raiser):
    assert (AsyncIORuntime().map_value(42, raiser(ValueError),
                                       (ValueError, lambda _: 42)) == 42)