[Python] Testing in FastAPI using Tortoise-ORM

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write some async tests in FastAPI using Tortoise ORM under Python 3.8 but I keep getting the same errors (seen at the end). I've been trying to figure this out for the past few days but somehow all my recent efforts in creating tests have been unsuccessful.

    I'm following the fastapi docs and tortoise docs on this one.

    main.py

    # UserPy is a pydantic model
    @app.post('/testpost')
    async def world(user: UserPy) -> UserPy:
    await User.create(**user.dict())
    # Just returns the user model
    return user


    simple_test.py

    from fastapi.testclient import TestClient
    from httpx import AsyncClient

    @pytest.fixture
    def client1():
    with TestClient(app) as tc:
    yield tc

    @pytest.fixture
    def client2():
    initializer(DATABASE_MODELS, DATABASE_URL)
    with TestClient(app) as tc:
    yield tc
    finalizer()

    @pytest.fixture
    def event_loop(client2): # Been using client1 and client2 on this
    yield client2.task.get_loop()


    # The test
    @pytest.mark.asyncio
    def test_testpost(client2, event_loop):
    name, age = ['sam', 99]
    data = json.dumps(dict(username=name, age=age))
    res = client2.post('/testpost', data=data)
    assert res.status_code == 200

    # Sample query
    async def getx(id):
    return await User.get(pk=id)
    x = event_loop.run_until_complete(getx(123))
    assert x.id == 123

    # end of code


    My errors vary on whether I'm usinng client1 or client2

    Using client1 error

    RuntimeError: Task <Task pending name='Task-9' coro=<TestClient.wait_shutdown() running at <my virtualenv path>/site-packages/starlette/testclient.py:487> cb=[_run_until_complete_cb() at /usr/lib/python3.8/asyncio/base_events.py:184]> got Future <Future pending> attached to a different loop


    Using client2 error

    asyncpg.exceptions.ObjectInUseError: cannot drop the currently open database


    Oh, I've also tried using httpx.AsyncClient but still no success (and more errors). Any ideas because I'm out of my own.

    Continue reading...

Compartilhe esta Página