我在运行测试时遇到问题。我使用FastAPI和Tortoise ORM,通常我使用sqlite文件将数据存储在文件中(现在,我可能会在生产中使用postges),一切都很好。当我试图运行测试时,问题出现了。我想覆盖数据库URL在内存数据库,但它不工作,并使用这个"生产"。数据库。当我在删除db文件后运行test时,它们通过了,但下一次没有,因为我在测试期间创建的用户已经存在。我如何强制我的配置覆盖db url?
main.py
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm
from tortoise.contrib.fastapi import register_tortoise
import users.router
from common.authentication import authenticate_user, create_access_token
app = FastAPI()
app.include_router(users.router.router)
@app.post("/obtain-token")
async def obtain_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = await authenticate_user(form_data.username, form_data.password)
access_token_expires = timedelta(minutes=5)
access_token = await create_access_token(
user, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
register_tortoise(
app,
db_url="sqlite://db.sqlite3",
modules={"models": ["users.models"]},
generate_schemas=True,
add_exception_handlers=True
)
conftest.py
import os
from typing import Generator
import pytest
from fastapi.testclient import TestClient
from tortoise.contrib.test import finalizer, initializer
from ..main import app
DB_URL = "sqlite://:memory:"
@pytest.fixture(scope="session")
def event_loop():
return asyncio.get_event_loop()
@pytest.fixture(scope="session")
def client() -> Generator:
initializer(
db_url=DB_URL,
modules=["users.models"],
)
with TestClient(app) as c:
yield c
finalizer()
test_users.py
from starlette.testclient import TestClient
def test_create_user(client: TestClient, event_loop: asyncio.AbstractEventLoop):
user_data = {
"username": "testUser",
"password": "testPassword",
"name": "testName",
"last_name": "testLastName",
"role": 1
}
response = client.post("/user/", json=user_data)
assert response.status_code == 200
我尝试在环境变量中设置URL,并在pytest fixture中更改它,但它没有帮助。
我不想在测试后删除db文件,因为它可以删除我用于开发应用程序和手动测试的数据。
遇到同样的问题。我的解决方案是下载一个更高的版本(0.17.0是稳定的)