Every second test fails with "RuntimeError: Event loop is closed" when re-using AsyncConnectionPool
#659
Unanswered
chbndrhnns
asked this question in
Q&A
Replies: 1 comment 2 replies
-
Hey @chbndrhnns — I believe your problem is occurring because the event loop is scoped per function but your pool exists in a broader scope and then cannot access the event loop its connections were created with to clean up resources. If you close the connection pool after each test run, all your tests pass: @pytest.mark.parametrize(
"count",
[
1,
2,
3,
4,
],
)
async def test_(count, adapter):
assert await adapter.request("GET", "http://jsonplaceholder.typicode.com/todos/1")
await adapter.aclose() You could do this in a separate fixture: @pytest.fixture(autouse=True)
async def close_adapter(adapter):
yield
await adapter.aclose() But at this point, you might as well context manage the pool correctly. Attempting to do this clarifies the issue: @pytest.fixture(scope="module")
async def adapter():
async with httpcore.AsyncConnectionPool() as pool:
yield pool
To resolve that, you can define an event loop that is not function scoped: @pytest.fixture(scope="session")
def event_loop(request):
"""
Redefine the event loop to support session/module-scoped fixtures;
see https://github.com/pytest-dev/pytest-asyncio/issues/68
"""
policy = asyncio.get_event_loop_policy()
loop = policy.new_event_loop()
try:
yield loop
finally:
loop.close() Now all of your tests pass. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
I first noticed the issue with httpx and was able to narrow it down to this snippet which exposes the same behaviour but with a shorter exception trace.
I expect four passing tests but every second test is failing.
A naive solution is to change the fixture scope from
module
tofunction
. However, this impacts me in testing my application which uses httpx deep down under the hood.This is the error I see:
Beta Was this translation helpful? Give feedback.
All reactions