'Mock Dependency classes in FastAPI

I have an api which is representative of the structure of:

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. 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?



Solution 1:[1]

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)

Solution 2:[2]

You can try to use the FastApi way of overriding dependencies. I created a wrapper library which adds a pytest fixture named: fastapi_dep.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jossefaz
Solution 2 Peter K