Problem overriding dependency with a functools.partial(Dep, ...) where Dep takes **kwargs #8817
-
First Check
Commit to Help
Example Codeimport functools
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient
app = FastAPI()
class Dep:
def __init__(self, _, **kwargs):
pass
def get_dep():
return Dep(1)
@app.get("/")
async def root(dep: Dep = Depends(get_dep)):
print("root called")
return "a"
def test_failing():
app.dependency_overrides[get_dep] = functools.partial(Dep, 1)
assert TestClient(app).get("/").json() == "a"
app.dependency_overrides = {}
def test_passing():
app.dependency_overrides[get_dep] = lambda: Dep(1)
assert TestClient(app).get("/").json() == "a"
app.dependency_overrides = {}DescriptionI'm attempting to override a dependency with a
It seems to be due to Operating SystemLinux Operating System DetailsUbuntu 20.04.3 LTS FastAPI Version0.68.0 Python VersionPython 3.8.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
|
Can you change the order of those tests? |
Beta Was this translation helpful? Give feedback.
-
|
Yes, the result is the same. But now I got a little further and can cut Databases out of the equation with the following revised MRE: import functools
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient
app = FastAPI()
class Dep:
def __init__(self, _, **kwargs):
pass
def get_dep():
return Dep(1)
@app.get("/")
async def root(dep: Dep = Depends(get_dep)):
print("root called")
return "a"
def test_failing():
app.dependency_overrides[get_dep] = functools.partial(Dep, 1)
assert TestClient(app).get("/").json() == "a"
app.dependency_overrides = {}
def test_passing():
app.dependency_overrides[get_dep] = lambda: Dep(1)
assert TestClient(app).get("/").json() == "a"
app.dependency_overrides = {}This fails in the same way. The problem seems to appear because Dep takes a I'll update issue title and description. EDIT: Done. |
Beta Was this translation helpful? Give feedback.
-
|
When you override dependency by function with Just use |
Beta Was this translation helpful? Give feedback.
When you override dependency by function with
**kwargs, FastAPI will try to resolve dependencies, findkwargsparameter and treat it as a requiredQueryparameter.You don't pass it, so you have error 422.
Just use
lambda: Dep(1)or create new function that will declare parameters that are really needed and pass them to the__init__ofDep