如何在单元测试中检查值是否为nan?

时间:2013-06-03 06:13:43

标签: python unit-testing assert nan

我有函数,有时会返回带有float('nan')的NaN(我没有使用numpy)。

我如何为它编写测试,因为

assertEqual(nan_value, float('nan'))

就像float('nan') == float('nan')总是假的。可能有assertIsNan之类的东西吗?我找不到任何关于它的东西......

2 个答案:

答案 0 :(得分:16)

我想出了

assertTrue(math.isnan(nan_value))

答案 1 :(得分:9)

如果math.isnan(x)既不是TypeError也不是x

float会提出Real

最好使用这样的东西:

import math


class NumericAssertions:
    """
    This class is following the UnitTest naming conventions.
    It is meant to be used along with unittest.TestCase like so :
    class MyTest(unittest.TestCase, NumericAssertions):
        ...
    It needs python >= 2.6
    """

    def assertIsNaN(self, value, msg=None):
        """
        Fail if provided value is not NaN
        """
        standardMsg = "%s is not NaN" % str(value)
        try:
            if not math.isnan(value):
                self.fail(self._formatMessage(msg, standardMsg))
        except:
            self.fail(self._formatMessage(msg, standardMsg))

    def assertIsNotNaN(self, value, msg=None):
        """
        Fail if provided value is NaN
        """
        standardMsg = "Provided value is NaN"
        try:
            if math.isnan(value):
                self.fail(self._formatMessage(msg, standardMsg))
        except:
            pass

然后,您可以使用self.assertIsNaN()self.assertIsNotNaN()