在unittest中创建pandas数据框

时间:2016-08-17 17:50:34

标签: pandas python-unittest

我正在尝试在我的unittest文件中创建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 '-'

1 个答案:

答案 0 :(得分:3)

您的unittest代码存在问题。你在子类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