RuntimeError: Event loop is closed when using pytest-asyncio to test FastAPI routes

2024/9/29 19:17:46

I received the error

RuntimeError: Event loop is closed

each time I try to make more than one async call inside my test. I already tried to use all other suggestions from other Stack Overflow posts to rewrite the event_loop fixture but nothing works. I wonder what I'm missing?

Run test command:

python -m pytest tests/ --asyncio-mode=auto

requirements.txt

pytest==7.1.2
pytest-asyncio==0.18.3
pytest-html==3.1.1
pytest-metadata==2.0.1

test.py

async def test_user(test_client_fast_api):assert 200 == 200# works finerequest_first = test_client_fast_api.post("/first_route")# recieve RuntimeError: Event loop is closedrequest_second = test_client_fast_api.post("/second_route")

conftest.py

@pytest.fixture()
def event_loop():try:loop = asyncio.get_running_loop()except RuntimeError:loop = asyncio.new_event_loop()yield looploop.close()
Answer

Add a file conftest.py to the directory where the test script is placed.

And write the following code:

import pytest
from main import app
from httpx import AsyncClient@pytest.fixture(scope="session")
def anyio_backend():return "asyncio"@pytest.fixture(scope="session")
async def client():async with AsyncClient(app=app, base_url="http://test") as client:print("Client is ready")yield client

And then use those fixtures in your own test code. For example, this is the real test code for my own project. You can change it to your own.

import pytest
from httpx import AsyncClient@pytest.mark.anyio
async def test_run_not_exists_schedule(client: AsyncClient):response = await client.get("/schedule/list")assert response.status_code == 200schedules = response.json()["data"]["schedules"]schedules_exists = [i["id"] for i in schedules]not_exists_id = max(schedules_exists) + 1request_body = {"id": not_exists_id}response = await client.put("/schedule/run_cycle", data=request_body)assert response.status_code != 200  @pytest.mark.anyio
async def test_run_adfasdfw(client: AsyncClient):response = await client.get("/schedule/list")assert response.status_code == 200schedules = response.json()["data"]["schedules"]schedules_exists = [i["id"] for i in schedules]not_exists_id = max(schedules_exists) + 1request_body = {"id": not_exists_id}response = await client.put("/schedule/run_cycle", data=request_body)assert response.status_code != 200

Finally, run in the project's terminal

python -m pytest

If all goes well, it should be OK.

This may involve libraries that need to be installed.

pytest
httpx
https://en.xdnf.cn/q/71176.html

Related Q&A

Adjust threshold cros_val_score sklearn

There is a way to set the threshold cross_val_score sklearn?Ive trained a model, then I adjust the threshold to 0.22. The model in the following below :# Try with Threshold pred_proba = LGBM_Model.pre…

Efficiently insert multiple elements in a list (or another data structure) keeping their order

I have a list of items that should be inserted in a list-like data structure one after the other, and I have the indexes at which each item should be inserted. For example: items = [itemX, itemY, itemZ…

matplotlib versions =3 does not include a find()

I am running a very simple Python script: from tftb.generators import amgauss, fmlinI get this error: C:\Users\Anaconda3\envs\tf_gpu\lib\site-packages\tftb-0.0.1-py3.6.egg\tftb\processing\affine.py in …

How to fix Field defines a relation with the model auth.User, which has been swapped out

I am trying to change my user model to a custom one. I do not mind dropping my database and just using a new one, but when I try it to run makemigrations i get this errorbookings.Session.session_client…

Generate and parse Python code from C# application

I need to generate Python code to be more specific IronPyton. I also need to be able to parse the code and to load it into AST. I just started looking at some tools. I played with "Oslo" and …

An efficient way to calculate the mean of each column or row of non-zero elements

I have a numpy array for ratings given by users on movies. The rating is between 1 and 5, while 0 means that a user does not rate on a movie. I want to calculate the average rating of each movie, and t…

Selecting unique observations in a pandas data frame

I have a pandas data frame with a column uniqueid. I would like to remove all duplicates from the data frame based on this column, such that all remaining observations are unique.

GEdit/Python execution plugin?

Im just starting out learning python with GEdit plus various plugins as my IDE.Visual Studio/F# has a feature which permits the highlighting on a piece of text in the code window which then, on a keyp…

autoclass and instance attributes

According to the sphinx documentation, the .. autoattribute directive should be able to document instance attributes. However, if I do::.. currentmodule:: xml.etree.ElementTree.. autoclass:: ElementTre…

python sqlite3 update not updating

Question: Why is this sqlite3 statement not updating the record?Info:cur.execute(UPDATE workunits SET Completed=1 AND Returns=(?) WHERE PID=(?) AND Args=(?),(pickle.dumps(Ret),PID,Args))Im using py…