Search code examples
pythonmockingpython-mock

Asserting call with lambda


I have this piece of code:

from shutil import rmtree

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

In my unit tests, I want to mock it so check that right path is passed:

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)

What can I replace ANY with to check that there is a lambda there?


Solution

  • I would do this with the 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)
    

    Note that it's not relevant that the argument is a lambda specifically, just that it is callable.