question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

async test is RuntimeError: no running event loop in router with await

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import FastAPI
import asyncio
import pytest
from httpx import AsyncClient


app = FastAPI()


async def query_db():
    await asyncio.sleep(0.1)    # add this, it's error
    return {'id': 1, 'data': 'hi'}


@app.get('/')
async def get_data():
    data = await query_db()
    return data


@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

Description

execute pytest in terminal it 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

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
blokjecommented, Jan 24, 2022

This is not a FastAPI issue but is related to AnyIO. More information about testing with AnyIO can be found at https://anyio.readthedocs.io/en/stable/testing.html.

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'
0reactions
MartinScherecommented, Jul 7, 2022

@CarlosLannister The base URL needs to be http://test:

@pytest.fixture(scope='function')
async def client():
    async with AsyncClient(app=app, base_url='http://test') as client:
        yield client
Read more comments on GitHub >

github_iconTop Results From Across the Web

Asyncio in corroutine RuntimeError: no running event loop
As it seems from the Traceback log it is look like you are trying to add tasks to not running event loop.
Read more >
fastapi asyncio.run() cannot be called from a running event loop
In your case, jupyter (IPython ≥ 7.0) is already running an event loop:You can now use async/await at the top level in the...
Read more >
Using async and await — Flask Documentation (2.2.x)
When a request comes in to an async view, Flask will start an event loop in a thread, run the view function there,...
Read more >
Coroutines and Tasks — Python 3.11.1 documentation
Coroutines declared with the async/await syntax is the preferred way of writing ... RuntimeError is raised if there is no running loop in...
Read more >
tiangolo/fastapi - Gitter
get_event_loop().run_until_complete(async_function()) so that you'll reuse the running event loop, but I'm running in different thread, which don't run ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found