1

Code:

class SomeClass(BaseClass):
    async def async_method(arg1, arg2, **kwargs):
        await self.foo.bar(arg1=arg1, arg2=arg2).baz(**kwargs)

One of the tests used:

@pytest.fixture
def same_class():
    return SameClass()


async def test_async_method(some_class: SomeClass):
    arg1_mock = 1
    arg2_mock = 2
    some_class.foo.bar = AsyncMock()
    some_class.foo.bar.baz = AsyncMock()
    
    await some_class.async_method(arg1=arg1_mock, arg2=arg2_moc)
    
    some_class.foo.bar.assert_called_once()

I get an error:

AttributeError: 'coroutine' object has no attribute 'baz'

How to add an asynchronous attribute method to AsyncMock? Any help

Maksim
  • 11
  • 2

1 Answers1

2

From the AsyncMock documentation

The AsyncMock object will behave so the object is recognized as an async function, and the result of a call is an awaitable.

In your code, bar is the async function that returns an awaitable. To make the awaitable return something with a baz attribute, set it on the return value instead.

some_class.foo.bar = AsyncMock()
some_class.foo.bar.return_value.baz = AsyncMock()
dirn
  • 19,454
  • 5
  • 69
  • 74