Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use assert_frame_equal in unittest

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'
like image 970
Lisa Avatar asked Aug 08 '16 22:08

Lisa


People also ask

How do you assert two data frames?

The equals() function is used to test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements.

How do I compare two DataFrames in Python?

The compare method in pandas shows the differences between two DataFrames. It compares two data frames, row-wise and column-wise, and presents the differences side by side. The compare method can only compare DataFrames of the same shape, with exact dimensions and identical row and column labels.

Is PyUnit and unittest same?

PyUnit is an easy way to create unit testing programs and UnitTests with Python. (Note that docs.python.org uses the name "unittest", which is also the module name.)


1 Answers

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]))
like image 131
Léo Germond Avatar answered Oct 05 '22 22:10

Léo Germond