【问题标题】:Properly mock datastore Query正确模拟数据存储查询
【发布时间】:2021-11-06 19:33:29
【问题描述】:

我正在尝试在 Python 中模拟 datastore 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 失败。

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

【问题讨论】:

    标签: python google-cloud-platform google-cloud-datastore python-mock


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      相关资源
      最近更新 更多