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, 

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

函数的实际逻辑不执行。它将用新的模拟对象替换目标函数,该对象在调用时返回您的值

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

最新更新