Question

I know if I do this:

import mock
my.factory = mock.MagicMock()

then all the things my.factory are mocked, but in fatory there is a method: create_fruit(self, type) I want if I pass-in 'apple' then return a mocked 'apple' object, if I pass-in a 'banana'then return me a 'banana' object.

Can this be implemented by mock module? I cannot find it clearly in doc: https://pypi.python.org/pypi/mock

Was it helpful?

Solution

Yes you can. But you will have to define a function for it.

from mock import Mock

def mock_create_fruit(fruit):
    if fruit not in ('apple', 'banana'):
        raise AssertionError('create_fruit not called with an allowed type, was %s' % (fruit,)
    return type(fruit, (object,), {})()

my.factory.create_fruit = Mock(side_effect=mock_create_fruit) 

The last line of our mock_create_fruit function is creating a class on the fly, creating an instance of it, and then returning it to the caller.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top