[Python] Testing equality of lists which contain NaN

Discussão em 'Python' iniciado por Stack, Julho 12, 2025.

  1. Stack

    Stack Membro Participativo

    I have a small class for which I am writing tests. The result for my function contains nan which causes my test to fail because nan is not equal to any other nan. How do I write a proper test for this?

    from math import nan
    import unittest
    import pandas as pd


    class holder:
    def __init__(self, source: list) -> None:
    self.source = source
    self.data = []

    def calculate_rolling_average(self):
    self.data = pd.Series(self.source).rolling(3).mean().to_list()


    class test_value(unittest.TestCase):
    def setUp(self):
    self.hold = holder(source=[10, 20, 30, 40])

    def test_rolling_simple_average_for_list(self):
    expected_result = [nan, nan, 20.0, 30.0]
    self.hold.calculate_rolling_average()
    self.assertSequenceEqual(self.hold.data, expected_result)


    unittest.main()



    This results in:

    >>> AssertionError: Sequences differ: [nan, nan, 20.0, 30.0] != [nan, nan, 20.0, 30.0]

    First differing element 0:
    nan
    nan

    [nan, nan, 20.0, 30.0]


    I read How to assert if the two possibly NaN values are equal which is testing a singular value for numpy.nan so the same does not apply to this question.

    Continue reading...

Compartilhe esta Página