Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
How to fix "attached to a different loop"? #38
I have a very simple app called "myapp". It uses the AsyncElasticsearch client:
My question is not about AsyncElasticsearch, it just happens to be an async thing I want to work with, could be sth else like a Mongo driver or whatever.
I want to test
... and test_stuff.py
When I execute the test I get an exception with the message "attached to a different loop". Digging into that matter I found that pytest-asyncio creates a new event_loop for each test case (right?). The Elasticsearch client however, takes the default loop on instantiation and sticks with it. So I tried to convince it to use the pytest-asyncio event_loop like so:
This however gives me another exception:
How am I supposed to test this scenario?
the first thing you can try is this:
i.e. make your app fixture depend on the event loop fixture. This should make your client instance get the loop actually used in the test (even if you don't actually use the argument, the event loop will get installed as the default loop for the duration of the test). This will also make your client fixture function-scoped, but it's a good starting point.
Hi Tinche, thanks for the incredibly fast response. You suggestions seems to work. However "This will also make your client fixture function-scoped" is something I'd rather like to avoid as it doesn't exactly increase the speed of the tests. What's the rationale for pytest-asyncio to create a new loop for each test? Not to share resources between tests? Maybe your suggestion is the only viable solution then.
Any idea, why my attempt to inject the loop into the client does not work? Cannot make any sense of the error message.
The AsyncElasticsearch instance probably grabs the loop and uses it somewhere before you can change it in the test.
Yeah, ideally tests should run in total isolation. The reason why your client fixture must be function scoped is that the event loop fixture is function scoped. You can override the event loop fixture to be session scoped though. I'm not sure this is tested but it should be possible :)
Make a conftest.py file in your tests directory, and put this in it: