English 中文(简体)
fastapi pytest: how to override a fastapi dependency that accepts arguments?
原标题:

I have this small MCVE FastAPI application which works fine as expected:

# run.py
import uvicorn
from fastapi import FastAPI, Depends

app = FastAPI()


###########

def dep_with_arg(inp):
    def sub_dep():
        return inp
    return sub_dep


@app.get("/a")
def a(v: str = Depends(dep_with_arg("a"))):
    return v


###########


def dep_without_arg():
    return "b"


@app.get("/b")
def b(v: str = Depends(dep_without_arg)):
    return v


###########


def main():
    uvicorn.run(
        "run:app",
        host="0.0.0.0",
        reload=True,
        port=8000,
        workers=1
    )


if __name__ == "__main__":
    main()

notice the difference between the dependencies of the /a and /b endpoints. in the /a endpoint, I have created a dependency that accepts an argument. both endpoints are working as expected when I call them.

I now try to test the endpoints while overriding the dependencies as below:

from run import app, dep_without_arg, dep_with_arg
from starlette.testclient import TestClient


def test_b():
    def dep_override_for_dep_without_arg():
        return "bbb"

    test_client = TestClient(app=app)
    test_client.app.dependency_overrides[dep_without_arg] = dep_override_for_dep_without_arg
    resp = test_client.get("/b")
    resp_json = resp.json()
    assert resp_json == "bbb"


###########


def test_a_method_1():
    def dep_override_for_dep_with_arg(inp):
        def sub_dep():
            return "aaa"

        return sub_dep

    test_client = TestClient(app=app)
    test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg
    resp = test_client.get(
        "/a",
    )
    resp_json = resp.json()
    assert resp_json == "aaa"


def test_a_method_2():
    def dep_override_for_dep_with_arg(inp):
        return "aaa"

    test_client = TestClient(app=app)
    test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg
    resp = test_client.get(
        "/a",
    )
    resp_json = resp.json()
    assert resp_json == "aaa"


def test_a_method_3():
    def dep_override_for_dep_with_arg(inp):
        return "aaa"

    test_client = TestClient(app=app)
    test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg("aaa")
    resp = test_client.get(
        "/a",
    )
    resp_json = resp.json()
    assert resp_json == "aaa"


def test_a_method_4():
    def dep_override_for_dep_with_arg():
        return "aaa"

    test_client = TestClient(app=app)
    test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg
    resp = test_client.get(
        "/a",
    )
    resp_json = resp.json()
    assert resp_json == "aaa"

test_b passes as expected but all the other tests fail:

FAILED test.py::test_a_method_1 - AssertionError: assert  a  ==  aaa 
FAILED test.py::test_a_method_2 - AssertionError: assert  a  ==  aaa 
FAILED test.py::test_a_method_3 - AssertionError: assert  a  ==  aaa 
FAILED test.py::test_a_method_4 - AssertionError: assert  a  ==  aaa 

How should I override dep_with_arg in the example above?

问题回答

The error you are getting is because the dep_with_arg dependency expects an argument, but the dep_override_for_dep_with_arg function you are passing to app.dependency_overrides does not take any arguments.

To fix this, you need to update the dep_override_for_dep_with_arg function to take an argument and return the value of that argument. For example:

def dep_override_for_dep_with_arg(inp):
    def sub_dep():
        return inp

    return sub_dep

This will allow you to override the dep_with_arg dependency with the value "aaa". For example:

test_client = TestClient(app=app)
test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg("aaa")
resp = test_client.get(
    "/a",
)
resp_json = resp.json()
assert resp_json == "aaa"

This will now pass the test.

Here is the full code with the fix:

import uvicorn
from fastapi import FastAPI, Depends

app = FastAPI()


def dep_with_arg(inp):
    def sub_dep():
        return inp
    return sub_dep


@app.get("/a")
def a(v: str = Depends(dep_with_arg("a"))):
    return v


def dep_without_arg():
    return "b"


@app.get("/b")
def b(v: str = Depends(dep_without_arg)):
    return v


def dep_override_for_dep_with_arg(inp):
    def sub_dep():
        return inp

    return sub_dep


def test_b():
    def dep_override_for_dep_without_arg():
        return "bbb"

    test_client = TestClient(app=app)
    test_client.app.dependency_overrides[dep_without_arg] = dep_override_for_dep_without_arg
    resp = test_client.get("/b")
    resp_json = resp.json()
    assert resp_json == "bbb"


def test_a():
    test_client = TestClient(app=app)
    test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg("aaa")
    resp = test_client.get("/a")
    resp_json = resp.json()
    assert resp_json == "aaa"


if __name__ == "__main__":
    uvicorn.run(
        "run:app",
        host="0.0.0.0",
        reload=True,
        port=8000,
        workers=1
    )




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签