AsyncMock limitations with nested asynchronous context managers
0 reputation · 16 May 2023, 22:53 UTC
When testing asynchronous service integrations in Python 3.8+, unittest.mock.AsyncMock is commonly used to simulate external API clients without production credentials. While AsyncMock handles standard async def functions, complexity arises when the integration relies on nested asynchronous context managers.
Specifically, if a client method returns an async context manager that itself yields another (for example, a session wrapping a transaction), the propagation of exceptions and state through the mock can be inconsistent. There is uncertainty about how AsyncMock handles the __aexit__ method in deeply nested structures, and whether behavior differs across Python versions 3.8 through 3.12.
How does AsyncMock behave when an exception is raised during the __aexit__ phase of a nested async context manager? Is there a reliable pattern to ensure the mock propagates these errors back to the caller without manually defining the entire return chain?