python unittest failing assertion with overloaded __repr__
-
10-02-2021 - |
Pregunta
In my code, I've defined a class with its own repr method. The representation of the class should be a list.
def __repr__(self):
if self.front <= self.tail:
q = self._queue[self.front:self.tail+1]
elif self.front > self.tail:
q = self._queue[self.front:]
q.extend(self._queue[:self.tail + 1])
return (q.__repr__())
I've written the following unittest to test this method.
def test_enqueue(self):
q = BoundedQueue(1)
q.enqueue(1)
self.assertEqual(q, [1])
However, I end up with an assertion error:
Traceback (most recent call last):
File "test_internmatch_queue.py", line 13, in test_enqueue
self.assertEqual(q, [1])
AssertionError: [1] != [1]
I'm not sure what the problem is... to my human eyes, [1]==[1]! I've tried several other variations in my repr method (below), and they all returned errors as well.
return repr(q)
return str(q)
Solución
q
is a BoundedQueue
. [1]
is a list
. They can't be equal unless you override __eq__
. repr
is not used for equality testing.
Otros consejos
As recursive states, __repr__
isn't used to detect whether two values are equal.
You have several options:
- Define
__eq__
which is what python calls to check equality. I don't recommend this as I don't really see a BoundedQueue as being equal to a list - Define an
items()
method which returns the list. Then check for equality against the list - Add a way to build a BoundedQueue from a list. Then write
__eq__
to check for equality between two BoundedQueues.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow