pandas 如何在单元测试中使用 assert_frame_equal

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38839402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:45:56  来源:igfitidea点击:

how to use assert_frame_equal in unittest

pythonpandasunit-testingpython-unittest

提问by Lisa

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_equalto be equal (pd.DataFrame([0,0,0,0])), the unittest still fails. Anyone would like to explain why it happens?

新的单元测试包。我正在尝试通过以下代码验证函数返回的 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'

采纳答案by alecxe

assert_frame_equal()is coming from the pandas.util.testingpackage, not from the unittest.TestCaseclass. Replace:

assert_frame_equal()来自pandas.util.testing包,而不是来自unittest.TestCase班级。代替:

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_equalattribute on the unittest.TestCaseinstance, and, since there is not assert_frame_equalattribute or method exposed on an unittest.TestCaseclass, it raised an AttributeError.

当您拥有 时self.assert_frame_equal,它尝试assert_frame_equalunittest.TestCase实例上查找属性,并且由于没有assert_frame_equalunittest.TestCase类上公开属性或方法,因此它引发了一个AttributeError.

回答by Léo Germond

alecxe answer is incomplete, you can indeed use pandas' assert_frame_equal()with unittest.TestCase, using unittest.TestCase.addTypeEqualityFunc

alecxe 答案不完整,您确实可以使用 pandas' assert_frame_equal()with unittest.TestCase,使用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]))