當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。