How to check if value is nan in unittest?
Asked Answered
J

4

36

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…

Jamarjamb answered 3/6, 2013 at 6:13 Comment(2)
possible duplicate of How do you test to see if a double is equal to NaN in Java?Adaxial
It cannot be a possible duplicate if the language is different.Teamwork
J
39

I came up with

assertTrue(math.isnan(nan_value))
Jamarjamb answered 3/6, 2013 at 6:52 Comment(0)
T
13

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

Thrips answered 18/12, 2013 at 10:42 Comment(4)
Nice. You can achieve the same without importing the math module by simply using the comparison value != value which evaluates to True for nan values.Postremogeniture
@Postremogeniture That is very dangerous and not at all to the point of the question. Context: float("NaN") != float("NaN") would evaluate to True, but so would float("NaN") != 3, which is not at all what the user is trying to do (assert if the value is nan).Schnabel
@SlobodanIlic I think you misunderstood my comment. Provided you have the variable a = 3, then you would not write float('nan') != a to check if its value is nan. You would write is_nan = (a != a). That way is_nan is only True, if a is indeed nan.Postremogeniture
@Postremogeniture You are correct, I did misunderstand. Thanks for clarifying. I'm gonna leave the original comment in place for consistency.Schnabel
I
6

Update with NumPy: I know the OP is not using numpy. However, I had to use numpy and didn't find any post. So I'll leave the answer here for anybody that may need help. It also works perfectly with unittest library.

import numpy as np
np.testing.assert_equal(nan_value, np.nan)
Irvinirvine answered 15/12, 2022 at 16:20 Comment(1)
Unfortunately there isn't a corresponding np.testing.assert_not_equal() for testing non-equality to np.NaN:(. But assertFalse(math.isnan(nan_value)) works.Hekking
E
1

Keying off of @user3503711's answer, the following worked for me:

numpy.isnan(nan_value)

I am using numpy==1.22.2. See https://numpy.org/doc/1.22/reference/generated/numpy.isnan.html

Entomologize answered 23/12, 2022 at 15:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.