Python编程:从入门到实践:第11章 测试类 test1

name_function.py

# 书本P105 下面的函数接受名和姓返回整洁的姓名


# def get_formatted_name(first, last):
#     """Generate a neatly formatted full name"""
#     full_name = first + " " + last
#     return full_name.title()


def get_formatted_name(first, last, middle=""):
    """生成整洁的姓名"""
    if middle:
        full_name = first + " " + middle + " " + last
        return full_name.title()
    else:
        full_name = first + " " + last
        return full_name

names.py

# 书本P105
# 函数get_formatted_name()将名和姓合并成姓名,在名和姓之间加上一个空格,并将它们的首字母都大写,再返回结果。
# 下面的程序让用户输入名和姓,并显示整洁的全名


from name_function import get_formatted_name

print("Enter 'q' at any time to quit")
while True:
    first = input("\nPlease give me a first name:")
    if first == "q":
        break
    last = input("\nPlease give me a last name:")
    if last == "q":
        break

    formatted_name = get_formatted_name(first, last)
    print("\tNeatly formatted name:" + formatted_name + ".")

test_name_function.py

# 书本P105
# 下面的程序包含一个方法的测试用例
# 它检查函数get_formatted_name()在给定名和姓时能够正确地工作

import unittest
from name_function import get_formatted_name


class NamesTestCase(unittest.TestCase):
    """测试name_function.py"""

    def test_first_last_name(self):
        """能够正确处理像Janis Joplin这样的姓名吗?"""
        formatted_name = get_formatted_name("janis", "joplin")
        self.asserEqual(formatted_name, "Janis Joplin")

    def test_first_middle_last_name(self):
        """能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?"""
        formatted_name = get_formatted_name("wolfgang", "mozart", "amadeus")
        self.assertEqual(formatted_name, "Wolfgang Amadeus Mozart")


unittest.main()

你可能感兴趣的:(Python编程:从入门到实践)