This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
async test is RuntimeError: no running event loop in router with await #4473
Comments
This is not a FastAPI issue but is related to In this case you are missing an instruction on which backend to use for testing. By adding the following snippet to your code (copied from link above) your test will run: @pytest.fixture
def anyio_backend():
return 'asyncio' |
@blokje Thank you for your reply. It does solve the above problem. Sorry, I'm not good at writing asynchronous code. But in fact, my code should be like this. Example Codefrom fastapi import FastAPI
import pytest
from httpx import AsyncClient
from motor.motor_asyncio import AsyncIOMotorClient
app = FastAPI()
client = AsyncIOMotorClient(f'mongodb://root:123456@127.0.0.1:27017/my_db')
db = client['my_db']
@app.get('/')
async def get_data():
data = await db['users'].find().to_list(None)
data = [{k:v for k,v in d.items() if k != '_id'} for d in data] # delete '_id' field
return data
@pytest.fixture
def anyio_backend():
return 'asyncio'
@pytest.mark.anyio
async def test_get_data():
# async with AsyncClient(base_url='http://127.0.0.1:8000') as ac: # don't use `app=app`, need manual launch server, but it's ok.
async with AsyncClient(app=app, base_url='http://127.0.0.1:8000') as ac:
response = await ac.get('/')
assert response.status_code == 200 DescriptionI get this error: |
there is an motor init error somewhere introduced with 0.69 and any.io, so this could be similar you can try: I found this solution here: encode/starlette#1315 |
I cannot reproduce this anymore... 🤔 It works fine here. |
@Kludex because you use the
in your code ;) The documentation still needs an update. |
I am receiving the same error if I extend @Kludex code and add some value in ac.get
|
If I manually launch the server seems to be working
|
@CarlosLannister The base URL needs to be @pytest.fixture(scope='function')
async def client():
async with AsyncClient(app=app, base_url='http://test') as client:
yield client |
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
First Check
Commit to Help
Example Code
Description
execute
pytest
in terminalit is raise
RuntimeError: no running event loop
.in fact, it is
RuntimeError: Event loop is closed
in my project.Operating System
Linux
Operating System Details
ubuntu20.04
FastAPI Version
0.72.0
Python Version
3.8.10
Additional Context
No response
The text was updated successfully, but these errors were encountered: