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

标签 python mocking python-requests

由于我们从代码发出的请求中返回模拟对象,这意味着无论被测代码的输入如何,只要正确处理请求的响应,测试总是会通过。但是,我们不知道代码是否首先向我的网站发出了正确的请求。例如,如果 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/

相关文章:

python - 如何在元素应用程序中扩展 Django 元素根 HTML 文件?

c# - 有没有更简洁的方法来在 C# 单元测试中 stub 值?

python - 组合两列给出 ValueError : Wrong number of items passed 2, placement implies 1

java - Mockito 何时不模拟而不是调用实际方法

java - 如何使用mockito在Junit中获取org.apache.felix.scr.annotations.Reference?

python - Python 中请求模块与 selenium 的比较

python - 关于请求 url 响应 404,但在浏览器中成功并抓取标签的问题

python - 在 python 中使用来自 JSON 响应的数据

python - python进程返回代码-9是什么意思?

javascript - Python CGI 脚本拒绝包含数据 URI 的数据 (403)