Python模拟异步方法

时间:2020-05-05 18:02:06

标签: mocking python-3.7 python-asyncio

我无法解决这个问题:

import asyncio
from unittest import create_autospec

import pytest


def create_future(result: Any, loop: asyncio.AbstractEventLoop) -> Any:
    f = asyncio.Future(loop=loop)
    f.set_result(result)
    return f


class Foo:
    async def process(self, arg1: str, arg2: str) -> None:
        await self.some_processing()

    async def some_processing(self) -> None:
        ...

class Bar:
    def __init__(self, foo: Foo):
        self._foo = foo

    async def do_something(self, arg1: str, arg2: str) -> None:
        await self._foo.process(arg1, arg2)


@pytest.mark.asyncio
async def test_do_something(event_loop: asyncio.AbstractEventLoop):
    foo_mock = create_autospec(Foo, spec_set=True)
    foo_mock.some_processing.return_value = create_future("3", event_loop)
    bar = Bar(foo)
    await bar.do_something("1", "2")
    foo_mock.process.assert_called_once_with("1", "2")

当然会失败

TypeError: object MagicMock can't be used in 'await' expression

我的问题是:我如何实现以下行为-我做了一些魔术,foo.process被嘲弄了所需的参数,而TypeError上却没有await foo.process(arg1, arg2)

我正在使用python 3.7,我知道python 3.8具有AsyncMock,但是python 3.8不是我可以使用的方式。

0 个答案:

没有答案
相关问题