使用 Tortoise-ORM 在 FastAPI 中进行测试

问题描述

我正在尝试在 Python 3.8 下使用 FastAPITortoise ORM 中编写一些异步测试,但我不断收到相同的错误(见最后)。过去几天我一直在努力解决这个问题,但不知何故,我最近在创建测试方面的所有努力都没有成功。

我正在关注这方面的 fastapi docstortoise docs

ma​​in.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

我的错误因我使用的是 client1 还是 client2

使用 client1 错误

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

使用 client2 错误

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

哦,我也试过使用 httpx.Asyncclient 但仍然没有成功(而且错误更多)。任何想法,因为我不是我自己的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)