【问题标题】:Problem with tests in FastAPI and Tortoise ORMFastAPI 和 Tortoise ORM 中的测试问题
【发布时间】:2022-08-05 03:51:01
【问题描述】:

我在运行测试时遇到问题。我将 FastAPI 与 Tortoise ORM 一起使用,通常我使用 sqlite 文件将我的数据存储在一个文件中(现在,我可能会在生产中使用 postges)并且一切正常。当我尝试运行测试时,问题就出现了。我想将数据库 URL 覆盖为内存数据库,但它不起作用,而是使用此“生产”数据库。当我在删除 db 文件后运行测试时,它们通过了,但下一次没有,因为我在测试期间创建的用户已经存在。如何强制我的配置覆盖 db url?

主文件


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 夹具中更改它,但它没有帮助。

我不想在测试后删除 db 文件,因为它可能会删除我用于开发应用程序和手动测试的数据。

    标签: python database pytest fastapi tortoise-orm


    【解决方案1】:

    堆栈有同样的问题。我的解决方案是下载更高版本(0.17.0 稳定)

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 2020-12-01
      • 2022-08-20
      • 2021-10-21
      • 2021-08-30
      • 2021-02-06
      • 2021-04-16
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多