Fork me on GitHub

MiniMockTest by pykler

Python unittest TestCase that wraps minimock for easier use

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}'))
or creating mock objects
someobj = self.Mock('someobj')
Also you do not have to worry about resetting the mock, all that is taken care of by the MockTestCase tearDown function.

Examples

Simple Testing

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)

Django Integration

To integrate with Django, simply create the following class, and use it as your base instead of using the django.test.TestCase directly.
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

Download

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