我试图在FastAPI中使用Python3.8下的Tortoise ORM编写一些异步测试,但我一直收到相同的错误(见结尾)。在过去的几天里,我一直在试图弄明白这一点,但不知何故,我最近在创建测试方面的所有努力都没有成功
我正在关注这个问题上的fastapi docs和tortoise docs
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
我的错误取决于我使用的是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
,但仍然没有成功(还有更多错误)。任何想法,因为我没有自己的想法
我花了大约一个小时来完成异步测试。以下是一个例子: (需要Python3.8+)
models/__init__.py
演示的源代码已发布到github: https://github.com/waketzheng/fastapi-tortoise-pytest-demo.git
相关问题 更多 >
编程相关推荐