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'
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.
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.
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.)
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]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With