我有一些函数,有时会返回 NaN float('nan')
(我没有使用 numpy)。
我如何为它写一个测试,因为
assertEqual(nan_value, float('nan'))
就像float('nan') == float('nan')
总是假的一样。可能有类似的东西assertIsNan
吗?我找不到任何关于它的信息……</p>
我有一些函数,有时会返回 NaN float('nan')
(我没有使用 numpy)。
我如何为它写一个测试,因为
assertEqual(nan_value, float('nan'))
就像float('nan') == float('nan')
总是假的一样。可能有类似的东西assertIsNan
吗?我找不到任何关于它的信息……</p>
我想出了
assertTrue(math.isnan(nan_value))
math.isnan(x)
将引发 a TypeError
if x
is既不是 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()
。