pythonpython-unittestpython-unittest.mock

Test that unittest.Mock was called with some specified and some unspecified arguments


We can check if a unittest.mock.Mock has any call with some specified arguments. I now want to test that some of the arguments are correct, while I do not know about the other ones. Is there some intended way to do so?

I could manually iterate over Mock.mock_calls, but is there a more compact way?

import random
from unittest import mock

def mymethod(a, handler):
    handler(a, random.random())

def test_mymethod():
    handler = mock.Mock()
    mymethod(5, handler)

    handler.assert_any_call(5, [anything]) # How do I achieve this?

Solution

  • You can assert the wildcard argument to be unittest.mock.ANY, which has its __eq__ method overridden to unconditionally return True so that the object is evaluated equal to anything:

    from unittest.mock import ANY
    
    def test_mymethod():
        handler = mock.Mock()
        mymethod(5, handler)
        handler.assert_any_call(5, ANY) # passes
    

    Demo: https://ideone.com/8Kbywo