我需要编写一个测试,有StringIO
和curl
,所以我试图模仿它们,但它会返回错误的数据,与我等待的不一样。
Python测试功能:
def test_make_curl_request(self):
redirect_url = 'abc'
content = 'Content'
mock_curl = mock.MagicMock()
mock_curl.getinfo = mock.Mock(return_value=redirect_url)
mock_curl.setopt = mock.Mock()
mock_curl.perform = mock.Mock()
mock_io_string = mock.MagicMock()
mock_io_string.getvalue = mock.Mock(return_value=content)
with mock.patch('pycurl.Curl', mock.Mock(return_value=mock_curl)):
with mock.patch('source.lib.StringIO', mock.Mock(return_value=mock_io_string)):
with mock.patch('source.lib.to_str', mock.Mock(return_value=redirect_url)):
with mock.patch('source.lib.to_unicode', mock.Mock(return_value=redirect_url)):
with mock.patch('source.lib.prepare_url', mock.Mock()):
self.assertEqual(init.make_pycurl_request('http://test.rg', 10), (content, redirect_url))
测试功能:
def make_pycurl_request(url, timeout, useragent=None):
prepared_url = to_str(prepare_url(url), 'ignore')
buff = StringIO()
curl = pycurl.Curl()
curl.setopt(curl.URL, prepared_url)
if useragent:
curl.setopt(curl.USERAGENT, useragent)
curl.setopt(curl.WRITEDATA, buff)
curl.setopt(curl.FOLLOWLOCATION, False)
# curl.setopt(curl.CONNECTTIMEOUT, timeout)
curl.setopt(curl.TIMEOUT, timeout)
curl.perform()
content = buff.getvalue()
redirect_url = curl.getinfo(curl.REDIRECT_URL)
curl.close()
if redirect_url is not None:
redirect_url = to_unicode(redirect_url, 'ignore')
return content, redirect_url
所以我对content
的模拟不起作用,我真的不知道该怎么做。
答案 0 :(得分:2)
我认为您创建的模拟对象超出了您的需求,并且您没有正确设置返回值。例如,我将mock_io_string.getvalue = mock.Mock(return_value=content)
替换为mock_io_string.getvalue.return_value = content
。