[英]Mock Dependency classes in FastAPI
I have an api which is representative of the structure of:我有一个代表以下结构的api:
from fastapi import FastAPI, Depends, Request, APIRouter
class SomeManager:
def get_value_from(self, s: str):
return GetValue(s, self)
class GetValue:
def __init__(self, value: str, parent: SomeManager):
self.str = str
def __call__(self, *args, **kwargs) -> str:
return self.str
api = FastAPI()
manager = SomeManager()
def generate_routes(m: SomeManager):
router = APIRouter(prefix="/test")
@router.get("")
def test(value = Depends(m.get_value_from("hi"))):
return value
return router
test_router = generate_routes(manager)
api.include_router(test_router)
I want to test my API, overwriting the m.get_value_from
method.我想测试我的 API,覆盖m.get_value_from
方法。 I was hoping to do something like:我希望做类似的事情:
def mock_get_value():
return "test_str"
monkeypatch.setattr(GetValue, "__call__", mock_get_value)
But it doesn't seem to work.但这似乎不起作用。
How can I mock this dependency?我如何模拟这种依赖关系?
You can mock the method itself您可以模拟方法本身
def mock_get_value(self, s: str):
return "test_str"
monkeypatch.setattr(SomeManager, "get_value_from", mock_get_value)
You can try to use the FastApi way of overriding dependencies .您可以尝试使用FastApi 覆盖依赖项的方式。 I created a wrapper library which adds a pytest fixture named: fastapi_dep
.我创建了一个包装库,它添加了一个名为: fastapi_dep
的 pytest 夹具。
Use it like so:像这样使用它:
def test_create_user(fastapi_dep):
def mock_get_value():
return "test_str"
with fastapi_dep(app).override({SomeManager.get_value_from: mock_get_value}):
response = client.post(....)
# the rest of your test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.