Skip to content

Full control over awaitable mock #64

Description

@Kentzo

When writing asyncio tests it is to control when and what awaitable mock should return.

Here is an example to give an idea:

class MagicCoro(unittest.mock.Mock):
    """
    >>> m = unittest.mock.MagicMock()
    >>> m.coro = MagicCoro(return_value=42)
    >>> assert await m.coro() == 42
    >>> assert m.exit.is_set()
    """
    def __init__(self, run_event=None, return_value=None):
        async def coro(*args, **kwargs):
            self.enter.set()

            if self.run:
                await self.run.wait()

            self.exit.set()

            return self.value

        super().__init__(wraps=coro)

        self.enter = asyncio.Event()
        self.run = run_event
        self.exit = asyncio.Event()
        self.value = return_value

    def _get_child_mock(self, **kw):
        return unittest.mock.MagicMock(**kw)

This allows to:

  • provide a return value
  • provide an event to wait for allowing user to control completion order
  • assert whether coroutine was entered or exited

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions