【问题标题】:dependency_overrides does not override dependencydependency_overrides 不会覆盖依赖项
【发布时间】:2019-11-13 11:08:53
【问题描述】:

下面的 FastApi 测试应该使用我的 get_mock_db 函数而不是 get_db 函数,但事实并非如此。目前测试失败,因为它使用了真实的数据库。

def get_mock_db():
    example_todo = Todo(title="test title", done=True, id=1)

    class MockDb:
        def query(self, _model):
            mock = Mock()
            mock.get = lambda _param: example_todo

        def all(self):
            return [example_todo]

        def add(self):
            pass

        def commit(self):
            pass

        def refresh(self, todo: CreateTodo):
            return Todo(title=todo.title, done=todo.done, id=1)

    return MockDb()


client = TestClient(app)


app.dependency_overrides[get_db] = get_mock_db


def test_get_all():
    response = client.get("/api/v1/todo")
    assert response.status_code == 200
    assert response.json() == [
        {
            "title": "test title",
            "done": True,
            "id": 1,
        }
    ]

【问题讨论】:

  • 您可能必须添加使用 get_db 的代码才能查看发生了什么。

标签: python python-3.x dependency-injection fastapi


【解决方案1】:

关键是要理解dependency_overrides 只是一个字典。为了覆盖某些内容,您需要指定与原始依赖项匹配的键。

def get_db():
   return {'db': RealDb()}

def home(commons: dict= Depends(get_db))
   commons['db'].doStuff()
 
app.dependency_overrides[get_db] = lambda: {'db': MockDb()}

在这里,您在 Depends 函数中调用了对 get_db 函数的引用。然后你指的是与dependency_overrides[get_db] 完全相同的功能。因此它被覆盖。首先验证这两个中的“xxx”是否完全匹配:Depends(xxx) 和 dependency_overrides[xxx]。

我花了一些时间才意识到Depends 调用中的任何内容实际上都是依赖项的标识符。所以在这个例子中,标识符是函数 get_db 并且相同的函数被用作字典中的键。

因此,这意味着以下示例不起作用,因为您覆盖的不是为 Depends 指定的内容。

def get_db(connection_string):
   return {'db': RealDb(connection_string)}

def home(commons: dict= Depends(get_db(os.environ['connectionString']))
   commons['db'].doStuff()

# Does not work 
app.dependency_overrides[get_db] = lambda: {'db': MockDb()}

【讨论】:

    猜你喜欢
    • 2014-03-18
    • 1970-01-01
    • 2020-04-12
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2015-11-21
    • 2012-08-15
    相关资源
    最近更新 更多