unittest: Proposal to add failUnlessNear

Antoon Pardon apardon at forel.vub.ac.be
Mon Jul 19 07:06:47 EDT 2004


I have been working with unittests lately and found that the
self.failUnlessAlmostEqual, isn't as usefull as it could be.

My main problem is, that it is only usefull with objects
that can be converted to floats, while there are a whole
bunch of objects that can be almost equal but not so
convertable. The first example coming to mind being
complex numbers.

A secondary objection is that you are limited to
a very specific set of tolerances. If for instance
you want to verify that two numbers differ at most
by 0.0003 you can't specify that.

So I propose to add the following


  def failUnlessNear(self, first, second, tolerance=1e-7, msg=None, norm=abs):
      """Fail if the two objects are too far appart as determined
         by the distance between them and the tolerance allowed.
      """
      if norm(second-first) > tolerance:
          raise self.failureException, \
                (msg or '%s != %s within %s tolerance' % (`first`, `second`, `tolerance`))


-- 
Antoon Pardon



More information about the Python-list mailing list