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
how to use assert_frame_equal in 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_equal
to 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.testing
package, not from the unittest.TestCase
class. 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_equal
attribute on the unittest.TestCase
instance, and, since there is not assert_frame_equal
attribute or method exposed on an unittest.TestCase
class, it raised an AttributeError
.
当您拥有 时self.assert_frame_equal
,它尝试assert_frame_equal
在unittest.TestCase
实例上查找属性,并且由于没有assert_frame_equal
在unittest.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]))