pytest-asyncio: Error of "attached to a different loop" appears in 0.11.0 but not in 0.10.0

My testcase get the error of “attached to a different loop” in 0.11.0 but works fine in 0.10.0

The detail is I have the following code in my testcase:

asyncio.get_event_loop().run_in_executor(...)

Is there any related change in 0.11.0?

A simple testcase for reproducing:

import asyncio
import pytest

@pytest.fixture(scope='function')
async def loop():
    return asyncio.get_event_loop()

def foo():
    return 0

@pytest.mark.asyncio
async def test_async(loop):
    await loop.run_in_executor(None, foo)

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 13
  • Comments: 28 (14 by maintainers)

Commits related to this issue

Most upvoted comments

@Tinche Sure, I’ll do it tonight

One problem with depending on the event_loop fixture is that while it works for that reduced test case it fails for my real test case (it just hangs) and I don’t understand why yet.

@simonfagerholm I confirm, your changes help in our case 👍

To apply your suggestion to the example code, just add the event_loop to the loop fixture. Like the following code segment works:

import asyncio
import pytest

@pytest.fixture(scope='function')
async def loop(event_loop):
    return asyncio.get_event_loop()

def foo():
    return 0

@pytest.mark.asyncio
async def test_async(loop):
    await loop.run_in_executor(None, foo)

@krizex Great, thanks for the help with confirming! I will see if I can create a fix in the hooks later today

No, the fixture is constructed by calling some low level module and the low level module call asyncio.get_event_loop() to get the event loop. To leverage the event_loop we have to introduce a new param in the code path to pass it to the low level module which is not pratical…

BTW, it is a backward compatibility issue so we have to fix it in the library side.