Python 2.7 中的模拟功能?

Mocking function in Python 2.7?

此代码运行,没有错误,但没有像我希望的那样模拟函数。为什么不?另外,很明显,这些函数不是 "side effects",它们是纯函数,但是据我所知,这是用于使用标准 Python 模拟库模拟函数的语法。

# mocking test
from mock import mock


def local_f(a, b):
    print "default local_f(%d,%d)" % (a, b)
    return a + b


def local_f2(a, b):
    print "local_f2(%d,%d)" % (a, b)
    return a * b


def go():
    print "(before) testing simple_f: %s" % local_f(3, 4)

    with mock.patch('mock_test.local_f',
                    side_effect=local_f2) as mock_function_obj:
        print "type(mock_function_obj) = %s" % type(mock_function_obj)
        print "(with) testing simple_f: %s" % local_f(3, 4)

    print "(after) testing simple_f: %s" % local_f(3, 4)

if __name__ == "__main__":
    go()

必须针对您正在模拟的模块进行模拟。在您的特定情况下,您是在嘲笑 __main__。我假设 mock_test 是包含您发布的代码的文件的名称?因此,您的补丁应如下所示:

with mock.patch('__main__.local_f')

我对您的代码进行更改后的示例输出:

default local_f(3,4)
(before) testing simple_f: 7
type(mock_function_obj) = <class 'mock.MagicMock'>
local_f2(3,4)
(with) testing simple_f: 12
default local_f(3,4)
(after) testing simple_f: 7