asynctest icon indicating copy to clipboard operation
asynctest copied to clipboard

Question on upstream AsyncMock

Open dimaqq opened this issue 6 years ago • 3 comments

Thanks to https://github.com/python/cpython/pull/9296, Python3.8 now has unittest.mock.AsyncMock

I wonder if this means that some asynctest use can be pivoted to upstream AsyncMock, in what cases, etc.

Likewise, what features or use cases remain exclusive to asynctest?

Advice is highly appreciated, and could possibly even make it to readme / rtd.

dimaqq avatar Jun 24 '19 02:06 dimaqq

Hi,

unittest.mock.AsyncMock borrows most of the concepts and API from asynctest.CoroutineMock.

Enventually (for projects which only support 3.8+), I believe that AsyncMock should become the class to use. For asynctest, the plan is to make asynctest.CoroutineMock and unittest.AsyncMock the same thing, as they share the same API. The goal is to make the transition to unittest.AsyncMock as easy as possible for asynctest users.

asynctest.TestCase and asynctest.patch still provides features not supported by unittest:

  • TestCase manages the loop, and supports the @fail_on decorator
  • asynctest.patch() supports patching coroutines (ie: decorating a coroutine function or a generator), while afaik, unittest.patch() will not work:
def my_symbol():
   print("I'm not patched")
   
@unittest.patch("module.my_symbol")
async def coroutine():
    # will print "I'm not patched", because the patch is only effective during the construction of the coroutine instance, not when the generator runs
    my_symbol() 

The PR has been merged to CPython one week before I started a new job in a new country, so I don't think I'll have much time to work on asynctest before a while :/

Martiusweb avatar Jun 24 '19 16:06 Martiusweb

also note that pypi mock has now backported AsyncMock for older pythons

graingert avatar Feb 21 '20 09:02 graingert

perhaps a new release with:

if sys.version_info >= (3, 8):
    from unittest.mock import AsyncMock as CoroutineMock
else:
    from mock import AsyncMock as CoroutineMock

and then depend on:

install_requires =
  pkgutil_resolve_name; python_version < "3.9"

graingert avatar Feb 21 '20 09:02 graingert