【问题标题】:Patching: Replacing a method call with another修补:用另一个方法调用替换
【发布时间】:2011-10-24 17:23:07
【问题描述】:

我使用 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 需要相同的参数。

我敢肯定这非常容易,而且可能时间已经很晚了,但我就是没看到...

【问题讨论】:

    标签: python unit-testing patch


    【解决方案1】:

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

    module_A.original_func = alternative_func
    

    【讨论】:

      【解决方案2】:

      您需要保存原始功能,以便在完成测试功能后恢复:

      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
      

      【讨论】:

        【解决方案3】:

        你可以重新分配原来的指向新的

        original_func = alternative_func
        

        然后调用 original 将实际上调用替代

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多