19

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'

3 Answers 3

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]))
3
  • 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, 2020 at 17:06
  • What is the purpose of msg here? Can the message of assert_frame_equal be somehow passed to assertEqual?
    – Fato39
    Feb 2, 2021 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. Jun 8, 2021 at 8:40
21

assert_frame_equal() comes from the pandas.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.

0
-1

If you import this, the problem is gone.

from pandas.testing import assert_frame_equal  # <-- for testing dataframes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.