单元测试示例不起作用
Unittest example not working
我正在学习 python,尤其是单元测试。
我正在尝试遵循以下简单示例,其中被测试的功能是:
def get_formatted_name(first, last):
"""Generate a neatly formatted name"""
full_name = first + ' ' + last
return full_name.title()
测试代码为:
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 liike 'Janis Joplin' work """
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()
根据示例,这应该 运行 正常并报告测试 运行 成功。
但是我收到以下错误:
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
FAILED (errors=2)
Process finished with exit code 1
不幸的是,我不知道出了什么问题!
根据文档,您需要添加以下代码。这样它将 运行 作为主要模块而不是其他任何东西。可以看例子here.
if __name__ == '__main__':
unittest.main()
我正在学习 python,尤其是单元测试。
我正在尝试遵循以下简单示例,其中被测试的功能是:
def get_formatted_name(first, last):
"""Generate a neatly formatted name"""
full_name = first + ' ' + last
return full_name.title()
测试代码为:
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 liike 'Janis Joplin' work """
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()
根据示例,这应该 运行 正常并报告测试 运行 成功。
但是我收到以下错误:
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
FAILED (errors=2)
Process finished with exit code 1
不幸的是,我不知道出了什么问题!
根据文档,您需要添加以下代码。这样它将 运行 作为主要模块而不是其他任何东西。可以看例子here.
if __name__ == '__main__':
unittest.main()