pythonnanequalitypython-unittest

unittest - how to assert if the two possibly NaN values are equal


In my test case, I assume that if two values are NaN then they are equal. What is the way to express it using unittest assertions? The two common functions presented below are not handling this case.

v1 = np.nan
v2 = np.nan
self.assertEquals(v1, v2)
self.assertTrue(v1 == v2)

A solution that is working for me right now is using a boolean expression inside assertTrue:

self.assertTrue(v1 == v2 or (np.isnan(v1) and np.isnan(v2))

Solution

  • You could use:

    numpy.testing.assert_equal(v1, v2)
    

    From docs:

    This function handles NaN comparisons as if NaN was a “normal” number. That is, no assertion is raised if both objects have NaNs in the same positions. This is in contrast to the IEEE standard on NaNs, which says that NaN compared to anything must return False.

    It throws AssertionError when the values are not equal and it should work fine with pytest, but it may not be a good fit for unittest tests.

    Another option is:

    numpy.isclose(v1, v2, equal_nan=True)
    

    but obviously it's a replacement for math.isclose, not for ==.