How to patch function's return value, but still get it's side effects in python unittest

Viewed 445

I want to patch a function's return value in a unittest (it is originally expensive to evaluate), but still test its side effect (setting an attribute). The code looks sth like this:

class MyClass:
    def __init__():
        self.my_attribute = None
    
    # this function returns some string but also sets the value of self.my_attribute
    def my_function():
        self.my_attribute = 'sth'
        return 'sth_else'

class MyTestCase(unittest.TestCase):
    @mock.patch(MyClass.my_function, return_value='test_value')
    def test_my_function(self, mock_function):
        #when
        my_instance = MyClass()
        my_return = my_instance.my_function()
        #then
        self.assertEqual(my_instance.my_attribute, 'sth')

However, since the function is patched it doesn't run (right?) and so there is no side effect either. Is there a way to force the side effect to show up?

0 Answers
Related