gpt4 book ai didi

pandas - 在单元测试中创建 Pandas 数据框

转载 作者:行者123 更新时间:2023-12-04 02:10:30 36 4
gpt4 key购买 nike

在我的单元测试文件中尝试创建 Pandas 数据框时,我遇到了一个我不明白的问题。该错误发生在类中的函数被调用之前。

这里是一个简单的重现代码:

import unittest
import pandas as pd
import numpy as np

class simpleTest(unitest.TestCase):
dates = pd.date_range('20160101', periods = 5)
dataDf = pd.DataFrame({'date': dates,
'count': np.array([3, 7, 4, 66, 9])})

def doSomething(self):
pass

if __name__ == '__main__':
unittest.main()

我得到的错误是这样的:

Traceback (most recent call last):
File "tsa_test.py", line 31, in <module>
unittest.main()
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 94, in __init__
self.parseArgs(argv)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 149, in parseArgs
self.createTests()
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 158, in createTests
self.module)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute '-'

最佳答案

您的单元测试代码有问题。您在子类化 unittest.TestCase 方面做对了,所以这一行没问题:

class simpleTest(unitest.TestCase):

但是,这个类现在应该有如下所示的方法:

     def test_foo(self):
...

(注意它们应该以 test_ 开头,并且应该以 self 开头)。遗漏任何此类方法都会混淆单元测试。

另外,您有静态类成员,您可能打算将其用作类固定装置。那是 not how it's done in unittest .你的类应该是这样的:

class simpleTest(unitest.TestCase):
@classmethod
def setUpClass(cls):
cls.dates = pd.date_range('20160101', periods = 5)
cls.dataDf = pd.DataFrame({'date': cls.dates,
'count': np.array([3, 7, 4, 66, 9])})

def test_foo(self):
# Note that here you access things like so:
self.dataDF
# even though you defined it as a class instance - that's how unittest works

关于pandas - 在单元测试中创建 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39003261/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com