Partially assert callable arguments with 'unittest.mock.ANY'
I just found out that you can use Python's unittest.mock.ANY to make assertions about certain arguments in a mock call, without caring about the other arguments. This can be handy if you want to test how a callable is called but only want to make assertions about some arguments. Consider the following example:
Let's say we only want to test the process function. But process ultimately depends on the fetch function, which has multiple side effects - it returns pseudo-random values and waits for 2 seconds on a fictitious network call. Since we only care about process, we'll mock the other two functions. Here's how unittest.mock.ANY can make life easier:
While this is a simple example, I found ANY to be quite useful while making assertions about callables that accept multiple complex objects as parameters. Being able to ignore some aruments while calling mock_callable.assert_called_with() can make the tests more tractable.
Under the hood, the implementation of ANY is quite simple. It's an instance of a class that defines eq and ne in a way that comparing any value with ANY will return True. Here's the full implementation:
It always returns True whenever compared with some value:
Further reading
Discussion in the ATmosphere