【发布时间】:2017-08-24 16:50:21
【问题描述】:
作为单元测试的一部分,我正在使用出色的 Requests 库测试一些响应。你可以用这个库做的很酷的事情是通过简单地调用来测试200 OK 状态代码的响应:
r = requests.get("http://example.com")
if r:
# success code, do something...
else:
# error code, handle the error.
这在幕后工作的方式是 Requests 根据状态码的类型更新返回的响应的__bool__() 协议方法。
我想做的是能够很好地模拟requests.get() 的响应对象,以便我不仅可以修补我有兴趣检查的方法/属性(status_code,json() ) 但也可以在我选择时返回False。
以下内容对我不起作用,因为一旦我从上面的示例代码中调用 r,它就会返回 Mock 对象 <Mock id='2998569132'>,其计算结果为 True。
with mock.patch.object(requests, 'get', return_value=mock.MagicMock(
# False, # didn't work
# __bool__=mock.Mock(return_value=False), # throws AttributeError, might be Python2.7 problem
# ok=False, # works if I call if r.ok: instead, but it's not what I want
status_code=401,
json=mock.Mock(
return_value={
u'error': {
u'code': 401,
u'message':
u'Request had invalid authentication credentials.',
u'status': u'UNAUTHENTICATED'
}
}
)
)) as mock_account_get_failure:
# mock_account_get_failure.return_value = False # overwrites what I just mocked with json() and status_code
我认为答案可能在于Magic Mocking the protocol method's return value,但请阅读here __bool__ 仅支持 Python 3.0。
【问题讨论】:
标签: python python-2.7 unit-testing mocking python-requests