Skip to content

Instantly share code, notes, and snippets.

@puffin
Created May 11, 2011 18:18
Show Gist options
  • Save puffin/966992 to your computer and use it in GitHub Desktop.
Save puffin/966992 to your computer and use it in GitHub Desktop.
Mock urllib2.open for UnitTest
class MockResponse(object):
def __init__(self, resp_data, code=200, msg='OK'):
self.resp_data = resp_data
self.code = code
self.msg = msg
self.headers = {'content-type': 'text/plain; charset=utf-8'}
def read(self):
return self.resp_data
def getcode(self):
return self.code
from mock import patch
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.utils import simplejson as json
from MockResponse import MockResponse
class MyTest(TestCase):
def setUp(self):
"Mock urllib2.urlopen"
self.patcher = patch('urllib2.urlopen')
self.urlopen_mock = self.patcher.start()
def test_one(self):
"""
Assuming that url-name view actually use urllib2.open to
retrieve data from another server:
json.loads(urllib2.urlopen(url, data).read())
"""
ret = {
'username': 'username',
'password': 'password',
...
}
self.urlopen_mock.return_value = MockResponse(json.dumps(ret))
data = {'username': 'your-username'}
response = self.client.post(reverse("url-name"), data)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'returned-data')
def tearDown(self):
self.patcher.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment