Reuse existing event loop if one is already running #546
-
When I run async tests using |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Just as a note (to help others that stumble upon this) there is a simple workaround. Install nest_asyncio and then put this into the root
|
Beta Was this translation helpful? Give feedback.
-
If I understand correctly, your question is why pytest-asyncio cannot reuse an already running loop. That's a fair point to make. When writing unit tests, it can be a good idea to test a unit in isolation. In order to exclude any potential side-effects, pytest-asyncio tries to run the test in a fresh event loop. By design, the event loops in asyncio are limited to one per thread. The loop schedules all the coroutines and other awaitables in a thread. In order to do so, it monitors things like network sockets and forwards data to the corresponding coroutine whenever new data is available. This is why loops cannot be easily nested. There are some ways around it, e.g. nest_asyncio or aioloop-proxy, but none of them are currently integrated into pytest-asyncio, You can reuse an event loop over multiple tests by reimplementing the Does this explanation help? |
Beta Was this translation helpful? Give feedback.
-
Hello, Now we have another solution: switching to pytest-playwright-asyncio. That implies updating existing tests to import from |
Beta Was this translation helpful? Give feedback.
Hello,
I've encountered the same case, it was actually caused by
playwright-pytest
as exposed in microsoft/playwright-pytest#240 (this discussion was also submitted as microsoft/playwright-pytest#167). On the pytest-asyncio side, reimplementing theevent_loop
fixture is deprecated since #587 .Now we have another solution: switching to pytest-playwright-asyncio. That implies updating existing tests to import from
playwright.async_api
, which also requires adding manyasync/await
and putting all tests in the same loop (at least because Playwright'sBrowser
is a session-wide fixture that tries to access the event loop... but settingasyncio_default_fixture_loop_scope = "session"
was not enou…