0

In my fastapi application i have written test cases using pytest. My tests folder includes

conftest.py

import pytest
from fastapi.testclient import TestClient
from main import app


@pytest.fixture(scope="session")
def test_client():
    client = TestClient(app)
    yield client

test_cases.py

def test_get_courses(test_client):
    response = test_client.get("/courses/")
    assert response.status_code == 200


def test_get_course_overview(test_client):
    course_id = "66c21d35c014f6ce1d0c29ab"
    response = test_client.get(f"/courses/{course_id}")
    print(response.json())
    assert response.status_code == 200

When i run single test cases no issue but if i run all test cases it give below error for printing response.json

{'status': False, 'status_code': 500, 'detail': 'Event loop is closed'}

I have use session based scope and also tried with pytest-asyncio still the same.

Thanks for solutions.

1 Answer 1

0

Try to add fixture which will create a new event loop for an each test case:

@pytest.fixture(scope="session")
def event_loop(request):
    """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()

It helped me when a had a similar issue.

Not the answer you're looking for? Browse other questions tagged or ask your own question.