classification
Title: Exception in AsyncMock side_effect cases incorrect refcount
Type: behavior Stage:
Components: asyncio Versions: Python 3.9
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: asvetlov, penlect, yselivanov
Priority: normal Keywords:

Created on 2021-06-13 14:52 by penlect, last changed 2021-06-13 14:52 by penlect.

Messages (1)
msg395752 - (view) Author: Daniel Andersson (penlect) * Date: 2021-06-13 14:52
Dear maintainers,

I discovered an unexpected behavior when the `side_effect` of an `AsyncMock` includes an exception. The test case below fails but I expected it to pass:

```
import sys
import unittest
from unittest.mock import AsyncMock


class A:
    async def foobar(self):
        while True:
            try:
                return await self.mock()
            except Exception:
                continue


class TestA(unittest.IsolatedAsyncioTestCase):
    async def test_refcount(self):
        a = A()
        a.mock = AsyncMock(side_effect=[Exception(), None])
        refc = sys.getrefcount(a)
        await a.foobar()
        self.assertEqual(refc, sys.getrefcount(a))


if __name__ == "__main__":
    unittest.main()
```

If `side_effect=[Exception(), None]` is changed to `side_effect=[None, None]` the test case pass.

I discovered this in a bigger codebase while debugging why a weakref.finalize did not trigger as expected.
History
Date User Action Args
2021-06-13 14:52:01penlectcreate