SaltyCrane Blog — Notes on JavaScript and web development

Mock notes

Mocking different return values for multiple calls

Docs: http://www.voidspace.org.uk/python/mock/examples.html#multiple-calls-with-different-effects

import unittest

from mock import patch


def myfunc():
    pass


class MyTestCase(unittest.TestCase):

    @staticmethod
    def multiple_return_values(*return_values):
        return_values = list(return_values)

        def inner(*args, **kwargs):
            return return_values.pop(0)
        return inner

    @patch('%s.myfunc' % __name__)
    def test_something(self, myfunc_mock):
        myfunc_mock.side_effect = self.multiple_return_values(
            'return 1', 'return 2')

        r1 = myfunc()
        r2 = myfunc()
        self.assertEqual(r1, 'return 1')
        self.assertEqual(r2, 'return 2')

Comments