sam sam - 1 month ago 18
Python Question

mocking of url for unittesting

I want to mock urllib.urlopen for creating unit test

def url_test(self):
response = urllib2.urlopen(test_url)
body = response.read()
if body:
return body.split(':')[0]


config.py

test_url = "localhost"


I want to mock the url_test() function but I do not understand how to mock the value of test_url. Because when I am trying to unit test the function it says me "connection refused"

this is what i tried.

@patch('urllib.urlopen')
def url_test(self, m_url):
m_response = m_url.return_value
m_response.read.return_value = 'Some body value:you wanted to return'
self.assertTrue(url_test(), "Failed")
m_url.assert_called_with('localhost')

Answer

You would mock any external system, which here is urllib2. Assuming you are using the unittest.mock library (backported to Python 2 as the mock project):

with mock.patch('urllib2.urlopen') as urlopen_mock:
    mock_response = urlopen_mock.return_value
    mock_response.read.return_value = 'Some body value:you wanted to return'

    # call the method being tested
    result = someobject.url_test()

    # make assertion about the return value and that the code tried to use 
    # a specific URL
    urlopen_mock.assert_called_with('localhost')
    self.assertEqual(result, 'Some body value')

In your update you mock the wrong location:

@patch('urllib.urlopen')

Your code uses urllib2, not urllib.