How to represent unittest.mock.call().__str__()

Viewed 1818

One of the mocks that I'm using contains the call call().__str__().

Output of my_mock.mock_calls

[call(<MagicMock name='mock()' id='140630678530704'>, indent=2, sort_keys=True),
 call().__str__(),            # <-- what I'm trying to represent
 call()]

How can I represent this?

Checking that call().__str__() is part of the mock_calls is causing me difficulty as that will get converted to the string 'call()'.

In [16]: mock.call().__str__()
Out[16]: 'call()'
2 Answers

If I understand you correctly, you want to check if the given call is in mock_calls. The standard way to check if a method has been called, is to use one of the assert_called_xxx methods on the created instance:

@mock.patch('mymodule.SomeClass')
def test1(mocked):
    inst = SomeClass()  # inst == mocked.return_value
    inst.__str__.assert_not_called()

    # use this if you don't have inst
    mocked.return_value.__str__assert_not_called()

    print(inst)
    inst.__str__.assert_called_once()
    mocked.return_value.assert_called_once()
    mocked.return_value.__str__.assert_called_once()

Note that instead of checking call().__str__ on mocked, you check __str__ on mocked.return_value, which is the result of call().

If for some reason you need to directly check for the string representation of that call, e.g. call.__str__(), you have to check the string instead:

assert 'call.__str__()' in [str(c) for c in inst.mock_calls]

Or, if you want to check it on the class:

assert 'call().__str__()' in [str(c) for c in mocked.mock_calls]

EDIT: Removed not working version, as pointed out by @user2357112supportsMonica, fixed incorrect usage of mocked.

You also could use this way.

inst.assert_has_calls([
    ("().__str__()", (), {})
])

It works because call is unittest.mock._Call class alias. But _Call is also tuple child.
So when you write ("().__str__()", (), {}) the items are:

  1. name
  2. args
  3. kwargs So it equals call().__str__()
Related