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

creating pandas data frame in unittest

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

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

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 '-'

你的单元测试代码有问题。您在 subclassing unittest.TestCase 中做对了,所以这一行是可以的:

class simpleTest(unitest.TestCase):

但是,此 class 现在应该具有如下所示的方法:

     def test_foo(self):
         ...

(注意他们应该以test_开头,并且应该取self)。任何此类方法的遗漏都会混淆 unittest。

另外,您有静态 class 成员,您可能打算将其用作 class 固定装置。那是 not how it's done in unittest。您的 class 应如下所示:

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