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

Viewed 4019

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?

1 Answers
Related