正确模拟数据存储查询

Properly mock datastore Query

我正在尝试在 Python 中模拟 数据存储 Client 交互。

因此我修补了 Query:

from google.cloud.datastore import Client
from unittest.mock import patch


def foo():
    client = Client()
    try:
        ancestor = client.key("anc", "123")
        query = client.query(kind="child", ancestor=ancestor)
        for q in query.fetch(limit=1):
            assert False, "Successfully mocked everything"
    finally:
        client.close()

p = patch(
    "google.cloud.datastore.client.Query",
    spec=["__call__", "fetch"],
)
with p as mock_klass:
    mock_klass.fetch.return_value = [1, 2] # This line seems to have no effect?
    foo()
    mock_klass.fetch.assert_called_once()

然而,当我执行代码时,assert_called_once 失败了。

我似乎在模拟时做错了什么,但不知道如何让它工作。 如果有人能指出如何让它工作,将不胜感激。

需要将 mock_klass.fetch 替换为 mock_klass.return_value.fetch