2014-10-04 82 views
2

我需要編寫一個測試,有StringIOcurl,所以我試圖嘲笑它們,但它返回不好的數據,與我等待的不一樣。Python模擬不起作用

的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模仿是不行的,我真的不知道該怎麼辦。

回答

2

我認爲你正在創建比你需要更多的模擬對象,而且你沒有設置很好的返回值。例如,我會用mock_io_string.getvalue.return_value = content替換mock_io_string.getvalue = mock.Mock(return_value=content)