简体   繁体   English

运行 pytest 时出现异常“没有与模型关联的 DB”

[英]Exception "No DB associated to model" when running pytest

I am developing a service with FastAPI and Tortoise-ORM.我正在使用 FastAPI 和 Tortoise-ORM 开发服务。

When I use the interface generated by Swagger UI or curl, I can add and read the data successfully.当我使用Swagger UI或curl生成的接口时,可以成功添加和读取数据。

However, when I run pytest, tests fail with the following error message: tortoise.exceptions.ConfigurationError: No DB associated to model但是,当我运行 pytest 时,测试失败并显示以下错误消息: 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.请记住,该错误仅在使用 pytest 时发生,我认为问题是某些配置错误或测试脚本中缺少,但我找不到原因。

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: test_1.py 文件如下:

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:应用程序.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.在我的情况下,不是 register_tortoise function 需要在 on_event('startup') function 中,而是我的代码的另一部分在初始化之前尝试使用数据库。 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.我将这段代码(具有查询的 class 的实例化)移动到 on_event('startup') 块中,一切都开始工作了。 Basically, if you have any db queries that fire before register_tortoise, it will fail.基本上,如果您有任何在 register_tortoise 之前触发的数据库查询,它将失败。 (That's why it works with Swagger) (这就是它与 Swagger 一起使用的原因)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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