小编Oks*_*ana的帖子

Python 使用 pytest 模拟修补另一个函数中的协程函数?

我在 module_name/app.py 中有两个函数

async def f1(arg):
    # do something
    return arg + '1'


async def f2(arg):
    result = await f1(arg)
    return result
Run Code Online (Sandbox Code Playgroud)

我尝试使用 pytest 和 asynctest 测试 f2 和模拟 f1。
只有我这样做才有效

def sf_f1(arg):
    return 'some value'

@pytest.mark.asyncio
async def test_f2():
    with asynctest.mock.patch('module_name.app.f1', side_effect=sf_f1):
        assert 'some value' == await f2('test')
Run Code Online (Sandbox Code Playgroud)

考试通过了

但是,我想做这样的事情

import module_name

@pytest.fixture()
def mock_f1():
    return asynctest.CoroutineMock(module_name.app.f1, side_effect=sf_f1)


@pytest.mark.asyncio
async def test_f2_2(mock_f1):
    assert 'some value' == await f2('test')
Run Code Online (Sandbox Code Playgroud)

我明白了

   assert 'some value' == await f2('test')
   AssertionError: assert 'some value' …
Run Code Online (Sandbox Code Playgroud)

python pytest python-asyncio

5
推荐指数
1
解决办法
4541
查看次数

标签 统计

pytest ×1

python ×1

python-asyncio ×1