我认为这更像是一个PyCharm问题,而不是单元测试问题,但是我正在从一本书中学习测试,这个例子让我失败了。我正在运行PyCharm 2016.3.2和Python 3.6
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 'Janis Joplin' work?"""
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
# In book, it's just the unittest.main() , which does not work...
# So in PyCharm __name__ doesn't equal __main__ ... not sure why
# if __name__ == '__main__':
unittest.main()
这是name_function.py:
def get_formatted_name(first, last):
"""Generate a neatly formatted full name."""
full_name = first + " " + last
return full_name.title()
如果我按照写入的方式运行它,我会收到以下错误:
EE
======================================================================
ERROR: test_name_function (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'test_name_function'
======================================================================
ERROR: true (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'true'
----------------------------------------------------------------------
Ran 2 tests in 0.000s
如果我让"如果"语句运行(或只是删除对unittest.main()的调用)然后它正常工作,根本没有main()调用。
这一切都在test_name_function.py
。因此,当运行这个文件(并导入name_function.py
)时,PyCharm似乎不认为这个文件是__main__
? PyCharm在幕后做了别的事吗?
我是Python和PyCharm的新手,并试图了解结构和环境。非常感谢你们。
答案 0 :(得分:0)
您可以使用此方法来解决问题。
suite = unittest.defaultTestLoader.loadTestsFromTestCase(NamesTestCase)
unittest.TextTestRunner().run(suite)