pytest: assert almost equal

How to do assert almost equal with py.test for floats without resorting to something like:

assert x - 0.00001 <= y <= x + 0.00001

More specifically it will be useful to know a neat solution for quickly compare pairs of float, without unpacking them:

assert (1.32, 2.4) == i_return_tuple_of_two_floats()

Solution 1:

I noticed that this question specifically asked about py.test. py.test 3.0 includes an approx() function (well, really class) that is very useful for this purpose.

import pytest

assert 2.2 == pytest.approx(2.3)
# fails, default is ± 2.3e-06
assert 2.2 == pytest.approx(2.3, 0.1)
# passes

# also works the other way, in case you were worried:
assert pytest.approx(2.3, 0.1) == 2.2
# passes

The documentation is here.

Solution 2:

You will have to specify what is "almost" for you:

assert abs(x-y) < 0.0001

to apply to tuples (or any sequence):

def almost_equal(x,y,threshold=0.0001):
  return abs(x-y) < threshold

assert all(map(almost_equal, zip((1.32, 2.4), i_return_tuple_of_two_floats())