unittest包新手。
我试图通过以下代码验证函数返回的DataFrame。即使我将assert_frame_equal
的输入硬编码为相等(pd.DataFrame([0,0,0,0])
),单位测试仍然失败。有人想解释它为什么会发生吗?
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'
答案 0 :(得分:7)
assert_frame_equal()
来自pandas.util.testing
包,而非来自unittest.TestCase
类。替换:
self.assert_frame_equal(pd.DataFrame([0,0,0,0]),pd.DataFrame([0,0,0,0]))
使用:
assert_frame_equal(pd.DataFrame([0,0,0,0]), pd.DataFrame([0,0,0,0]))
当您有self.assert_frame_equal
时,它会尝试在assert_frame_equal
个实例上找到unittest.TestCase
属性,并且由于assert_frame_equal
属性或方法没有公开unittest.TestCase
1}}类,它引发了AttributeError
。
答案 1 :(得分:3)
alecxe答案不完整,您确实可以使用unittest.TestCase.addTypeEqualityFunc
assert_frame_equal()
与unittest.TestCase
一起使用
import unittest
import pandas as pd
import pandas.testing as pd_testing
class TestSplitWeight(unittest.TestCase):
def assertDataframequal(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]))