如何在unittest中使用assert_frame_equal

时间:2016-08-08 22:24:54

标签: python pandas unit-testing python-unittest

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'

2 个答案:

答案 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]))