如何修补函数';s返回值,但仍然得到它';python unittest中的副作用

如何修补函数';s返回值,但仍然得到它';python unittest中的副作用,python,python-3.x,unit-testing,mocking,side-effects,Python,Python 3.x,Unit Testing,Mocking,Side Effects,我想在unittest中修补函数的返回值(最初的计算成本很高),但仍然测试其副作用(设置属性)。代码如下所示: 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.

我想在unittest中修补函数的返回值(最初的计算成本很高),但仍然测试其副作用(设置属性)。代码如下所示:

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

但是,由于该函数已修补,因此不会运行(对吗?),因此也没有副作用。有没有办法强迫副作用出现?

我认为这是不可能的。要么用其他东西替换函数(比如模拟),要么调用整个函数(直接调用,或者作为副作用)。您不能修补掉函数体的特定部分(比如return语句,它没有什么特殊之处,可以出现在函数中的任何地方,或者多次出现)。如果您有可能重构测试代码,您可以考虑扩展计算,然后进行修补。