-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Description
Hi!
I'm trying to test my FastAPI application and got into some trouble with app.dependency_overrides.
I'm using parametrized dependencies and when I'm trying to add the dependency to the dependency_overrides dict and run my tests, the tests runs with the original dependency instead of the mock dependency I created.
When I use regular function, it works fine. The problem occurs only with class dependencies.
Here what I tried to do:
class NameDependency:
def __init__(self, name: str):
self._name = name
def __call__(self) -> str:
return self._name
app = FastAPI()
@app.get('/')
async def hello(name: str = Depends(NameDependency('foo'))):
return {'message': f'hello {name}'}
client = TestClient(app)
app.dependency_overrides[NameDependency] = Mock(return_value='bar')
def test_hello():
res = client.get('/')
assert res.json()['message'] == 'hello bar'
When I run this test, instead of passing, I get AssertionError hello foo == hello bar.
I also tried the following alternatives:
# 1st alternative
app.dependency_overrides[NameDependency('foo')] = Mock(return_value='bar')
# 2nd alternative
app.dependency_overrides[NameDependency] = Mock(return_value=Mock(return_value='bar'))
I've tried more but I could not find the correct way to do that.
I think I'm missing something and I'll glad if someone can help me. I didn't find an example to this online and I didn't see this in the docs either.
Thanks for anyone that will help!