拦截函数调用 python

intercept function calls going out of a function python

我想拦截函数内部发生的函数调用。这旨在对函数内部的函数调用产生 "mocking" 某种影响。

例如:

def calls_add(a,b):
    print "this function calls add"
    c = add(a,b)
    print "call to add returned",c

我想在 call_add 之上添加一个装饰器来拦截对函数 add 的调用并调用其他函数(将相同的参数传递给 add)

像这样:

def some_other_func(*args,**kwargs):
    return "test value"

@mock(add,some_other_func)
def calls_add(a,b):
    print "this function calls add"
    c = add(a,b)
    print "call to add returned",c

有没有办法做到这一点而不必触及 calls_add 的代码。我正在查看检查库,但需要帮助。

我想你在找 unittest.mock.patch:

patch() acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the target is patched with a new object. When the function/with statement exits the patch is undone.

来自APIhere and documentation here

你必须使用 mock.patch。你有以下两种可能:

  1. 如果要使用装饰器:

    import mock
    
    
    def some_other_func(*args, **kwargs):
        return "test value"
    
    
    def add(a, b): 
        return a + b 
    
    
    @mock.patch("__main__.add", some_other_func)
    def calls_add(a, b): 
        print "this function calls add"
        c = add(a, b)
        print "call to add returned", c
    
    
    calls_add(1, 2)
    
  2. 如果您不想使用装饰器:

    import mock
    
    
    def some_other_func(*args, **kwargs):
        return "test value"
    
    
    def add(a, b): 
        return a + b 
    
    
    def calls_add(a, b): 
        print "this function calls add"
        c = add(a, b)
        print "call to add returned", c
    
    
    calls_add(1, 2)
    
    with mock.patch("__main__.add", some_other_func):
        calls_add(1, 2)