Python 模拟依赖项

Python Mock dependencies

您好,我正在寻找一种模拟函数调用的函数的方法。 目前我只找到类似这样的例子:

def f1():
    a = 'do not make this when f1() is mocked'
    return 10, True

def f2():
    num, stat = f1()
    return 2*num, stat

import mock

print f2() # Unchanged f1 -> prints (20, True)

with mock.patch('__main__.f1') as MockClass: # replace f1 with MockClass 
    MockClass.return_value = (30, True) # change the return value
    print f2() # prints now 60, 

问题在于方法的 return 值被覆盖,但函数的实际逻辑仍在执行。 函数中发生的事情应该被忽略。 换句话说,我想为测试重载函数。 这是个好主意,还是有其他方法可以解决这个问题?

没有执行函数的实际逻辑。它将用新的模拟对象替换目标函数,returns 你在调用时的值

def f1():
    a = 'do not make this when f1() is mocked'
    print("should be printed once")
    return 10, True
 
def f2():
    num, stat = f1()
    return 2*num, stat
 
import mock
 
print f2() # Unchanged f1 -> prints (20, True)
 
with mock.patch('__main__.f1') as MockClass: # replace f1 with MockClass 
    MockClass.return_value = (30, True) # change the return value
    print f2() # prints now 60,

输出:

should be printed once
(20, True)
(60, True)

sohuld be printed once只打印一次,因此打补丁时不会执行第二次内部逻辑。

在此处查看执行情况https://ideone.com/jRpObT