Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spy async bug introduced in Python 3.8.1 #178

Closed
adamcharnock opened this issue Jan 12, 2020 · 5 comments
Closed

Spy async bug introduced in Python 3.8.1 #178

adamcharnock opened this issue Jan 12, 2020 · 5 comments
Labels

Comments

@adamcharnock
Copy link

adamcharnock commented Jan 12, 2020

I believe bpo-38875 has introduced a bug in mocker.spy(). Spied coroutines are no longer awaited as they should be.

This test highlights the issue:

import pytest


class MyClass:
    async def method(self):
        return "hi"


@pytest.mark.asyncio
async def test_spy_async(mocker):
    my_obj = MyClass()
    mocker.spy(my_obj, 'method')

    returned = await my_obj.method()

    # Passes
    assert my_obj.method.called

    # AssertionError: assert <coroutine object MyClass.method at 0x10f2a5d40> == 'hi'
    assert returned == "hi"

It looks like spy() (specifically, wrapper() defined within spy()) returns a coroutine and expects unittest's patch() do to the awaiting, rather than doing the awaiting itself. This worked until bpo-38875 changed this behaviour. Now unittest will no longer await retuned awaitables, rather it returns them.

@adamcharnock
Copy link
Author

If anyone needs a quick workaround, I'm using something like this:

    if sys.version_info >= (3, 8):
        from unittest.mock import AsyncMock
        redis_pool.grow = AsyncMock(wraps=redis_pool.grow)
    else:
        mocker.spy(redis_pool, "grow")

    assert redis_pool.grow.call_count == 123

AsyncMock is new in 3.8

@nicoddemus
Copy link
Member

Hi @adamcharnock,

Thanks for the report and workaround.

Would you consider opening up a PR with this change?

@k4nar
Copy link

k4nar commented Mar 31, 2020

Thank you very much for this fix! Do you know when it will be released? 🙏

@nicoddemus
Copy link
Member

Thanks for the ping @k4nar! Just released 3.0.0 with this fix. 👍

@k4nar
Copy link

k4nar commented Mar 31, 2020

Awesome, thank you for the responsiveness! Stay safe :) .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants