How to perform unittest for floating point outputs? - python

前端 未结 2 1492
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 18:33

Let\'s say I am writing a unit test for a function that returns a floating point number, I can do it as such in full precision as per my machine:

>>>         


        
2条回答
  •  迷失自我
    2021-01-07 18:59

    The unittest.TestCase class has specific methods for comparing floats: assertAlmostEqual and assertNotAlmostEqual. To quote the documentation:

    assertAlmostEqual(first, second, places=7, msg=None, delta=None) assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)

    Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. Note that these methods round the values to the given number of decimal places (i.e. like the round() function) and not significant digits.

    If delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta.

    Thus, you could test the function like this:

    self.assertAlmostEqual(div(1, 9), 0.1111111111111111)  # round(a-b, 7) == 0
    self.assertAlmostEqual(div(1, 9), 0.1111, 4)           # round(a-b, 4) == 0
    

    On a side note, unless you use pytest as a tests runner, you should prefer the TestCase.assert* methods to bare assert statements, as the test failure messages produced by the methods are generally much more informative.

提交回复
热议问题