0

Error : E RuntimeError: Task <Task pending name='Task-3' coro=<test_index() running at /home/chintal/Desktop/yt-stories/fastapi-boilerplate/src/test/user/test_controller.py:41> cb=[_run_until_complete_cb() at /usr/lib/python3.8/asyncio/base_events.py:184, WorkerThread.stop()]> got Future attached to a different loop asyncpg/protocol/protocol.pyx:338: RuntimeError

import pytest
from httpx import AsyncClient 
from app.server import app

"""Use below code to test async functions"""


@pytest.mark.asyncio
async def test_index_one():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/v1/user/test/user/2")
    assert response.status_code == 200

@pytest.mark.asyncio
async def test_index():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/v1/user/test/user/1")
    assert response.status_code == 200
larsks
  • 277,717
  • 41
  • 399
  • 399
  • 1
    Any reason for not using the built-in `TestClient` in FastAPI? – MatsLindh Jun 30 '22 at 10:01
  • for async testing fastapi documents had this AsyncClient example – maulik prajapati Jun 30 '22 at 12:07
  • Ah, I forgot about that. There's a note at the bottom showing this exact error: _If you encounter a RuntimeError: Task attached to a different loop when integrating asynchronous function calls in your tests (e.g. when using MongoDB's MotorClient) Remember to instantiate objects that need an event loop only within async functions, e.g. an '@app.on_event("startup") callback._ https://fastapi.tiangolo.com/advanced/async-tests/ – MatsLindh Jun 30 '22 at 12:13

1 Answers1

2

Yes, you can.

import asyncio

import pytest


@pytest.fixture(scope="session", autouse=True)
def event_loop():
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

Reference: https://github.com/pytest-dev/pytest-asyncio/issues/38#issuecomment-264418154

Marcelo Trylesinski
  • 634
  • 1
  • 5
  • 13