Dependency override not working #6245
-
First Check
Commit to Help
Example Codefrom fastapi import APIRouter, Depends
from ..dependencies.get_user import get_user
router = APIRouter()
@router.post("")
async def my_func(user: str = Depends(get_user)):
...
return {...}DescriptionI'm trying to run some tests with pytest against the API but my dependency override is not working. It still tries to run the function as if there was no override. All other tests where we don't need to override a dependency work fine
from fastapi import Header
from typing import Union
def get_user(xyz: Union[str, None] = Header(default=...)):
return ...
from fastapi import APIRouter, Depends
from ..dependencies.get_user import get_user
router = APIRouter()
@router.post("")
async def my_func(user: str = Depends(get_user)):
...
return {...}
import responses
from fastapi.testclient import TestClient
from ...main import app
from ..dependencies.get_user import get_user
def override_get_user():
return "asdf"
app.dependency_overrides[get_user] = override_get_user
client = TestClient(app)
def test_my_func():
resp = client.post("/api/...", headers={"xyz": "dummy"})
assert resp.status_code == 200
assert resp.json() == {...}Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.78.0 Python Version3.9.13 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 3 replies
-
|
You need use |
Beta Was this translation helpful? Give feedback.
-
|
Thanks, I've just tried that but it didn't work either. I've updated the main post with your suggestion |
Beta Was this translation helpful? Give feedback.
-
|
in from api.dependencies.get_user import get_userinstead of: from ..dependencies.get_user import get_userseems to have done the trick |
Beta Was this translation helpful? Give feedback.
-
|
@chrobotm thank you for putting an end to two days of debugging dependency injections. Just needed to find the right comment :( |
Beta Was this translation helpful? Give feedback.
-
|
If anyone has more trouble with this: Mounted sub apps using e.g.: app.mount(path, subapp)won't inherit |
Beta Was this translation helpful? Give feedback.
-
|
hey everyone I'm having a similar issue where I am trying to test reading a user at /users endpoint ,however the app seems to read from real db rather than test db , the override_get_db doesn't seem to run . Any suggestions ? |
Beta Was this translation helpful? Give feedback.
-
|
Can you try something like that? |
Beta Was this translation helpful? Give feedback.
If anyone has more trouble with this: Mounted sub apps using e.g.:
won't inherit
dependency_overridesand will need to have the overrides registered again manually.