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…
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.
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.
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.
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.
I came up with
assertTrue(math.isnan(nan_value))
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With