如何让python的MagicMock在第一次被调用时返回一个值并在第二次被调用时引发异常?

Saq*_*Ali 4 python mocking magicmock

我有以下使用模拟的 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()
Run Code Online (Sandbox Code Playgroud)

输出:

Goodbye
Goodbye
Run Code Online (Sandbox Code Playgroud)

一切正常。伟大的。

但我希望模拟出的方法Goodbye在第一次被调用时返回,并在第二次被调用时引发异常。我怎样才能做到这一点??

And*_*Guy 5

正如 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
Run Code Online (Sandbox Code Playgroud)

显然你可能不想提出一个空的Exception,但我不确定你想提出什么例外......