示例#1
0
async def test_cannot_nest_contexts():
    dispatch = Dispatch()

    class MyRequestContext:
        x: int = 0

    context = MyRequestContext()

    with pytest.raises(RuntimeError):
        async with dispatch.connection_context(context):
            async with dispatch.connection_context(context):
                pass
示例#2
0
async def test_dispatch_context_inside_request():
    """
    If a context is set, it should be visible inside the handler and the handler should
    be able to modify the state in ways that are visible to other handlers.
    """
    dispatch = Dispatch()

    class MyRequestContext:
        x: int = 0

    @dispatch.handler
    async def increment():
        dispatch.ctx.x += 1
        return {"x": dispatch.ctx.x}

    context = MyRequestContext()
    async with dispatch.connection_context(context):
        result = await dispatch.execute(
            JsonRpcRequest(id=0, method="increment"))
        assert result["x"] == 1
        result = await dispatch.execute(
            JsonRpcRequest(id=1, method="increment"))
        assert result["x"] == 2
    assert context.x == 2