[Python] How to properly configure pytest with FastAPI and Tortoise ORM?

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to configure the tests. According to the tortoise orm documentation I create this test configuration file:

    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:SECRET_PASS_HERE@127.0.0.1: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


    And the test file looks like this:

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


    I try to run the tests, but I get this error:

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


    I have found that some users don't use initializer and finalizer and do everything manually. Testing in FastAPI using Tortoise-ORM https://stackoverflow.com/a/66907531 But that doesn't look like the clear solution. Question: Is there a way to make the tests work using initializer and finalizer?

    Continue reading...

Compartilhe esta Página