Equality test failing for eval(repr(object)) in python3

1.2k views Asked by At

Here's the __repr__ method inside a class called Grid

def __repr__(self):
    return 'Grid(%r, %r)' % (self.rows, self.cols)

and I've put some basic tests inside a unittest module to check if eval can do an equality test without failure, and that looks like this:

# One of the tests inside a unittest.TestCase subclass
def test_grid(self):
    grid = Grid(3, 4)
    self.assertEqual(eval(repr(grid)), grid)

Now, this is the test report (I've isolated this test from others):

======================================================================
FAIL: test_grid (tests.test_core.TestCore)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/user/Desktop/sample/tests/test_core.py", line 14, in test_grid
    self.assertEqual(eval(repr(grid)), grid)
AssertionError: Grid(3, 4) != Grid(3, 4)

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

The Assertion exception message is even more confusing to me. Isn't Grid(3, 4) != Grid(3, 4) supposed to be False?

1

There are 1 answers

4
Rusty On BEST ANSWER

I think the core of the issue is that you are creating a new object, and even though the values are the same inside - python cannot tell that they are, so it compares object by references. And they are different. I believe you need to override python's magic comparison operator to be able to compare by internal values.