单元测试回溯问题

2024-10-03 13:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我的以下代码有问题,我的一个单元测试。我一直收到回溯,我不知道为什么。我的程序运行良好,除了我所做的单元测试已创建。用于unittest我只想确保返回的第一个单词在所有的\u第一个单词中。任何帮助都会很好。你知道吗

回溯:

  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

Tags: theinselfhellosongtitletrackunittest
1条回答
网友
1楼 · 发布于 2024-10-03 13:27:15

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]

相关问题 更多 >