首页 > 解决方案 > 熊猫的单元测试

问题描述

我正在尝试对我用 Python 编写的名为 NeuralNetworkModel() 的类进行单元测试。它是一个接收文件并训练 ANN 模型并将其保存为 pickle 文件的类。目前我有一个非常基本的单元测试,该类正在正确地将文件作为数据框读取。我的代码如下。

import unittest
import pandas as pd
from pandas.util.testing import assert_frame_equal
from NN_model import NeuralNetworkModel

class NeuralNetworkModel(unittest.TestCase):

    def test(self):
        self.assertTrue(True)

    @classmethod
    def set_up(cls):
        """ SetUp """
        test_input_dir = '/home/student/data_analytics/prediction_model/clean_files/'
        test_file_name = '25_1.csv'
        try:
            data = pd.read_csv(test_input_dir + test_file_name, sep = ',')
        except IOError:
            print('Cannot Open File')
        cls.fixture = data

    def test_dataFrame_constrcuted_as_expected(self):
        """ Test that the dataframe read in equals what you expect"""
        foo = pd.DataFrame()
        assert_frame_equal(self.fixture, foo)


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

运行此文件时出现的错误是

ERROR: test_dataFrame_constrcuted_as_expected (__main__.NeuralNetworkModel)
Test that the dataframe read in equals what you expect
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_NN_model.py", line 25, in test_dataFrame_constrcuted_as_expected
    assert_frame_equal(self.fixture, foo)
AttributeError: 'NeuralNetworkModel' object has no attribute 'fixture'

----------------------------------------------------------------------
Ran 2 tests in 0.002s

FAILED (errors=1)

我对单元测试很陌生,我很挣扎,但我不知道为什么我的测试没有通过?

标签: pythonpandasunit-testing

解决方案


确保您正确命名事物。unittest不认识set_up(),所以它永远不会被调用。将其重命名为setUpClass(),它应该可以工作。

文档供参考。


推荐阅读