模拟requests/responses,模拟对象没有属性'url'

Mocking requests/responses, mock object has no attribute 'url'

我是模拟库的新手,到目前为止它一直给我带来麻烦。我正在尝试测试一个 Url 解析方法,该方法从 initialUrl 获取响应,然后在该方法中解析该响应。我设置了 autospec=true 所以我认为它应该可以访问请求库中的所有方法(包括 response.url) 我正在尝试模拟 getresponse 虽然我'我不确定是否需要这样做?

我的 getUrl 方法接受响应和 returns 其解析的内容:

def getUrl(response):
    if response.history:
        destination = urllib.parse.urlsplit(response.url)

        baseUrlTuple = destination._replace(path="", query="")
        return urllib.parse.urldefrag(urllib.parse.urlunsplit(baseUrlTuple)).url

    raise RuntimeError("No redirect")

测试方法:

def testGetUrl(self):
    initialUrl = 'http://www.initial-url.com'
    expectedUrl = 'http://www.some-new-url.com'

    mock_response = Mock(spec=requests, autospec=True)
    mock_response.status_code = 200
    mock_get = Mock(return_value=mock_response)
    #mock_get.return_value.history = True
    resp = mock_get(self.initialUrl)
    mock_response.history = True
    resultUrl = getBaseUrl(resp)
    self.assertEqual(resultUrl, expectedUrl)

当我 运行 测试时,我得到

    raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute 'url'

首先,我将修复您问题中的代码,使其真正运行。

您有多种选择,最简单的方法是将 url 添加到您正在模拟的属性列表中:

mock_response.url = <your URL>

但是了解您正在尝试使用请求库作为模拟的规范也很重要,如果您希望 url 属性是,您应该使用 requests.Response()自动生成。不过,您仍然必须将要使用的任何 url 分配给它,否则您将在函数中将 Mock 对象与 int 进行比较。

如果您想了解更多信息,请查看涉及规范的文档: https://docs.python.org/3/library/unittest.mock-examples.html