编写函数或类时,还可为其编写测试。通过测试,可确定代码面对各种输入都能够按要求的那样工作。

单元测试和测试用例

Python标准库中的模块unittest提供了代码测试工具。单元测试用于核实函数的某个方面没有问题;测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。良好的测试用例考虑到了函数可能收到的各种输入,包含针对所有这些情形的测试。全覆盖式测试用例包含一整套单元测试,涵盖了各种可能的函数使用方式。
测试函数,
name_function.py

def get_formatted_name(first,last):
    #获取全部名字
    full_name = first+' '+last
return full_name.title()
可通过的测试用例
test_name_function.py
import unittest
from name_function import get_formatted_name

测试类

class NamesTestCase(unittest.TestCase):   #必须继承unittest.TestCase类
    def test_first_last_name(self):
        formatted_name = get_formatted_name('janis','joplin')
        self.assertEqual(formatted_name,'Janis Joplin')
unittest.main()

代码行unittest.main()让Python运行这个文件中的测试。输出结果如下:

怎么看一个python项目 python程序怎么看代码_测试用例

上述输出表明,给定包含名和姓的姓名时,函数get_formatted_name()总是能正确地处理。修改get_formatted_name()后,再次运行。

不能通过的测试

下面是get_formatted_name()的新版本,他要求通过一个实参指定中间名:

def get_formatted_name(first,middle,last):
    #获取全部名字
    full_name = first+' '+middle+' '+last
return full_name.title()

再次运行测试用例输出:

怎么看一个python项目 python程序怎么看代码_测试用例_02

测试类

前面介绍了编写针对单个函数的测试,下面编写针对类的测试,。很多程序中都会用到类,因此能够证明你的类能够正确的工作会大有裨益。

一个要测试的类

类的测试与函数的测试相似——你所做的大部分的工作都是测试类中方法的行为,但存在一些不同之处,下面编写一个类进行测试。

survey.py

class AnonymousSurvey():
    #收集匿名调查问卷答案
    def __init__(self,question):
        self.question = question
        self.responses = []

    def show_question(self):
        #打印问卷调查
        print(self.question)

    def store_response(self,new_response):
        self.responses.append(new_response)

    def show_result(self):
        #显示所有的答案
        print("Survey results:")
        for response in self.responses:
            print('-'+response)

为证明AnonymousSurvey类能够正确的工作,我们编写一个使用它的程序
language_survey.py

from survey import AnonymousSurvey

#定义一个问题,并创建一个表示调查的AnonymousSurvey对象
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)

#显示问题并存储答案
my_survey.show_question()
print("Enter 'q' at any time to quit.\n")
while True:
    response = input("Language:")
    if response == 'q':
        break;
    my_survey.store_response(response)

#显示调查结果
print("\n 谢谢每一个参加回答!")
my_survey.show_results()

输出结果:

怎么看一个python项目 python程序怎么看代码_测试类_03

测试AnonymousSurvey类

下面编写一个测试,对AnonymousSurvey类的行为的一个方面进行验证。

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):
    #针对AnonymousSurvey类的测试
    def test_store_single_response(self):
        question = "What language did you first learn to speak?"
        my_survey = AnonymousSurvey(question)
        responses = ['English','Spanish','Chinese']

        for response in responses:
            my_survey.store_response(response)

        for response in responses:
            self.assertIn(response,my_survey.responses)
unittest.main()

测试结果:

怎么看一个python项目 python程序怎么看代码_测试类_04