2011-10-24 38 views
2

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

我敢肯定它的超級容易,MAYB它是晚了,但我沒有看到它......

回答

0

您可以重新分配原來指向新

original_func = alternative_func 

然後調用原來實際上將在頂部測試import module_A調用替代

4

,然後在設置功能用途:

module_A.original_func = alternative_func 
1

您需要保存原始功能,以便在完成測試功能後即可恢復:

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