question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

MagicMock doesn't implement `__aenter__` or `__aexit__`

See original GitHub issue

When testing asyncio code, the probability of needing to test async context manager is high.

The current code using MagicMock doesn’t implement __aenter__ or __aexit__ methods

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:27
  • Comments:42 (16 by maintainers)

github_iconTop GitHub Comments

7reactions
Galbarcommented, Mar 21, 2017

We had the same problem mocking aiopg. We ended up with this workaround:

class AsyncContextManagerMock(MagicMock):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for key in ('aenter_return', 'aexit_return'):
            setattr(self, key,  kwargs[key] if key in kwargs else MagicMock())

    async def __aenter__(self):
        return self.aenter_return

    async def __aexit__(self, *args):
        return self.aexit_return

3reactions
thehesiodcommented, Sep 22, 2017

nice work @Martiusweb on a real fix and @Galbar on work-around, this thread inspired us to do a simpler fix:

class MagicMockContext(MagicMock):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        type(self).__aenter__ = CoroutineMock(return_value=MagicMock())
        type(self).__aexit__ = CoroutineMock(return_value=MagicMock())

with usage:

with asynctest.mock.patch('dummy.Dummy', new_callable=MagicMockContext) as mockClientSession:
Read more comments on GitHub >

github_iconTop Results From Across the Web

python - Mock for context-manager fails with AttributeError: __ ...
The issue is when you're calling mo(..) the object it is returning( tuple ) doesn't have __enter__ and __exit__ attributes on it. To...
Read more >
unittest.mock — mock object library — Python 3.11.1 ...
mock provides a core Mock class removing the need to create a host of stubs throughout your test suite. After performing an action,...
Read more >
Mocking — asynctest 0.12.3 documentation
asynctest will mock an attribute as a CoroutineMock if the function is a native coroutine ( async def function) or a decorated generator...
Read more >
Testing asynchronous context managers in Python
The asynctest module enhances standard unittest.mock to deal with ... but the __aenter__ and __aexit__ methods required by asynchronous ...
Read more >
unittest's new context methods in Python 3.11 (with backports)
... logic in many cases, such as dynamic use of unittest.mock. ... Call addCleanup to schedule the context manager's __exit__ to run at ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found