我有函数,有时会返回带有float('nan')
的NaN(我没有使用numpy)。
我如何为它编写测试,因为
assertEqual(nan_value, float('nan'))
就像float('nan') == float('nan')
总是假的。可能有assertIsNan
之类的东西吗?我找不到任何关于它的东西......
答案 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()
。