修补:用anoth替换方法调用

2024-04-23 07:12:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python的嘲讽框架来测试它太好了!
但是,有一件事我还没有弄清楚,那就是如何修补一个函数,以便用另一个函数替换调用。你知道吗

示例:

# module_A.py
def original_func(arg_a,arg_b):
    # ...

# module_B.py
import module_A

def func_under_test():
    # ...
    module_A.original_func(a,b)
    # Some code that depends on the behavior of the patched function
    # ...

# my test code
def alternative_func(arg_a,arg_b):
    # do something essential for the test

def the_test():
    # patch the original_func with the alternative_func here
    func_under_test()
    # assertions

通常断言就足够了,但在本例中,我需要alternative_func来启动,而不是在调用时使用original_func。你知道吗

还要注意alternative_func需要相同的参数。你知道吗

我肯定这很简单,也许现在已经很晚了,但我就是看不出来。。。你知道吗


Tags: the函数pytestimport框架示例def
3条回答

可以重新指定原始对象以指向新对象

original_func = alternative_func

那么调用original实际上就是调用alternative

您需要保存原始函数,以便在完成测试函数后可以还原:

import module_a

def the_test():
    orig_func = module_a.original_func
    module_a.original_func = alternative_func

    # do testing stuff

    # then restore original func for other tests
    module_a.original_func = orig_func

在测试import module_A的顶部,然后在设置函数中使用:

module_A.original_func = alternative_func

相关问题 更多 >