Python Unittest Failure When Results Appear Equal
Solution 1:
Ok, I found the difference. Python 3 has more support for unicode, but it doesn't show the encoding that is in effect when printing a unicode string, which is why they printed the same even though they had different types:
<class '__main__.Pica'>
<class 'str'>
In order for the assertion to work, either a smarter compare is needed, or else the strings need to be put in a common format before calling the assert methods.
Solution 2:
The results appear equal, however they are not. You are not comparing a list of strings. rpn()
can return a list that holds Pica
objects:
>>> from rpn import RPN
>>> type(RPN().rpn(['2p1', '10p3', '-'])[0])
<class'rpn.Pica'>
This shows that the first element of the list returned by rpn()
is a Pica
. So, comparing a Pica
to a string is going to return False
, thus your assertion fails.
You can add a __eq__()
method to your Pica
class, then you can compare Pica
s with Pica
s:
def__eq__(self, other):
"""Test two Pica objects for equality"""return self.points == other.points
Then you could do this in your test:
self.assertEqual(self.calc.rpn(['10p3', 2, '-']), [Pica(8*12+3)])
It would be nice to also be able to create a Pica
from a string:
def__init__(self, value):
ifisinstance(value, str):
a,b = value.split('p')
value = int(a) * 12 + int(b)
self.points = value
Now you can test like this:
self.assertEqual(self.calc.rpn(['10p3', 2, '-']), [Pica('8p3')])
Post a Comment for "Python Unittest Failure When Results Appear Equal"