Esempio n. 1
0
async def test_map_as():
    async def map_op(value):
        return value * 2

    assert [value async for value in a.map(map_op, range(5))] == list(range(0, 10, 2))
    assert [
        value async for value in a.map(hide_coroutine(map_op), range(5, 10, 2))
    ] == list(range(10, 20, 4))
Esempio n. 2
0
async def test_map_sa():
    def map_op(value):
        return value * 2

    assert [value async for value in a.map(map_op, asyncify(range(5)))] == list(
        range(0, 10, 2)
    )
    assert [value async for value in a.map(map_op, asyncify(range(5, 10, 2)))] == list(
        range(10, 20, 4)
    )
Esempio n. 3
0
async def test_exit_stack_pop_all():
    async with a.ExitStack() as exit_stack:
        contexts = list(
            map(lambda v: MockAsyncContext(v) if v % 2 else MockContext(v),
                range(10)))
        values = await a.list(a.map(exit_stack.enter_context, contexts))
        assert values == list(range(10))
        assert all(cm.entered for cm in contexts)
        assert all(not cm.exited for cm in contexts)
        clone_stack = exit_stack.pop_all()
    assert all(not cm.exited for cm in contexts)
    await clone_stack.aclose()
    assert all(cm.exited for cm in contexts)
Esempio n. 4
0
    async def test_mock_backend_example(self) -> None:
        # This is an example of a backend system.
        # This test demonstrates how contracts can be used with coroutines.

        async def has_author(identifier: str) -> bool:
            return identifier in ["Margaret Cavendish", "Jane Austen"]

        async def has_category(category: str) -> bool:
            return category in await get_categories()

        async def get_categories() -> List[str]:
            return ["sci-fi", "romance"]

        @dataclasses.dataclass
        class Book:
            identifier: str
            author: str

        @icontract.require(lambda categories: a.map(has_category, categories))
        @icontract.ensure(lambda result: a.all(
            a.await_each(has_author(book.author) for book in result)))
        async def list_books(categories: List[str]) -> List[Book]:
            result = []  # type: List[Book]
            for category in categories:
                if category == "sci-fi":
                    result.extend([
                        Book(identifier="The Blazing World",
                             author="Margaret Cavendish")
                    ])
                elif category == "romance":
                    result.extend([
                        Book(identifier="Pride and Prejudice",
                             author="Jane Austen")
                    ])
                else:
                    raise AssertionError(category)

            return result

        sci_fi_books = await list_books(categories=['sci-fi'])
        self.assertListEqual(['The Blazing World'],
                             [book.identifier for book in sci_fi_books])