简体   繁体   中英

Python mock patch a coroutine function within another function using pytest?

I have two functions in module_name/app.py

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


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

I try to test f2 and mock f1 using pytest and asynctest.
It only works, if I do

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

test PASSED

But, I want do to something like this

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

I get

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

Why doesn't the second way work?

In your second example, in mock_f1 fixture you create a CoroutineMock object and return it. But you don't overwrite module_name.app.f1 function: Mock -like objects don't patch anything automatically.

Here is an illustrating addition to your example:

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

Which will print somethink like this

fixture value: <CoroutineMock spec='function' id='139756096130688'>
actual module_name.app.f1 function: <function f1 at 0x7f1b7e1139d8>

When you call f2 , it uses f1 function from the module, which is not overriden.

So here is how this would work for you:

@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

As you probably know, monkeypatch will make sure that changes are applied only while the fixture is active.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM