gpt4 book ai didi

Python 模拟不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:35 26 4
gpt4 key购买 nike

我需要写一个测试,有 StringIOcurl,所以我试着模拟它们,但它返回了错误的数据,与我等待的不一样。

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 的模拟不起作用,我真的不知道该怎么做。

最佳答案

我认为您创建的模拟对象比您需要的多,而且您没有正确设置返回值。例如,我会将 mock_io_string.getvalue = mock.Mock(return_value=content) 替换为 mock_io_string.getvalue.return_value = content

关于Python 模拟不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26195184/

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