Ошибка атрибута Unittest. mymodule не имеет атрибута myclass - PullRequest
0 голосов
/ 12 июня 2019

Я пишу юнит-тест для написанного мною класса.

У меня есть следующая структура. Сначала мой модуль.

NewsStream.py

from enum import Enum
import xml.etree.ElementTree as ET
import numpy as np # linear algebra
import pandas as pd # data processing
import json
import urllib.request

# XML parser

class XMLParser:
    BASE_PATH = "../input" # TODO: substitute this with an online streaming.

    def __init__(self, file_path = ''):
        """
            Initializes the XMLParser class instance.
            :param file_path: Path to input xml file containing all the data.
            """
        self.file_path = file_path


    def xml_to_pandas_df(self, columns = []):
        """
            Using the standard xml python library, we parse the data xml file and convert the xml data to a pandas data frame.
            :return: A pandas data frame instance containing all the data.
            """

        xml = objectify.parse(self.file_path)
        root = xml.getroot()

        data=[]
        for i in range(len(root.getchildren())):
            data.append([child.text for child in root.getchildren()[i].getchildren()])

        df = pd.DataFrame(data)
        df.columns = columns

        return df

    def url_to_pandas_df(self, url, set_index = False, index_name = None):
        """
            Using urllib python library, we download the data from a url and convert them into a pandas dataframe.
            :return: a pandas dataframe instance containing all the data
            """

        f = urllib.request.urlopen(url)
        myfile = f.read()
        data = json.loads(myfile.decode('utf-8'))
        df = pd.DataFrame(data)

        if set_index:
            df = df.set_index(index_name)

        return df

Следовательно, мой юнит-тест

LKCluster-unittest.py

import NewsStream
import unittest

BASE_PATH = './TestInput/'

class test_XMLparser(unittest.TestCase):
    """ Test class for functions of XMLparser. """


    def test_parser_xml_empty(self):
        """ Test xml parser in the case of an empty xml. """

        file_path = BASE_PATH + 'empty.xml'
        parser = NewsStream.XMLparser(file_path)
        df = parser.xml_to_pandas_df()
        actual = df.empty
        expected = True
        self.assertEqual(actual, expected)

    def test_parser_xml_50(self):
        """ Test xml parser in the case of a fifty-record xml. """

        file_path = BASE_PATH + 'test50.xml'
        columns = ['CategoryCode', 'DateTime', 'ID', 'SourceCode', 'Text', 'Title']
        parser = NewsStream.XMLparser(file_path)
        df = parser.xml_to_pandas_df(columns = columns)
        actual = len(df)
        expected = 50
        self.assertEqual(actual, expected)


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

Когда я интерпретирую свою оболочку, я получаю следующую ошибку

~:$ python3 LKCluster-unittest.py 
EE
======================================================================
ERROR: test_parser_xml_50 (__main__.test_XMLparser)
Test xml parser in the case of a fifty-record xml.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "LKCluster-unittest.py", line 32, in test_parser_xml_50
    parser = NewsStream.XMLparser(file_path)
AttributeError: module 'NewsStream' has no attribute 'XMLparser'

======================================================================
ERROR: test_parser_xml_empty (__main__.test_XMLparser)
Test xml parser in the case of an empty xml.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "LKCluster-unittest.py", line 21, in test_parser_xml_empty
    parser = NewsStream.XMLparser(file_path)
AttributeError: module 'NewsStream' has no attribute 'XMLparser'

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=2)

Почему он не видит функции класса? Когда я использую класс в скрипте, он отлично работает.

p.s .: версия python 3.7, и я запускаю ее как на Mac OSX, так и на Ubuntu

...