gpt4 book ai didi

python-3.x - 如何为 python 的 requests.Response.text 属性设置值?

转载 作者:行者123 更新时间:2023-12-05 08:17:09 30 4
gpt4 key购买 nike

我想在我的单元测试中模拟 requests.Response() 对象,我从下面的链接得到了提示。

How to mock data as request.Response type in python

在这里,我可以只设置status_code 值(不是@Property),我想设置@Property textcontent 的值

类 UsernamePasswordAuthStrategyTest(TestCase):

def test_do_success(self):
content = self._factory.get_reader(ReaderType.CONTENT).read('MY_TEST')
auth_strategy = UsernamePasswordAuthStrategy(content)
# mock send_request method response
response = Response()
response.status_code = 200
# How could I achieve below line?
response.text = """<html>
<body>
<form method="post" name="NavForm">
<input id="csrfKey" name="csrfKey" type="hidden" value="JEK7schtDx5IVcH1eOWKN9lFH7ptcwHD/"/>
</form>
</body>
</html>"""
auth_strategy.send_request = mock.MagicMock(return_value=response)
session, auth_result = auth_strategy.do() # {'for_next_url_params': {'csrfKey': 'T4WNcz+hXqrxVa5R9o2HXkDm8pNZEi4k/'}}
self.assertTrue(session, 'Test Failed! Something went wrong')
self.assertTrue('for_next_url_params' in auth_result and 'csrfKey' in auth_result['for_next_url_params'],
'Test Failed! csrfKey not found')

send_request 返回response

最佳答案

我已经阅读了 python 文档并弄明白了...

解决方案是->

def test_do_success(self):
content = self._factory.get_reader(ReaderType.CONTENT).read('MY_TEST')
auth_strategy = UsernamePasswordAuthStrategy(content)
# mock send_request method response
response = Response()
response.status_code = 200
my_text = """<html>
<body>
<form method="post" name="NavForm">
<input id="csrfKey" name="csrfKey" type="hidden" value="JEK7schtDx5IVcH1eOWKN9lFH7ptcwHD/"/>
</form>
</body>
</html>
"""
type(response).text = mock.PropertyMock(return_value=my_text)
auth_strategy.send_request = mock.MagicMock(return_value=response)
session, auth_result = auth_strategy.do()
self.assertTrue(session, 'Test Failed! Something went wrong')
self.assertTrue('JEK7schtDx5IVcH1eOWKN9lFH7ptcwHD' in auth_result['for_next_url_params']['csrfKey'],
'Test Failed! csrfKey not found')

我在文本周围添加了 PropertyMock,代码更改为 -->

type(response).text = mock.PropertyMock(return_value=my_text)

关于python-3.x - 如何为 python 的 requests.Response.text 属性设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54446296/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com