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

2024-10-02 18:23:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在模块名中有两个函数/应用程序副本在

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


async def f2(arg):
    result = await f1(arg)
    return result

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

^{pr2}$

测试通过

但是,我想做这样的事情

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')

我明白了

   assert 'some value' == await f2('test')
   AssertionError: assert 'some value' == 'test1'
     - some value
     + test1

为什么第二条路不行?在


Tags: testasyncreturnpytestvaluedefargsome
1条回答
网友
1楼 · 发布于 2024-10-02 18:23:10

在第二个示例中,在mock_f1fixture中,创建一个CoroutineMock对象并返回它。但是你不能重写module_name.app.f1函数:Mock类对象不会自动修补任何内容。在

以下是对示例的补充说明:

@pytest.mark.asyncio
async def test_f2_2(mock_f1):
    print('fixture value:', mock_f1)
    print('actual module_name.app.f1 function:', module_name.app.f1)
    assert 'some value' == await f2('test')

会印出这样的想法

^{pr2}$

当您调用f2时,它使用模块中的f1函数,该函数不会被重写。在

以下是如何为您工作:

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

您可能知道,monkeypatch将确保只有在fixture处于活动状态时才应用更改。在

相关问题 更多 >