模拟请求/响应,模拟对象没有属性'url'

问题描述 投票:0回答:1

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

我的getUrl方法,它接收响应并返回其解析的内容:

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解析方法,该方法从initialUrl接收响应,然后在该方法中对其进行解析。我设置了...

python unit-testing mocking python-mock
1个回答
0
投票

首先,我会在您的问题中修复代码,以使其实际运行。

© www.soinside.com 2019 - 2024. All rights reserved.