Dot*_*tan 18 python python-requests
出于测试目的,我正在尝试在python中创建一个Response()对象,但事实证明它听起来更难.
我试过这个:
from requests.models import Response
the_response = Response()
the_response.code = "expired"
the_response.error_type = "expired"
the_response.status_code = 400
Run Code Online (Sandbox Code Playgroud)
但是当我试图the_response.json()得到一个错误,因为函数试图得到len(self.content)并且a.content为空.所以我设置,a._content = "{}"但后来我得到一个编码错误,所以我必须改变a.encoding,但然后它无法解码内容....这一直在继续.有没有一种简单的方法来创建一个功能齐全且具有任意status_code和内容的Response对象?
Or *_*uan 29
因为对象上的_content属性Response(在python3上)必须是字节而不是unicodes.
这是怎么做的:
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())
Run Code Online (Sandbox Code Playgroud)
jon*_*rpe 17
创建一个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
Run Code Online (Sandbox Code Playgroud)
spec如果您尝试访问实际Response没有的方法和属性,则提供确保模拟将会抱怨.
与接受的答案中的内容相同,但您可以使用该raw属性而不是_content 私有属性(因为这是库的内部细节):
from io import BytesIO
from requests.models import Response
the_response = Response()
the_response.code = "expired"
the_response.error_type = "expired"
the_response.status_code = 400
the_response.raw = BytesIO(b'{ "key" : "a" }')
print(the_response.json())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13022 次 |
| 最近记录: |