我是 FastAPI 的新手,我已經實作了所有東西,但是在測驗 API 時,我無法覆寫依賴項。
這是我的代碼:
測驗控制器.py
import pytest
from starlette.testclient import TestClient
from app.main import app
from app.core.manager_imp import ManagerImp
@pytest.fixture()
def client():
with TestClient(app) as test_client:
yield test_client
async def over_create_record():
return {"msg": "inserted successfully"}
app.dependency_overrides[ManagerImp.create_record] = over_create_record
def test_post(client):
data = {"name": "John", "email": "[email protected]"}
response = client.post("/person/", json=data)
assert response.status_code == 200
assert response.json() == {"msg": "inserted successfully"}
控制器.py
from app.controllers.v1.controller import Controller
from fastapi import status, HTTPException
from app.models.taxslip import Person
from app.core.manager_imp import ManagerImp
from app.core.duplicate_exception import DuplicateException
from fastapi_utils.cbv import cbv
from fastapi_utils.inferring_router import InferringRouter
router = InferringRouter(tags=["Person"])
@cbv(router)
class ControllerImp(Controller):
manager = ManagerImp()
@router.post("/person/")
async def create_record(self, person: Person):
"""
Person: A person object
returns response if the person was inserted into the database
"""
try:
response = await self.manager.create_record(person.dict())
return response
except DuplicateException as e:
return e
manager_imp.py
from fastapi import HTTPException, status
from app.database.database_imp import DatabaseImp
from app.core.manager import Manager
from app.core.duplicate_exception import DuplicateException
class ManagerImp(Manager):
database = DatabaseImp()
async def create_record(self, taxslip: dict):
try:
response = await self.database.add(taxslip)
return response
except DuplicateException:
raise HTTPException(409, "Duplicate data")
在測驗中,我想從 ManagerImp 類中重寫 create_record 函式,以便我可以得到這個回應{"msg": "inserted successfully"}。基本上,我想模擬 ManagerImp create_record 函式。如您所見,我已經嘗試過,test_controller.py但我仍然得到原始回復。
uj5u.com熱心網友回復:
你沒有使用依賴注入系統來獲取ManagerImp.create_record函式,所以沒有什么可以覆寫的。
由于您沒有使用 FastAPIDepends來獲取依賴項 - FastAPI 無法回傳替代函式。
在您的情況下,您需要使用常規的模擬庫,例如 unittest.mock 或pytest-mock。
我還想指出,默認情況下,像您在此處所做的那樣初始化共享依賴項將在所有實體之間共享相同的實體,ControllerImp而不是為ControllerImp.
cbv 裝飾器改變了一些東西,如檔案中所述:
對于每個共享依賴項,添加一個值為 type 的類屬性
Depends
因此,要使其與 FastAPI 的處理方式相匹配,并使cbv裝飾器按您的意愿作業:
def get_manager():
return ManagerImp()
@cbv(router)
class ControllerImp(Controller):
manager = Depends(get_manager)
當你這樣做時,你可以dependency_overrides按照你的計劃使用:
app.dependency_overrides[get_manager] = lambda: return MyFakeManager()
如果您只想替換該create_record功能,您仍然必須使用常規模擬。
您還必須在測驗完成后洗掉依賴項覆寫,除非您希望它應用于所有測驗,因此yield請在您的夾具中使用,然后在夾具再次開始執行時洗掉覆寫。
uj5u.com熱心網友回復:
我認為你應該把你app.dependency_overrides的功能放在里面@pytest.fixture。試著把它放在你的client().
@pytest.fixture()
def client():
app.dependency_overrides[ManagerImp.create_record] = over_create_record
with TestClient(app) as test_client:
yield test_client
因為每個測驗都將運行新的app,這意味著它將從一個測驗重置所有內容,并且只有相關的東西與pytest該測驗系結。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/461182.html
