pytest: assert almost equal

后端 未结 7 1505
时光说笑
时光说笑 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

    These answers have been around for a long time, but I think the easiest and also most readable way is to use unittest for it's many nice assertions without using it for the testing structure.

    Get assertions, ignore rest of unittest.TestCase

    (based on this answer)

    import unittest
    
    assertions = unittest.TestCase('__init__')
    

    Make some assertions

    x = 0.00000001
    assertions.assertAlmostEqual(x, 0)  # pass
    assertions.assertEqual(x, 0)  # fail
    # AssertionError: 1e-08 != 0
    

    Implement original questions' auto-unpacking test

    Just use * to unpack your return value without needing to introduce new names.

    i_return_tuple_of_two_floats = lambda: (1.32, 2.4)
    assertions.assertAlmostEqual(*i_return_tuple_of_two_floats())  # fail
    # AssertionError: 1.32 != 2.4 within 7 places
    

提交回复
热议问题