gpt4 book ai didi

python - 我们如何检查模拟请求是否确实正确?

转载 作者:行者123 更新时间:2023-12-01 07:04:04 25 4
gpt4 key购买 nike

由于我们从代码发出的请求中返回模拟对象,这意味着无论被测代码的输入如何,只要正确处理请求的响应,测试总是会通过。但是,我们不知道代码是否首先向我的网站发出了正确的请求。例如,如果 makeRequest() 由于某种原因向 www.my-site.com/foobarwww.google.com 发出请求我们会得到误报,因为测试仍然会通过,因为模拟响应仍然是我们所期望的,但它们实际上应该失败。

可能是一个愚蠢的问题,但是 unittest.mock 有办法吗?检查并确保提出的请求也是我们所期望的?

def makeRequest(session):
resp = session.get(www.my-site.com/foobar)
return resp
@patch.object(requests.Session, 'get')
def test_makeRequest(self, mock_get):
def mockResp(self):
r = requests.Response()
req.status_code = 200
return r

mock_get.return_value = mockResp()
mock_get_response = makeRequest()

最佳答案

您可以通过在模拟上使用断言来检查请求参数。

# setting up the canned response on the mock
mock_get.return_value = mockResp()

# actually calls the real code under test, i.e. calls makeRequest
mock_get_response = makeRequest()

# make an assertion about what the code *within* makeRequest did
mock_get.assert_called_once_with("www.my-site.com/foobar")

# maybe make an assertion about the `mock_get_response` here, too

请注意,正如所写,此测试将失败。您需要将 session 传递到 makeRequest 中,因为它需要一个必需参数。与在 requests.Session 上设置模拟相比,在测试期间将模拟作为 session 参数传递会更容易。

关于python - 我们如何检查模拟请求是否确实正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512827/

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