How to set event loop while testing app using pytest-asyncio #8415
Replies: 5 comments 5 replies
-
Did you try adding a import asyncio
import pytest
@pytest.fixture(scope="session")
def event_loop():
"""Create an instance of the default event loop for each test case."""
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close() I have had no issues with asyncpg / SQLA with the above |
Beta Was this translation helpful? Give feedback.
-
Hi @jgould22, and thanks for your answer. This solution is equivalent to the snippet described in my question, which unfortunately doesn't seem like a great option for two reasons:
|
Beta Was this translation helpful? Give feedback.
-
@PCanavelli @commentator8 let me know if it was helpful and if you have any questions:) |
Beta Was this translation helpful? Give feedback.
-
I have a SSE api, which returns an EventSourceResponse.
The unit test is
I still got an error:
|
Beta Was this translation helpful? Give feedback.
-
Using AsyncClient from httpx library instead of fastapi TestClient works for me.
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
Hi everyone,
I need some help regarding the best way to test a FastAPI app interacting with a postgresql databse through asyncpg. More precisely, I am trying to swap psycopg2 for asyncpg, and rewriting all necessary methods and unit tests to make them async.
I'm using pytest-asyncio to unit test the newly-async code. Testing calls to the API is proving problematic: all async tests now fail with the dreaded
Future <Future pending cb=[Protocol._on_waiter_completed()]> attached to a different loop
.From what I could find on pytest-asyncio's github, this kind of issue is not easily solvable on their end, and is usually addressed by creating an
event_loop
fixture and passing it to the app being tested with something like:However, this type of fix was suggested in cases that don't involve FastAPI/Uvicorn, and I am at a loss as to how to force-set FastAPI's event loop to use the test fixture.
Could anyone suggest the best way to do so, or an alternative method to solve this testing issue?
I've tried to submit a code snipped encapsulating the main details of my use case: the router structure, the db session generation and usage, and the test client fixture. Please feel free to request a rewrite of the example or additional info as needed.
Thanks in advance for your help
Operating System
Linux
Operating System Details
Debian
FastAPI Version
fastapi==0.85.0
Python Version
Python 3.9.2
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions