2017-04-21 36 views
-1

我遇到了我的下面的代码my a Unittest问题。我不断收到回溯,我不知道为什么。我的程序运行良好,除了我创建的Unittests。对于unittest,我只是想确保在all_first_words中返回第一个单词。任何帮助都会很棒。Unittest Traceback问题

回溯:

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() 

:被测试代码:

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.trackName.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 
+1

你传递一个字符串列表。字符串没有'trackName'属性。这正是错误消息所说的.... –

回答

1

轨道变量是字符串

您可以简化代码:

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]