Unittest追溯问题

时间:2017-04-21 19:41:56

标签: python list unit-testing

我的下面代码出现问题我的单元测试。我一直收到追溯,我不知道为什么。我的程序运行正常,除了我创建的Unittests。对于unittest,我只想确保在all_first_words中返回第一个单词。任何帮助都会很棒。

追溯:

area  Count
river     3
beach     1
item      1

正在测试的代码:

  File "final_project.py", line 219, in test_first_words_list
    self.assertEqual(Song().firstwords(["hello world"]),["hello"])
  File "final_project.py", line 69, in firstwords
    first_word = track.trackName.partition(' ')[0] # split the string at the first word, isolates the first word in the title
AttributeError: 'str' object has no attribute 'trackName'




import unittest
class TestSong(unittest.TestCase):
def test_first_words_list(self):
        self.assertEqual(Song().firstwords(["hello world"]),["hello"])
if __name__ == "__main__":
    unittest.main()

1 个答案:

答案 0 :(得分:1)

track 变量是字符串

您可以像这样简化代码:

def firstwords(self,large_song_list):
    """ method that takes the first word of each song title
    and creates a list containing that first word
    """
    all_first_words = [] # create an empty list 
    for track in large_song_list: 
        first_word = track.partition(' ')[0] # split the string at the first word, isolates the first word in the title 
        all_first_words.append(first_word)
    return all_first_words

注意:这可以通过comprehension list

在一行中完成
    all_first_words = [track.partition(' ')[0] for track in large_song_list]