简体   繁体   中英

Exception "No DB associated to model" when running pytest

I am developing a service with FastAPI and Tortoise-ORM.

When I use the interface generated by Swagger UI or curl, I can add and read the data successfully.

However, when I run pytest, tests fail with the following error message: tortoise.exceptions.ConfigurationError: No DB associated to model

Bearing in mind that the error only occurs when pytest is used, I believe that the problem is some configuration that is wrong or is missing from the test scripts, but I can't find the cause.

Does anyone have any ideas?

My structure is as follows:

src /
     +--api /
     |      +-__ init__.py
     |      +-app.py
     |      +-main.py
     |      +-models.py
     |      +-routers.py
     |      +-schemas.py
     +--tests /
              +-__ init__.py
              +-test_subjects.py

The test_1.py file is as follows:

import pytest
from fastapi.testclient import TestClient
from api.main import app

client = TestClient(app)


def test_create_subject():
    response = await client.post(
        '/api/subject/',
        json={
            'name': 'Programming',
        },
    )

def test_read_subjects():
    response = client.get("/api/subjects/")
    assert response.status_code == 200

app.py:

from fastapi import FastAPI
from tortoise.contrib.fastapi import register_tortoise
from tortoise import Tortoise

def get_application():
    _app = FastAPI(title='MyProject')

    _app.add_middleware(
        CORSMiddleware,
        allow_credentials=True,
        allow_methods=['*'],
        allow_headers=['*'],
    )
    return _app

app = get_application()


@app.on_event('startup')
async def startup():
   register_tortoise(
        app,
        db_url='sqlite://db.sqlite3',
        modules={'models': ['api.models']},
        generate_schemas=True,
        add_exception_handlers=True,
    )

main.app:

import uvicorn
from .app import app
from .routers import subjects
from .schemas.subjects import SubjectSchema


app.include_router(subjects.router)


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

In my case it wasn't the register_tortoise function that needed to be in the on_event('startup') function, rather another part of my code that was trying to use the db before it was initialised. I moved this piece of code (the instantiation of the class that had the query) inside an on_event('startup') block and everything started working. Basically, if you have any db queries that fire before register_tortoise, it will fail. (That's why it works with Swagger)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM