2013-06-03 29 views
11

我有功能,有时返回NaNs float('nan')(我不使用numpy)。如何检查单位测试中的值是否为nan?

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

assertEqual(nan_value, float('nan')) 

就像float('nan') == float('nan')始终为false。有没有像assertIsNan?我找不到任何关于它...

+0

可能的重复[你如何测试以查看double是否等于NaN在Java?](http://stackoverflow.com/questions/1456566/how-do-you-test-to-see-if -a-双是相等到南在-java的) – Raedwald

回答

10

我想出了

assertTrue(math.isnan(nan_value)) 
7

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()

相关问题