Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if value is nan in unittest?

I've got functions, which sometimes return NaNs with float('nan') (I'm not using numpy).

How do I write a test for it, since

assertEqual(nan_value, float('nan')) 

is just like float('nan') == float('nan') always false. Is there maybe something like assertIsNan? I could not find anything about it…

like image 815
tamasgal Avatar asked Jun 03 '13 06:06

tamasgal


People also ask

How do you check if a value is a NaN?

The math. isnan() method checks whether a value is NaN (Not a Number), or not. This method returns True if the specified value is a NaN, otherwise it returns False.

How can you tell if a float is NaN?

To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.

How do you judge NaN?

The most common method to check for NaN values is to check if the variable is equal to itself. If it is not, then it must be NaN value.

How do you check if something is a NaN in Python?

A simple solution to check for a NaN in Python is using the mathematical function math. isnan() . It returns True if the specified parameter is a NaN and False otherwise.


2 Answers

I came up with

assertTrue(math.isnan(nan_value)) 
like image 84
tamasgal Avatar answered Oct 15 '22 21:10

tamasgal


math.isnan(x) will raise a TypeError if x is neither a float nor a Real.

It's better to use something like this :

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 

You can then use self.assertIsNaN() and self.assertIsNotNaN().

like image 27
LaGoutte Avatar answered Oct 15 '22 21:10

LaGoutte