18

New to unittest package. I'm trying to verify the DataFrame returned by a function through the following code. Even though I hardcoded the inputs of assert_frame_equal to be equal (pd.DataFrame([0,0,0,0])), the unittest still fails. Anyone would like to explain why it happens?

import unittest
from pandas.util.testing import assert_frame_equal
class TestSplitWeight(unittest.TestCase):
    def test_allZero(self):
        #splitWeight(pd.DataFrame([0,0,0,0]),10)
        self.assert_frame_equal(pd.DataFrame([0,0,0,0]),pd.DataFrame([0,0,0,0]))

suite = unittest.TestLoader().loadTestsFromTestCase(TestSplitWeight)
unittest.TextTestRunner(verbosity=2).run(suite)
Error: AttributeError: 'TestSplitWeight' object has no attribute 'assert_frame_equal'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Lisa
  • 4,126
  • 12
  • 42
  • 71

3 Answers3

25

alecxe answer is incomplete, you can indeed use pandas' assert_frame_equal() with unittest.TestCase, using unittest.TestCase.addTypeEqualityFunc

import unittest
import pandas as pd
import pandas.testing as pd_testing

class TestSplitWeight(unittest.TestCase):
    def assertDataframeEqual(self, a, b, msg):
        try:
            pd_testing.assert_frame_equal(a, b)
        except AssertionError as e:
            raise self.failureException(msg) from e

    def setUp(self):
        self.addTypeEqualityFunc(pd.DataFrame, self.assertDataframeEqual)

    def test_allZero(self):
        self.assertEqual(pd.DataFrame([0,0,0,0]), pd.DataFrame([0,0,0,0]))
Tom Jelen
  • 2,559
  • 1
  • 24
  • 23
Léo Germond
  • 720
  • 8
  • 18
  • I have duplicate your code and I got the following error: `TypeError: addTypeEqualityFunc() missing 1 required positional argument: 'function'`. Do you know why? – Dadou Jul 20 '20 at 17:06
  • What is the purpose of msg here? Can the message of assert_frame_equal be somehow passed to assertEqual? – Fato39 Feb 02 '21 at 15:17
  • 1
    @fato39 the msg parameter allows to pass-on an additional message, additionaly the raise...from construct used there wraps the original pandas exception into a unittest-compatible failureException. – Léo Germond Jun 08 '21 at 08:40
18

assert_frame_equal() is coming from the pandas.util.testing package, not from the unittest.TestCase class. Replace:

self.assert_frame_equal(pd.DataFrame([0,0,0,0]),pd.DataFrame([0,0,0,0]))

with:

assert_frame_equal(pd.DataFrame([0,0,0,0]), pd.DataFrame([0,0,0,0]))

When you had self.assert_frame_equal, it tried to find assert_frame_equal attribute on the unittest.TestCase instance, and, since there is not assert_frame_equal attribute or method exposed on an unittest.TestCase class, it raised an AttributeError.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
-1

If you import this, the problem is gone.

from pandas.testing import assert_frame_equal  # <-- for testing dataframes
banana_99
  • 591
  • 5
  • 15