When using python mox mock objects is there any way to avoid all of them being equal (as in __eq__)?

248 views Asked by At

I'm experiencing some problems derived from the fact than several all mox Mock object of a given class seem to be equal in the ==,__eq__ sense although they are different objects (at least mock1 is mock2 returns False). is there any way to prevent that behaviour?

In the code example below you can see that the count is wrong because it thinks all the mocks are equal:

import mox

class MyClass(object):
    pass

real1 = MyClass()
real2 = MyClass()
listreal = (real1, real2)
mocker = mox.Mox()
mock1 = mocker.CreateMock(MyClass)
mock2 = mocker.CreateMock(MyClass)
listmock = (mock1, mock2)

real1 == real2  # False
real1 is real2  # False
listreal.count(real1)  # 1
mock1 == mock2  # True
mock1 is mock2  # False
listmock.count(mock1)  # 2
1

There are 1 answers

0
RubenLaguna On

It seems that the implementation of __eq__ for mox.MockAnything and mox.MockObject just compares the replay_mode and the expected_calls_queue so any mock object that is expecting the same calls is actually "equal".

class MockAnything:
  def __eq__(self, rhs):
    """Provide custom logic to compare objects."""

    return (isinstance(rhs, MockAnything) and
            self._replay_mode == rhs._replay_mode and
            self._expected_calls_queue == rhs._expected_calls_queue)

That has several implications when the mocks are used in collections for methods like list.remove(), etc.

You have to add some calls to a fake method to make the mocks not equal in the eyes of __eq__.