Python mock() not mocking the return value

6.1k views Asked by At

I'm having some trouble with Python mock() and I'm not familiar enough to figure out what's going on with it.

I have an abstract async task class that looks something like:

class AsyncTask(object):
    @classmethod
    def enqueue(cls):
        ....
        task_ent = cls.createAsyncTask(body, delayed=will_delay)
        ....

I'd like to patch the createAsyncTask method for a specific instance of this class.

The code I wrote looks like:

@patch.object(CustomAsyncTaskClass, "createAsyncTask")
def test_my_test(self, mock_create_task):
    ....
    mock_create_task.return_value = "12"
    fn()    # calls CustomAsyncTaskClass.enqueue(...)
    ....

When I print out task_ent in enqueue, I get <MagicMock name='createAsyncTask()' id='140578431952144'>

When I print out cls.createAsyncTask in enqueue, I get <MagicMock name='createAsyncTask' id='140578609336400'>

What am I doing wrong? Why won't createAsyncTask return 12?

2

There are 2 answers

0
piggs_boson On

Try the following:

@patch("package_name.module_name.createAsyncTask")
def test_my_test(self, mock_create_task):
    ....
    mock_create_task.return_value = "12"
    fn()    # calls CustomAsyncTaskClass.enqueue(...)
    ....

where module_name is the name of the module which contains the class AsyncTask.

In general, this is the guideline https://docs.python.org/3/library/unittest.mock.html#where-to-patch

0
Zmall On

I know that this question is old but I just had the same problem and fixed it now.

If you patch multiple functions it is very important to keep the order in mind. It has to be reversed from the patches.

@patch("package_name.function1")
@patch("package_name.function2")
def test_method(
mocked_function2: MagicMock,
mocked_function1: MagicMock
)