4

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
  • ack, ignore this -- I had the arguments for something backwards. I can't figure out how to delete the question, sorry =(
    – user358829
    Commented Jun 23, 2015 at 23:18
  • 2
    It would be much better if you wrote the answer (no matter how ridiculous) and accepted it.
    – niCk cAMel
    Commented Mar 11, 2019 at 8:28

2 Answers 2

3

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

1

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
)
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.