pytest: assert almost equal

后端 未结 7 1506
时光说笑
时光说笑 2020-12-24 03:55

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

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


        
7条回答
  •  清酒与你
    2020-12-24 04:42

    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())
    

提交回复
热议问题