如何使用FastAPI和Tortoise ORM正确配置pytest?

问题描述 投票:0回答:1

我正在尝试配置测试。根据tortoise orm文档我创建了这个测试配置文件:

import pytest
from fastapi.testclient import TestClient
from tortoise.contrib.test import finalizer, initializer

import app.main as main
from app.core.config import settings

@pytest.fixture(scope="session", autouse=True)
def initialize_tests(request):
    db_url = "postgres://USERNAME_HERE:[email protected]:5432/test"
    initializer(
        [
            "app.models",
        ],
        db_url=db_url,
        app_label="models"
    )
    print("initialize_tests")
    request.add_finaliser(finalizer)

@pytest.fixture(scope="session")
def client():
    app = main.create_application()
    with TestClient(app) as client:
        print("client")
        yield client

测试文件如下所示:

def test_get(client):
    response = client.get("/v1/url/")
    assert response.status_code == 200

我尝试运行测试,但收到此错误:

asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress

我发现有些用户不使用初始化程序和终结程序,而是手动完成所有操作。 使用 Tortoise-ORM 在 FastAPI 中进行测试 https://stackoverflow.com/a/66907531 但这看起来并不是一个明确的解决方案。 问题:有没有办法使用初始化器和终结器使测试工作?

python postgresql pytest fastapi tortoise-orm
1个回答
0
投票
import pytest
from fastapi.testclient import TestClient
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
from main import app

@pytest.fixture(scope="module")
def test_client():
    # Register Tortoise with a test database
    register_tortoise(
        app,
        db_url="sqlite://:memory:",  # In-memory test database
        modules={"models": ["src.models"]},  # Path to your models
        generate_schemas=True,  # Automatically generate schemas for testing
        add_exception_handlers=True,  # Include exception handlers
    )
    with TestClient(app) as c:
        yield c

这对我有用:)

© www.soinside.com 2019 - 2024. All rights reserved.