2013-06-03 10 views
11

Ho funzioni, che a volte restituiscono NaN con float('nan') (non sto usando numpy).Come verificare se il valore è nan in unittest?

Come faccio a scrivere un test per esso, dal momento che

assertEqual(nan_value, float('nan')) 

è proprio come float('nan') == float('nan') sempre false. C'è forse qualcosa come assertIsNan? Non sono riuscito a trovare nulla ...

+0

possibile duplicato di [Come verificare se un doppio è uguale a NaN in Java?] (Http://stackoverflow.com/questions/1456566/how-do-you-test-to-see-if -a-doppio-è uguale a nan-in-java) – Raedwald

risposta

10

mi si avvicinò con

assertTrue(math.isnan(nan_value)) 
7

math.isnan(x) alzerà un TypeError se x non è né un float né una Real.

E 'meglio usare qualcosa di simile:

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 

È quindi possibile utilizzare self.assertIsNaN() e self.assertIsNotNaN().