python - 在同一测试中模拟对同一功能的两个单独响应

标签 python python-2.7 unit-testing mocking

在我的previous问题,我问了如何在我的类中模拟一个包装 requests.get 的类。 answer如果我只调用一次 requests.get,则提供的效果很好。然而,事实证明我的类(class)比我举的例子更复杂。

我的类调用 request.get 两次。一次是在初始化时,因为它遇到了一个返回 API 值的 API 端点,我需要在我的实际请求中使用它,还有一次是在我进行 .fetch 调用时。

import requests
class ExampleAPI(object):
    def __init__(self):
        self.important_tokens = requests.get(url_to_tokens)['tokens']

    def fetch(self, url, params=None, key=None, token=None, **kwargs):
        return requests.get(url, params=self.important_tokens).json() 

现在,事实证明我需要创建两个模拟响应。一个用于初始化,一个用于 .fetch。使用上一个答案中的代码:

@patch('mymodule.requests.get')
def test_fetch(self, fake_get):
    expected = {"result": "True"}
    fake_get.return_value.json.return_value = expected
    e = ExampleAPI()    # This needs one set of mocked responses
    self.assertEqual(e.fetch('http://my.api.url.example.com'), expected)    # This needs a second set

如何为这两个单独的 request.get 调用创建单独的响应?

最佳答案

您可以将可迭代对象分配给模拟对象的 side_effects 属性;每次调用模拟时,它都会返回可迭代对象的下一项。

fake_responses = [Mock(), Mock()]
fake_responses[0].json.return_value = ...
fake_responses[1].json.return_value = ...
fake_get.side_effects = fake_responses

关于python - 在同一测试中模拟对同一功能的两个单独响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35737788/

相关文章:

python - 正则表达式 - 选择字符串直到 '/'

python - 用测试中的模拟替换客户端库?

python - 如何在不添加参数的情况下对基于时间的函数进行单元测试

python - 如何知道一个字符串是否属于python中字符串列表的组合?

python - 如何通过 TCP 套接字发送列表 - Python

python - 操作系统错误 : [Errno 8] Exec format error when trying to run chromedriver for selenium

python - python中的shell脚本中的 "&"相当于什么

python - 将单个 python .py 文件分解为多个具有相互依赖性的文件

python - BYTE 到 python C 类型结构转换问题

c# - Moq - 异步方法的设置。错误