【发布时间】:2019-01-30 17:31:12
【问题描述】:
我想在我的单元测试中模拟 requests.Response() 对象,我从下面的链接中得到了提示。
How to mock data as request.Response type in python
在这里,我可以只设置status_code 的值(不是@Property),我想设置@Property 的值text 或content
类用户名密码AuthStrategyTest(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
【问题讨论】:
-
我们需要你的一些代码来解决问题。
-
@eagle33322 提供的链接有足够的信息,所以之前没有添加代码。您也可以在提供的链接中举一个例子
-
@eagle33322 不是真的,该示例只是说明如何为
status_code设置值而不是@Property 以及我在描述中使用的相同链接
标签: python-3.x python-requests