Skip to content Skip to sidebar Skip to footer

Python Unittest Failure When Results Appear Equal

I'm running a series of unit tests on an RPN calculator I've just put together. This calculator can mix integers, floats, and picas. I often need to be able to calculate using pica

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:

  1. <class '__main__.Pica'>
  2. <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 Picas with Picas:

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"