如何模拟.修补一个生成器/具有yield的类方法

问题描述 投票:0回答:1

如何修补生成器类方法。例如在下面的课程中,我们如何修补 get_changed_diff_patch 方法?

class PassiveJsonMixin(JsonMixin):
    """
    passive items that do not have id/key
    """

    def __init__(self, *args, **kwargs):
        JsonMixin.__init__(self, *args, **kwargs)
        # self.build_json()
        pass
    def get_changed_diff_patch(self, parent_hidden=False):
        print ("From PassiveJsonMixin: get_changed_diff_patch")
        return
        yield

通常的方法

patch.object(mymod.PassiveJsonMixin, 'get_changed_diff_patch',wrapper(mymod.PassiveJsonMixin.get_changed_diff_patch) )
                                                                                                                                                                    

                                                                                                                                                                                                                                                                                                                                          

似乎不起作用。

python generator patch yield python-unittest.mock
1个回答
0
投票

通过使用 with 上下文对答案进行一些扩展:

from unittest import mock

class MyClass:
    def some_generator(self):
        for i in range(5):
            yield i

    def method_using_generator(self):
        values = []
        for value in self.some_generator():
            values.append(value)
        return values


with mock.patch.object(MyClass, 'some_generator', return_value=[10, 20, 30, 40, 50]):
    my_instance = MyClass()
    result = my_instance.method_using_generator()
    print (result)
    
    
© www.soinside.com 2019 - 2024. All rights reserved.