sam sam - 1 year ago 105
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 =
if body:
return body.split(':')[0]

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.

def url_test(self, m_url):
m_response = m_url.return_value = 'Some body value:you wanted to return'
self.assertTrue(url_test(), "Failed")

Answer Source

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 = '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
    self.assertEqual(result, 'Some body value')

In your update you mock the wrong location:


Your code uses urllib2, not urllib.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download