Python中使用mock的部分补丁

Python中使用mock的部分补丁,python,python-3.x,unit-testing,mocking,python-unittest,Python,Python 3.x,Unit Testing,Mocking,Python Unittest,如何在函数上使用mock.patch,这样我就可以访问方法.assert\u调用的等,同时我还可以保留函数的原始功能 下面是示例代码: from unittest import mock def foo(arg): print(arg) def tested(): foo('hi') @mock.patch('__main__.foo') def test(foo): tested() foo.assert_called_once() test() 我想

如何在函数上使用
mock.patch
,这样我就可以访问方法
.assert\u调用的
等,同时我还可以保留函数的原始功能

下面是示例代码:

from unittest import mock

def foo(arg):
    print(arg)

def tested():
    foo('hi')

@mock.patch('__main__.foo')
def test(foo):
    tested()
    foo.assert_called_once()

test()

我想让它测试
foo
函数是否只调用了一次,但我仍然需要它来打印
hi

哦。我已经解决了。我只需要将参数
的副作用
添加到decorator:-)

像这样:

@mock.patch('__main__.foo', side_effect=foo)
def test(foo):
    ...

哦。我已经解决了。我只需要将参数
的副作用
添加到decorator:-)

像这样:

@mock.patch('__main__.foo', side_effect=foo)
def test(foo):
    ...