2

I need to write a test, there is StringIO and curl, so I tried to mock them but it returns bad data, not same as I waiting for.

Python test function:

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))

Testing function:

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

So my mock on content doesn't work, I don't really know what to do.

1 Answer 1

2

I think you're creating more mock objects than you need and you're not setting return values quite right. For instance, I'd replace mock_io_string.getvalue = mock.Mock(return_value=content) with mock_io_string.getvalue.return_value = content.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.