创建一个正常运行的 Response 对象

新手上路,请多包涵

出于测试目的,我试图在 python 中创建一个 Response() 对象,但事实证明它比听起来更难。

我试过这个:

 from requests.models import Response

the_response = Response()
the_response.code = "expired"
the_response.error_type = "expired"
the_response.status_code = 400

但是当我尝试 the_response.json() 我得到一个错误,因为该函数试图获取 len(self.content)a.content 为空。所以我设置 a._content = "{}" 但后来出现编码错误,所以我必须更改 a.encoding ,但随后它无法解码内容….这一直在继续。有没有一种简单的方法可以创建一个具有功能且具有任意状态代码和内容的 Response 对象?

原文由 Dotan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 689
2 个回答

那是因为 Response 对象(在 python3 上)的 _content 属性必须是字节而不是 unicode。

这是如何做到的:

 from requests.models import Response

the_response = Response()
the_response.code = "expired"
the_response.error_type = "expired"
the_response.status_code = 400
the_response._content = b'{ "key" : "a" }'

print(the_response.json())

原文由 Or Duan 发布,翻译遵循 CC BY-SA 3.0 许可协议

创建一个 mock 对象,而不是尝试构建一个真实的对象:

 from unittest.mock import Mock

from requests.models import Response

the_response = Mock(spec=Response)

the_response.json.return_value = {}
the_response.status_code = 400

提供 spec 确保如果您尝试访问真实的方法和属性,模拟将抱怨 Response 没有。

原文由 jonrsharpe 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题