[TIP] Mock calls with collections

Federico Simoncelli federico.simoncelli at gmail.com
Sat Jan 24 16:38:34 PST 2015


Hi, I am trying to test a method that receives a collection that later
on is modified. I think it can be simplified as:

x = MagicMock()
y = [1, 2, 3]
x.my_call(y)
y.remove(3)
x.my_call(y)

print(x.my_call.mock_calls)

(PS: I am not able to insert the "mock_calls" checks between the
multiple my_call calls).

Anyway the expected output is:

 [call([1, 2, 3]), call([1, 2])]

because at the moment of the first call the collection contained 1, 2, 3.

Instead the output is:

 [call([1, 2]), call([1, 2])]

because the mock recorded the collection object (y) and not its
snapshot in time at the moment of the call.

I understand that maintaining the snapshot at call time means creating
a new collection, which could be problematic for other types of
checks, eg:

 assert x.my_call.mock_calls[0][1][0] is y

Anyway I am looking forward to assert calls to the same function with
the same collection with (possibly) different items at different time.

Any suggestion on how to do it? (Or maybe this could be a feature/bug on mock)

Thanks,
-- 
Federico



More information about the testing-in-python mailing list