当前位置: 首页>>代码示例>>Python>>正文


Python contextlib.asynccontextmanager方法代码示例

本文整理汇总了Python中contextlib.asynccontextmanager方法的典型用法代码示例。如果您正苦于以下问题:Python contextlib.asynccontextmanager方法的具体用法?Python contextlib.asynccontextmanager怎么用?Python contextlib.asynccontextmanager使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在contextlib的用法示例。


在下文中一共展示了contextlib.asynccontextmanager方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_basic

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import asynccontextmanager [as 别名]
def test_basic():
    exit_count = 0

    @contextlib.asynccontextmanager
    async def ctx(v):
        nonlocal exit_count
        await asyncio.sleep(0)
        yield v
        await asyncio.sleep(0)
        exit_count += 1

    group = AsyncContextGroup([ctx(i) for i in range(3)])
    async with group as yielded_values:
        assert yielded_values == tuple(range(3))

    assert exit_count == 3 
开发者ID:ethereum,项目名称:trinity,代码行数:18,代码来源:test_contextgroup.py

示例2: test_exception_entering_context

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import asynccontextmanager [as 别名]
def test_exception_entering_context():
    exit_count = 0

    @contextlib.asynccontextmanager
    async def ctx(should_raise=False):
        nonlocal exit_count
        await asyncio.sleep(0)
        if should_raise:
            raise ValueError()
        try:
            yield
        finally:
            await asyncio.sleep(0)
            exit_count += 1

    group = AsyncContextGroup([ctx(), ctx(True), ctx()])
    with pytest.raises(ValueError):
        async with group:
            # the body of the with block should never execute if an exception is raised when
            # entering the context group.
            assert False  # noqa: B011

    # One of our contexts was not entered so we didn't exit it either.
    assert exit_count == 2 
开发者ID:ethereum,项目名称:trinity,代码行数:26,代码来源:test_contextgroup.py

示例3: test_exception_exiting

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import asynccontextmanager [as 别名]
def test_exception_exiting():
    exit_count = 0

    @contextlib.asynccontextmanager
    async def ctx(should_raise=False):
        nonlocal exit_count
        await asyncio.sleep(0)
        try:
            yield
        finally:
            exit_count += 1
            if should_raise:
                raise ValueError()

    group = AsyncContextGroup([ctx(), ctx(True), ctx(True)])
    with pytest.raises(MultiError) as exc_info:
        async with group:
            pass

    exc = exc_info.value
    assert len(exc.exceptions) == 2
    assert isinstance(exc.exceptions[0], ValueError)
    assert isinstance(exc.exceptions[1], ValueError)
    assert exit_count == 3 
开发者ID:ethereum,项目名称:trinity,代码行数:26,代码来源:test_contextgroup.py

示例4: test_exception_inside_context_block

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import asynccontextmanager [as 别名]
def test_exception_inside_context_block():
    exit_count = 0

    async def f(should_raise):
        await asyncio.sleep(0)
        if should_raise:
            raise ValueError()

    @contextlib.asynccontextmanager
    async def ctx(should_raise=False):
        nonlocal exit_count
        await asyncio.sleep(0)
        try:
            yield f(should_raise)
        finally:
            await asyncio.sleep(0)
            exit_count += 1

    group = AsyncContextGroup([ctx(), ctx(True), ctx()])
    with pytest.raises(ValueError):
        async with group as awaitables:
            empty1, exception, empty2 = await asyncio.gather(*awaitables, return_exceptions=True)
            assert empty1 is None
            assert empty2 is None
            raise exception

    assert exit_count == 3 
开发者ID:ethereum,项目名称:trinity,代码行数:29,代码来源:test_contextgroup.py

示例5: test_enter_context

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import asynccontextmanager [as 别名]
def test_enter_context(self):
        state = None

        @contextlib.contextmanager
        def ctxtest():
            nonlocal state
            state = "before"
            yield state
            state = "after"

        @contextlib.asynccontextmanager
        async def actxtest():
            nonlocal state
            state = "before2"
            yield state
            state = "after2"

        async with await s_base.Base.anit() as base:
            await base.enter_context(ctxtest())
            self.eq("before", state)

        self.eq("after", state)

        async with await s_base.Base.anit() as base:
            await base.enter_context(actxtest())
            self.eq("before2", state)

        self.eq("after2", state) 
开发者ID:vertexproject,项目名称:synapse,代码行数:30,代码来源:test_lib_base.py

示例6: fake_beam_syncer

# 需要导入模块: import contextlib [as 别名]
# 或者: from contextlib import asynccontextmanager [as 别名]
def fake_beam_syncer(chain, event_bus):
    @contextlib.asynccontextmanager
    async def fake_beam_sync(removed_nodes: Dict):
        # beam sync starts, it fetches requested nodes from remote peers

        def replace_missing_node(missing_node_hash):
            if missing_node_hash not in removed_nodes:
                raise Exception(f'An unexpected node was requested: {missing_node_hash}')
            chain.chaindb.db[missing_node_hash] = removed_nodes.pop(missing_node_hash)

        async def collect_accounts(event: CollectMissingAccount):
            replace_missing_node(event.missing_node_hash)
            await event_bus.broadcast(
                MissingAccountResult(1), event.broadcast_config()
            )
        accounts_sub = event_bus.subscribe(CollectMissingAccount, collect_accounts)

        async def collect_bytecodes(event: CollectMissingBytecode):
            replace_missing_node(event.bytecode_hash)
            await event_bus.broadcast(
                MissingBytecodeResult(), event.broadcast_config()
            )
        bytecode_sub = event_bus.subscribe(CollectMissingBytecode, collect_bytecodes)

        async def collect_storage(event: CollectMissingStorage):
            replace_missing_node(event.missing_node_hash)
            await event_bus.broadcast(
                MissingStorageResult(1), event.broadcast_config()
            )
        storage_sub = event_bus.subscribe(CollectMissingStorage, collect_storage)

        await event_bus.wait_until_any_endpoint_subscribed_to(CollectMissingAccount)
        await event_bus.wait_until_any_endpoint_subscribed_to(CollectMissingBytecode)
        await event_bus.wait_until_any_endpoint_subscribed_to(CollectMissingStorage)

        try:
            yield
        finally:
            accounts_sub.unsubscribe()
            bytecode_sub.unsubscribe()
            storage_sub.unsubscribe()

    return fake_beam_sync


# Test that eth_getBalance works during beam sync 
开发者ID:ethereum,项目名称:trinity,代码行数:48,代码来源:test_rpc_during_beam_sync.py


注:本文中的contextlib.asynccontextmanager方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。