erdewit / nest_asyncio

Patch asyncio to allow nested event loops
BSD 2-Clause "Simplified" License
693 stars 79 forks source link

Fix asyncio warnings emitted during pytest #76

Closed amosjyng closed 1 year ago

amosjyng commented 1 year ago

I'm basing these changes on https://stackoverflow.com/a/73367187 . Without this change, I get:

nest_asyncio.py:45: DeprecationWarning: There is no current event loop loop = events.get_event_loop_policy().get_event_loop()

erdewit commented 1 year ago

nest_asyncio.py:45: DeprecationWarning: There is no current event loop

I can't reproduce this warning or find it in the asyncio source with Python 3.11.1 How is it triggered?

amosjyng commented 1 year ago

Interesting, so this script triggers it on 3.11.1 for me:

import nest_asyncio
import asyncio

nest_asyncio.apply()

async def hello():
    return "world"

asyncio.new_event_loop().run_until_complete(hello())

But I recommend running this with pytest; running it with Python doesn't output the warning, but the line in the code that does warnings.warn still gets reached.

Commenting out nest_asyncio.apply() resolves the issue.

Are you able to reproduce it now?

erdewit commented 1 year ago

I tried running the snippet with pytest but still can't produce a warning. The pytest environment looks like this:

platform linux -- Python 3.11.1, pytest-7.1.3, pluggy-1.0.0
rootdir: /home/ewald
plugins: anyio-3.6.1, asyncio-0.19.0, flaky-3.7.0, cov-4.0.0, timeout-2.1.0
asyncio: mode=Mode.STRICT

Note that the snippet creates a new (and unpatched) event loop; To run with a patched loop try something such as the following:

import nest_asyncio
import asyncio

async def hello():
    return "world"

loop = asyncio.new_event_loop()
nest_asyncio.apply(loop)
r = loop.run_until_complete(hello())
assert r == 'world'
amosjyng commented 1 year ago

Ah ok, thanks for the heads up! I've changed it to get_event_loop instead.

I've managed to reproduce this issue in a Github test environment, by modifying your test workflow to run with pytest instead in this commit. If you click through to runs such as this one and open up the "Testsuite" section, you should be able to see the warning reproduced:

warning

Please let me know if I can help any further with reproducing the issue! :)

amosjyng commented 1 year ago

Ping, any updates? Seems like others are running into this too :P

erdewit commented 1 year ago

This is fixed slightly differently by patching the event loop policy: https://github.com/erdewit/nest_asyncio/commit/9d46de93f251f717912dd6055ef79b68e80dec26

amosjyng commented 1 year ago

Awesome!