How to check the layout of calls using wildcards?

I am writing unit tests and want to test a call that has a function object, for example:

call(u'mock', u'foobar', <function <lambda> at 0x1ea99b0>, 10)

How to verify that call () has all the parameters I want without playing lambda?

Edit: I wanted to clarify that I am using the mock library here: http://mock.readthedocs.org/en/latest/ . call I showed above, this is a call to the MagicMock object that I want to check with assert_has_calls .

+6
source share
3 answers

I finally found out how to do what I want. Basically, when using assert_has_calls I wanted one parameter to match no matter what it was (because I can't recreate lambda every time during the test).

The way to do this is to use mock.ANY .

So, in my example, this might correspond to a call:

 mocked_object.assert_has_calls([ call('mock', 'foobar', mock.ANY, 10) ]) 
+13
source

If you want more granularity than mock.ANY, you can create your own validator class to use in call comparisons, such as assert_has_calls, assert_called_once_with, etc.

 class MockValidator(object): def __init__(self, validator): # validator is a function that takes a single argument and returns a bool. self.validator = validator def __eq__(self, other): return bool(self.validator(other)) 

What can be used as:

 import mock my_mock = mock.Mock() my_mock('foo', 8) # Raises AssertionError. my_mock.assert_called_with('foo', MockValidator(lambda x: isinstance(x, str))) # Does not raise AssertionError. my_mock.assert_called_with('foo', MockValidator(lambda x: isinstance(x, int))) 
+4
source

not sure how you build call , but if it's some kind of args :

 # IN THE CASE WE'RE DOING call(*args) if all([len(args) == 4,isinstance(args[0],str), isinstance(args[1],str), hasattr(args[2],'__call__'), isinstance(args[3],int)]): # PASS else: # FAIL 

If you are overly concerned about getting input that is callable, which is NOT a function, and feel that it will fail the unit test:

 from types import FunctionType isinstance(lambda x: x,FunctionType) # True 
+2
source

All Articles