问题描述
我正在使用 FastAPI 和 Tortoise-ORM 开发一项服务。
当我使用Swagger UI或curl生成的界面时,可以成功添加和读取数据。
但是,当我运行 pytest 时,测试失败并显示以下错误消息:tortoise.exceptions.ConfigurationError: No DB associated to model
谨记该错误仅在使用pytest时发生,我认为问题是某些配置错误或测试脚本中缺失,但我找不到原因。
有人有什么想法吗?
我的结构如下:
src /
+--api /
| +-__ init__.py
| +-app.py
| +-main.py
| +-models.py
| +-routers.py
| +-schemas.py
+--tests /
+-__ init__.py
+-test_subjects.py
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:
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)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)