Skip to content

Instantly share code, notes, and snippets.

@melbic
Forked from puffin/MockResponse.py
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save melbic/0c53b8da5ee0d812e815 to your computer and use it in GitHub Desktop.

Select an option

Save melbic/0c53b8da5ee0d812e815 to your computer and use it in GitHub Desktop.

Revisions

  1. @puffin puffin revised this gist May 11, 2011. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions tests.py
    Original file line number Diff line number Diff line change
    @@ -2,6 +2,7 @@

    from django.core.urlresolvers import reverse
    from django.test import TestCase
    from django.utils import simplejson as json

    from MockResponse import MockResponse

  2. @puffin puffin created this gist May 11, 2011.
    13 changes: 13 additions & 0 deletions MockResponse.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    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
    35 changes: 35 additions & 0 deletions tests.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    from mock import patch

    from django.core.urlresolvers import reverse
    from django.test import TestCase

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