minimocktest.MockTestCase provides a full featured unittest.TestCase subclass that allows for mocking. Using this class as the basis of your unittests allows you to mock functions by calling
self.mock('urllib2.urlopen', returns=StringIO.StringIO('{"error": 1}'))
someobj = self.Mock('someobj')
import unittest
from minimocktest import MockTestCase
import StringIO
import urllib2
def urldump(url):
''' simple function to be tested '''
f = urllib2.urlopen(url)
try:
return f.read()
finally:
f.close()
class MySimpleTestCase(MockTestCase):
def setUp(self):
super(self.__class__, self).setUp()
self.file = StringIO.StringIO('MiniMockTest')
self.file.close = self.Mock('file_close_function')
def test_urldump_dumpsContentProperly(self):
self.mock('urllib2.urlopen', returns=self.file)
self.assertEquals(urldump('http://pykler.github.com'), 'MiniMockTest')
self.assertSameTrace('\n'.join([
"Called urllib2.urlopen('http://pykler.github.com')",
"Called file_close_function()",
]))
urllib2.urlopen('anything')
self.mock('urllib2.urlopen', returns=self.file, tracker=None)
urllib2.urlopen('this is not tracked')
self.assertTrace("Called urllib2.urlopen('anything')")
self.assertTrace("Called urllib2.urlopen('this is not tracked')", includes=False)
self.assertSameTrace('\n'.join([
"Called urllib2.urlopen('http://pykler.github.com')",
"Called file_close_function()",
"Called urllib2.urlopen('anything')",
]))
suite = unittest.TestLoader().loadTestsFromTestCase(MySimpleTestCase)
unittest.TextTestRunner().run(suite)
from minimocktest import MockTestCase
from django.test import TestCase
from django.test.client import Client
class DjangoTestCase(TestCase, MockTestCase):
'''
A TestCase class that combines minimocktest and django.test.TestCase
'''
def _pre_setup(self):
TestCase._pre_setup(self)
MockTestCase.setUp(self)
# optional: shortcut client handle for quick testing
self.client = Client()
def _post_teardown(self):
MockTestCase.tearDown(self)
TestCase._post_teardown(self)
def setUp(self):
pass
def tearDown(self):
pass
You can download this project in either zip or tar formats.
You can also clone the project with Git by running:
$ git clone git://github.com/pykler/MiniMockTest