2017-09-28 49 views
0

這是爲了測試這個類;然而,我收到一個錯誤,我不知道如何解決它。Python速成教程,測試你的代碼示例

import unittest 
from name_function import get_formatted_name 

class NamesTestCase(unittest.TestCase): 
    """Tests for 'name_function.py'""" 

    def test_first_last_name(self): 
    """Do names like 'Mark James' work?""" 
    formatted_name = get_formatted_name('mark','James') 
    self.assertEqual(formatted_name,'Mark James') 

unittest.main() 

這裏是正在測試的類。

def get_formatted_name(first, last): 
    """This is where the name is formatted correctly""" 
    full_name = first + " " + last 
    return full_name.title() 

我得到的錯誤是這樣的:

/Desktop/python_work/test_name_function.py", line 1, in <module> 
    import unittest 
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/__init__.py", line 58, in <module> 
    from .result import TestResult 
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/result.py", line 5, in <module> 
    import traceback 
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/traceback.py", line 3, in <module> 
    import linecache 
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/linecache.py", line 10, in <module> 
    import tokenize 
    File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tokenize.py", line 96, in <module> 
    class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')): 
AttributeError: 'module' object has no attribute 'namedtuple' 

任何有線索?

+6

沒有你的名字你自己的文件或模塊'collections'一個? – PRMoureu

+0

'import unittest'發生異常 - 它看起來與您的課​​程沒有任何關係。 – wwii

+0

我完全沒有碰到unittest文件 –

回答

0

我相信你需要,如果 '' == '主要' 添加: unittest.main()到您的代碼。

下面的代碼應該修正這個錯誤 -

import unittest 
from name_function import get_formatted_name 

class NamesTestCase(unittest.TestCase): 
    """Tests for 'name_function.py'""" 

    def test_first_last_name(self): 
     """Do names like 'Mark James' work?""" 
     formatted_name = get_formatted_name('mark','James') 
     self.assertEqual(formatted_name,'Mark James') 
if '__name__' == '__main__': 
    unittest.main() 
+0

這與導入錯誤有什麼關係? –