使用 lambda 断言调用

Asserting call with lambda

我有这段代码:

from shutil import rmtree

def ook(path):
    rmtree(path, onerror=lambda x, y, z: self._logger.warn(z[1]))

在我的单元测试中,我想模拟它所以检查正确的 path 是否通过:

from mock import patch, ANY

@patch("rmtree")
def test_rmtree(self, m_rmtree):
    ook('/tmp/fubar')
    m_rmtree.assert_called_once_with('/tmp/fubar', onerror=ANY)

我可以用什么替换 ANY 来检查那里是否有 lambda?

我会用 call_args and call_count rather than directly in assert_called_once_with, I don't think unittest.mock has anything like e.g. jasmine.any:

from collections import Callable

...

@patch("rmtree")
def test_rmtree(self, m_rmtree):
    ook('/tmp/fubar')
    assert m_rmtree.call_count == 1
    args, kwargs = m_rmtree.call_args
    assert args[0] == '/tmp/fubar'
    assert isinstance(kwargs.get('onerror'), Callable)

请注意,参数具体是 lambda 并不重要,只是它是可调用的。