Asserting `mock_calls` equals expected call list
mocking, python
Solution
I haven't used this library, but the error is pretty common. It basically means you're trying to use some attribute without it being defined first. Since the `call` attribute was referenced in the mock documentation, my assumption was that it is something defined by the mock library (in addition to defining "MagicMock") that you need to import into your program in order to use. This is pretty common, a library typically can't define everything in a single attribute, you might need to import multiple attributes to get it all working.
Browsing through the mock documentation, I found that it does indeed have a `call` method. Therefore, you need to import the `call` method into your script as well. Change the first line to...
from mock import MagicMock, call
Now, you are importing not only the MagicMock attribute, but also the call attribute.
Problem
I am trying to recreate the mock_calls example so that I can check that an expected list of calls is equal to the actual calls made. However, I am receiving a `NameError` exception because `name 'call' is not defined`: ``` >>> from mock import MagicMock >>> mock = MagicMock() >>> result = mock(1, 2, 3) >>> mock.first(a=3) <MagicMock name='mock.first()' id='47645192'> >>> mock.second() <MagicMock name='mock.second()' id='47653440'> >>> int(mock) 1 >>> result(1) <MagicMock name='mock()()' id='47666064'> >>> expected = [call(1, 2, 3), call.first(a=3), call.second(), call.__int__(), call()(1)] Traceback (most recent call last): File "<pyshell#39>", line 1, in <module> expected = [call(1, 2, 3), call.first(a=3), call.second(), call.__int__(), call()(1)] NameError: name 'call' is not defined ``` I have tried defining my `expected` variable as a string instead, however this still doesn't allow a direct comparison. ``` >>> expected = """[call(1, 2, 3), call.first(a=3), call.second(), call.__int__(), call()(1)]""" >>> mock.mock_calls == expected False >>> mock.mock_calls [call(1, 2, 3), call.first(a=3), call.second(), call.__int__(), call()(1)] ``` Any ideas on how to get this example to work? If so, is that the same as the proper way to check that `mock_calls` has an expected list of calls, and in the same order? Edit: Here is the source code for the `_CallList` class, which is the type of object returned by the `mock_calls` attribute. ``` class _CallList(list): def __contains__(self, value): if not isinstance(value, list): return list.__contains__(self, value) len_value = len(value) len_self = len(self) if len_value > len_self: return False for i in range(0, len_self - len_value + 1): sub_list = self[i:i+len_value] if sub_list == value: return True return False def __repr__(self): return pprint.pformat(list(self)) ```