'Mock patch specific instance of class

How to mock a specific instance of a class using patch?

In my test file I have:

@classmethod
def setUpClass(cls):
    cls.instance_of_my_class = myClass()

one of the tests then calls a function in myClass that I wish to mock the return value of.

I can do so like this.

self.instance_of_my_class.cool_fuction = Mock(return_value=(True, True))

I wish to do this using with patch so that the mock does not persist into the other tests, or to, in some way unset the mock.

However, patch requires a string like "package.module.Class.attribute" as it's target so putting

with patch("self.instance_of_my_class") as mock:
      mock.return_value.cool_fuction.return_value = (True, True)

fails with traceback

AssertionError: No module named 'self'

If I patch the class like

with patch("functions_folder.my_script.myClass") as mock:
      mock.return_value.cool_fuction.return_value = (True, True)

the wrong instance is patched and mock.called returns False

The test looks like:

def test_foo_function(self):
    result = self.instance_of_my_class.foo_function()
    self.assertTrue(result[0]["confirmed"])

and foo_function calls on cool_function which I want to mock return (True, True)



Solution 1:[1]

Thanks to @johnsharpe for pointing out the answer.

with the same setUpClass at the start of Test_myClass as I had:

@classmethod
def setUpClass(cls):
    cls.instance_of_my_class = myClass()

working test case now looks like:

@patch.object(myClass, "cool_function")
def test_foo_function(self, mock):
    mock.return_value = (True, True)
    
    result = self.instance_of_my_class.foo_function()

    self.assertTrue(result[0]["confirmed"])
    self.assertTrue(mock.called)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 beautysleep