如何在第一次调用 python 的 MagicMock 时将其设置为 return 值,并在第二次调用时引发异常?
How to get python's MagicMock to return a value the first time it is called and raise an exception the second time it is called?
我有以下 python 使用模拟的程序。
#!/usr/bin/env python
import mock
def my_func1():
return "Hello"
my_func = mock.MagicMock()
my_func.return_value = "Goodbye"
print my_func()
print my_func()
输出:
Goodbye
Goodbye
一切正常。太好了。
但我希望模拟方法在第一次调用时 return Goodbye
并在第二次调用时引发异常。我该怎么做?
您可以使用side_effect
代替return_value
,例如:
import mock
a = 0
def my_func1():
global a
a += 1
if a < 2:
return "Goodbye"
else:
raise Exception()
my_func = mock.MagicMock()
my_func.side_effect = my_func1
print my_func()
# output Goodbye
print my_func()
# An exception was raised.
正如 Sraw 指出的那样,您可以使用 side_effect
。我可能会使用生成器函数而不是引入全局函数:
import mock
def effect(*args, **kwargs):
yield "Goodbye"
while True:
yield Exception
my_func = mock.MagicMock()
my_func.side_effect = effect()
my_func() #Returns "Goodbye!'
my_func() #Raises exception
my_func() #Raises exception
显然你可能不想提出一个裸 Exception
,但我不确定你想提出什么异常...
我有以下 python 使用模拟的程序。
#!/usr/bin/env python
import mock
def my_func1():
return "Hello"
my_func = mock.MagicMock()
my_func.return_value = "Goodbye"
print my_func()
print my_func()
输出:
Goodbye
Goodbye
一切正常。太好了。
但我希望模拟方法在第一次调用时 return Goodbye
并在第二次调用时引发异常。我该怎么做?
您可以使用side_effect
代替return_value
,例如:
import mock
a = 0
def my_func1():
global a
a += 1
if a < 2:
return "Goodbye"
else:
raise Exception()
my_func = mock.MagicMock()
my_func.side_effect = my_func1
print my_func()
# output Goodbye
print my_func()
# An exception was raised.
正如 Sraw 指出的那样,您可以使用 side_effect
。我可能会使用生成器函数而不是引入全局函数:
import mock
def effect(*args, **kwargs):
yield "Goodbye"
while True:
yield Exception
my_func = mock.MagicMock()
my_func.side_effect = effect()
my_func() #Returns "Goodbye!'
my_func() #Raises exception
my_func() #Raises exception
显然你可能不想提出一个裸 Exception
,但我不确定你想提出什么异常...