29

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

我如何为它写一个测试,因为

assertEqual(nan_value, float('nan'))

就像float('nan') == float('nan')总是假的一样。可能有类似的东西assertIsNan吗?我找不到任何关于它的信息……</p>

4

2 回答 2

33

我想出了

assertTrue(math.isnan(nan_value))
于 2013-06-03T06:52:16.740 回答
13

math.isnan(x)将引发 a TypeErrorif xis既不是 afloat也不是 a 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()

于 2013-12-18T10:42:37.637 回答