11 测试代码
编写函数或类时,还可为其编写测试。通过测试,可确定代码面对各种输入都能够按要求的那样工作。在程序中添加新代码时,你也可以对其进行测试,确认它们不会破坏程序既有的行为。
在本章中,你将学习如何使用Python模块unittest
中的工具来测试代码。你将学习编写测试用例,核实一系列输入都将得到预期的输出。你将看到测试通过了是什么样子,测试未通过又是什么样子,还将知道测试未通过如何有助于改进代码。你将学习如何测试函数和类,并将知道该为项目编写多少个测试。
"""11.1 测试函数"""
"""
下面是一个简单的函数,它接受名和姓并返回整洁的姓名:
"""
"""name_function.py"""
def get_formatted_name(first, last):
"""Generate a neatly formatted full name."""
full_name = first + ' ' + last
return full_name.title()
"""
为核实get_formatted_name()像期望的那样工作,我们来编写一个
使用这个函数的程序。程序names.py让用户输入名和姓,并显示整洁的全名:
"""
"""names.py"""
from name_function import get_formatted_name
print "Enter 'q' at any time to quit."
while True:
first = raw_input("\nPlease give me a first name: ")
if first == 'q':
break
last = raw_input("Please give me a last name: ")
if last == 'q':
break
formatted_name = get_formatted_name(first, last)
print("\tNeatly formatted name: " + formatted_name + '.')
Enter 'q' at any time to quit.
Please give me a first name: janis
Please give me a last name: joplin
Neatly formatted name: Janis Joplin.
Please give me a first name: bob
Please give me a last name: dylan
Neatly formatted name: Bob Dylan.
Please give me a first name: q
从上述输出可知,合并得到的姓名正确无误。现在假设我们要修改get_formatted_name()
,使其还能够处理中间名。这样做时,我们要确保不破坏这个函数处理只有名和姓的姓名的方式。为此,我们可以在每次修改get_formatted_name()
后都进行测试:运行程序names.py,并输入像Janis Joplin这样的姓名,但这太烦琐了。
所幸Python提供了一种自动测试函数输出的高效方式。倘若我们对get_formatted_name()
进行自动测试,就能始终信心满满,确信给这个函数提供我们测试过的姓名时,它都能正确地工作。
11.1.1 单元测试和测试用例
Python标准库中的模块unittest
提供了代码测试工具。
单元测试用于核实函数的某个方面没有问题;测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。
良好的测试用例考虑到了函数可能收到的各种输入,包含针对所有这些情形的测试。全覆盖式测试用例包含一整套单元测试,涵盖了各种可能的函数使用方式。对于大型项目,要实现全覆盖可能很难。通常,最初只要针对代码的重要行为编写测试即可,等项目被广泛使用时再考虑全覆盖。
11.1.2 可通过的测试
要为函数编写测试用例,可先导入模块unittest
以及要测试的函数,再创建一个继承unittest.TestCase
的类,并编写一系列方法(需要以test或Test开头)对函数行为的不同方面进行测试。 下面是一个只包含一个方法的测试用例,它检查函数get_formatted_name()
在给定名和姓时能否正确地工作:
#############name_function.py############################
def get_formatted_name(first, last):
# Generate a neatly formatted full name
full_name = first + ' ' + last
return full_name.title()
#########################################################
print("单元测试和测试用例")
# 我们可以在每次修改get_formatted_name()后都进行测试:
# 运行程序names.py,并输入像Janis Joplin这样的姓名,但这太烦琐了
# 所幸Python提供了一种自动测试函数输出的高效方式。
# 倘若我们对get_formatted_name()进行自动测试,就能始终信心满满,确信给这个函数提供我们测试过的姓名时,它都能正确地工作。
import unittest
from name_function import get_formatted_name
# 这个类必须继承unittest.TestCase类
class NameTestCase(unittest.TestCase):
# 测试name_function.py
def test_first_last_name(self):
# 能够正确地处理像Janis Joplin这样的姓名
formatted_name = get_formatted_name('janis', 'joplin')
# 将formatted_name的值同字符串'Janis Joplin'进行比较
self.assertEqual(formatted_name, 'Janis Joplin')
# 让Python运行这个文件中的测试
unittest.main()
###############################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
单元测试和测试用例
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Process finished with exit code 0
###################################################################################
①处,我们使用了unittest
类最有用的功能之一:一个断言方法。断言方法用来核实得到的结果是否与期望的结果一致。
在这里,我们期望formatted_name
的值为"Janis Joplin"
。为检查是否确实如此,我们调用unittes
t的方法assertEqual()
,并向它传递formatted_name
和"Janis Joplin"
进行比较。代码行unittest.main()
让Python运行这个文件中的测试。
1.1.3 不能通过的测试
修改get_formatted_name(),使其能够处理中间名,但这样做时,故意让这个函数无法正确地处理像Janis Joplin这样只有名和姓的姓名。
#############name_function.py############################
def get_formatted_name(first, middle, last):
# Generate a neatly formatted full name
full_name = first + ' ' + middle + last
return full_name.title()
#########################################################
print("单元测试和测试用例")
# 我们可以在每次修改get_formatted_name()后都进行测试:
# 运行程序names.py,并输入像Janis Joplin这样的姓名,但这太烦琐了
# 所幸Python提供了一种自动测试函数输出的高效方式。
# 倘若我们对get_formatted_name()进行自动测试,就能始终信心满满,确信给这个函数提供我们测试过的姓名时,它都能正确地工作。
import unittest
from name_function import get_formatted_name
# 这个类必须继承unittest.TestCase类
class NameTestCase(unittest.TestCase):
# 测试name_function.py
def test_first_last_name(self):
# 能够正确地处理像Janis Joplin这样的姓名
formatted_name = get_formatted_name('janis', 'joplin')
# 将formatted_name的值同字符串'Janis Joplin'进行比较
self.assertEqual(formatted_name, 'Janis Joplin')
# 让Python运行这个文件中的测试
unittest.main()
###################################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
单元测试和测试用例
E
======================================================================
ERROR: test_first_last_name (__main__.NameTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "H:/python/venv/pizza.py", line 13, in test_first_last_name
formatted_name = get_formatted_name('janis', 'joplin')
TypeError: get_formatted_name() missing 1 required positional argument: 'last'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Process finished with exit code 1
###########################################################################
下面是函数get_formatted_name()的新版本,它要求通过一个实参指定中间名:
"""name_function.py"""
def get_formatted_name(first, middle, last):
"""生成整洁的姓名"""
full_name = first + ' ' + middle + ' ' + last
return full_name.title()
运行程序test_name_function.py
"""test_name_function.py"""
import unittest
#from name_function import get_formatted_name
def get_formatted_name(first, middle, last):
"""生成整洁的姓名"""
full_name = first + ' ' + middle + ' ' + last
return full_name.title()
class NamesTestCase(unittest.TestCase): # 这个类必须继承unittest.TestCase类
"""测试name_function.py"""
def test_first_last_name(self):
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
if __name__ == '__main__':
# unittest.main()
unittest.main(argv=['first-arg-is-ignored'], exit=False)
E
======================================================================
ERROR: test_first_last_name (__main__.NamesTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "<ipython-input-22-c6f1d3890843>", line 15, in test_first_last_name
formatted_name = get_formatted_name('janis', 'joplin')
TypeError: get_formatted_name() takes exactly 3 arguments (2 given)
----------------------------------------------------------------------
Ran 1 test in 0.041s
FAILED (errors=1)
11.1.4 测试未通过时怎么办
测试未通过时怎么办呢?如果你检查的条件没错,测试通过了意味着函数的行为是对的,而测试未通过意味着你编写的新代码有错。因此,测试未通过时,不要修改测试,而应修复导致测试不能通过的代码:检查刚对函数所做的修改,找出导致函数行为不符合预期的修改。
在这个示例中,get_formatted_name()
以前只需要两个实参——名和姓,但现在它要求提供名、中间名和姓。就这里而言,最佳的选择是让中间名变为可选的。这样做后,使用类似于Janis Joplin的姓名 进 行 测 试 时 , 测 试 就 会 通 过 了 , 同 时 这 个 函 数 还 能 接 受 中 间 名 。 下 面 来 修 改get_formatted_name()
,将中间名设置为可选的,然后再次运行这个测试用例。如果通过了,我们接着确认这个函数能够妥善地处理中间名。
将中间名设置为可选的,可在函数定义中将形参middle移到形参列表末尾,并将其默认值指定为一个空字符串。我们还要添加一个if测试,以便根据是否提供了中间名相应地创建姓名:
# get_formatted_name()以前只需要两个实参——名和姓,
# 但现在它要求提供名、中间名和姓。就这里而言,最佳的选择是让中间名变为可选的
"""name_function.py"""
def get_formatted_name(first, last, middle=''):
# Generate a neatly formatted full name
if middle:
full_name = first + ' ' + middle + ' ' + last
else:
full_name = first + ' ' + last
return full_name.title()
#################################################################3
print("单元测试和测试用例")
# 我们可以在每次修改get_formatted_name()后都进行测试:
# 运行程序names.py,并输入像Janis Joplin这样的姓名,但这太烦琐了
# 所幸Python提供了一种自动测试函数输出的高效方式。
# 倘若我们对get_formatted_name()进行自动测试,就能始终信心满满,确信给这个函数提供我们测试过的姓名时,它都能正确地工作。
import unittest
from name_function import get_formatted_name
# 这个类必须继承unittest.TestCase类
class NameTestCase(unittest.TestCase):
# 测试name_function.py
def test_first_last_name(self):
# 能够正确地处理像Janis Joplin这样的姓名
formatted_name = get_formatted_name('janis', 'joplin')
print(formatted_name)
# 将formatted_name的值同字符串'Janis Joplin'进行比较
self.assertEqual(formatted_name, 'Janis Joplin')
# 让Python运行这个文件中的测试
unittest.main()
######################################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
单元测试和测试用例
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Janis Joplin
Process finished with exit code 0
######################################################################################
11.1.5 添加新测试
确定get_formatted_name()
又能正确地处理简单的姓名后,我们再编写一个测试,用于测试包含中间名的姓名。为此,我们在NamesTestCase
类中再添加一个方法:
# get_formatted_name()以前只需要两个实参——名和姓,
# 但现在它要求提供名、中间名和姓。就这里而言,最佳的选择是让中间名变为可选的
"""name_function.py"""
def get_formatted_name(first, last, middle=''):
# Generate a neatly formatted full name
if middle:
full_name = first + ' ' + middle + ' ' + last
else:
full_name = first + ' ' + last
return full_name.title()
##################################################################################
# 我们可以在每次修改get_formatted_name()后都进行测试:
# 运行程序names.py,并输入像Janis Joplin这样的姓名,但这太烦琐了
# 所幸Python提供了一种自动测试函数输出的高效方式。
# 倘若我们对get_formatted_name()进行自动测试,就能始终信心满满,确信给这个函数提供我们测试过的姓名时,它都能正确地工作。
import unittest
from name_function import get_formatted_name
# 这个类必须继承unittest.TestCase类
class NameTestCase(unittest.TestCase):
# 测试name_function.py
def test_first_last_name(self):
# 能够正确地处理像Janis Joplin这样的姓名
formatted_name = get_formatted_name('janis', 'joplin')
print(formatted_name)
# 将formatted_name的值同字符串'Janis Joplin'进行比较
self.assertEqual(formatted_name, 'Janis Joplin')
# 又能正确地处理简单的姓名后,我们再编写一个测试,用于测试包含中间名的姓名。为此,我们在NamesTestCase类中再添加一个方法:
def test_first_last_middle_name(self):
formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
# 让Python运行这个文件中的测试
unittest.main()
##########################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
Janis Joplin
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
Process finished with exit code 0
###########################################################################
习题11-1 城市和国家:
编写一个函数,它接受两个形参:一个城市名和一个国家名。这个函数返回一个格式为 City, Country
的字符串,如 Santiago, Chile
。将这个函数存储在一个名为 city_functions.py 的模块中。
创建一个名为 test_cities.py 的程序,对刚编写的函数进行测试(别忘了,你需要导入模块 unittest
以及要测试的函数)。编写一个名为 test_city_country()
的方法,核实使用类似于 ‘santiago’ 和 ‘chile’ 这样的值来调用前述函数时,得到的字符串是正确的。
运行 test_cities.py,确认测试 test_city_country()
通过了。
'''test_cities.py'''
def city_country(City, Country):
fullname = City + ' '+ Country
return fullname.title()
###########################################################
import unittest
from test_cities import city_country
class CityCountry(unittest.TestCase):
def test_city_country(self):
formatted_string = city_country('santiago', 'chile')
self.assertEqual(formatted_string, 'Santiago Chile')
unittest.main()
############################################################
习题11–2 人口数量:
修改前面的函数,使其包含第三个必不可少的形参 population
,并返回一个格式为 City, Country – population xxx
的字符串,如 Santiago, Chile – population 5000000
。运行 test_cities.py,确认测试 test_city_country()
未通过。
修改上述函数,将形参population
设置为可选的。再次运行 test_cities.py,确认测试 test_city_country()
又通过了。
再编写一个名为 test_city_country_population()
的测试,核实可以使用类似于 ‘santiago’、’chile’ 和 ‘population=5000000’ 这样的值来调用这个函数。再次运行test_cities.py,确认测试 test_city_country_population()
通过了。
'''test_cities.py'''
def city_country(City, Country, population=''):
if population == 5000:
fullname = City + ' ' + Country + ' ' + str(population)
else:
fullname = City + ' ' + Country
return fullname.title()
##########################################################################3
import unittest
from test_cities import city_country
class CityCountry(unittest.TestCase):
def test_city_country(self):
formatted_string = city_country('santiago', 'chile')
self.assertEqual(formatted_string, 'Santiago Chile')
def test_city_country_population(self):
formatted_string = city_country('santiago', 'chile', 5000)
self.assertEqual(formatted_string, 'Santiago Chile 5000')
unittest.main()
########################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Process finished with exit code 0
####################################################################
11.2 测试类
11.2.1 各种断言方法
Python在unittest.TestCase
类中提供了很多断言方法。表中描述了6个常用的断言方法。使用这些方法可核实返回的值等于或不等于预期的值、返回的值为True
或False
、返回的值在列表中或不在列表中。你只能在继承unittest.TestCase
的类中使用这些方法。
方法 | 用途 |
---|---|
assertEqual(a, b) | 核实a == b |
assertNotEqual(a, b) | 核实a != b |
assertTrue(x) | 核实x为True |
assertFalse(x) | 核实x为False |
assertIn(item, list) | 核实item在list中 |
assertNotIn(item, list) | 核实item不在list中 |
"""11.2.2 一个要测试的类 """
"""survey.py"""
class AnonymousSurvey():
# 收集匿名调查问卷的答案
def __init__(self, question):
# 存储一个问题,并为存储答案做准备
self.question = question
self.response = []
def show_question(self):
# 显示调查问卷
print(self.question)
def store_response(self, new_question):
# 存储单份调查答卷
self.response.append(new_question)
def show_result(self):
# 显示收集到的所有答卷
print("Survey results: ")
for response in self.response:
print('-' + response)
###########################################################################
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("\nThank you to everyone who participated in the survey!")
my_survey.show_result()
##############################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
What language did you first learn to speak?
Enter 'q' at any time to quit.
Language: Chinese
Language: q
Thank you to everyone who participated in the survey!
Survey results:
-Chinese
Process finished with exit code 0
################################################################################
"""11.2.2 一个要测试的类 """
"""survey.py"""
class AnonymousSurvey():
# 收集匿名调查问卷的答案
def __init__(self, question):
# 存储一个问题,并为存储答案做准备
self.question = question
self.response = []
def show_question(self):
# 显示调查问卷
print(self.question)
def store_response(self, new_question):
# 存储单份调查答卷
self.response.append(new_question)
def show_result(self):
# 显示收集到的所有答卷
print("Survey results: ")
for response in self.response:
print('-' + response)
##########################################################################
"""11.2.3 测试 AnonymousSurvey 类 """
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
# 但只能收集一个答案的调查用途
def test_store_single_response(self):
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
# assertIn(item, list) 核实item在list中
self.assertIn('English', my_survey.response)
def test_store_three_responses(self):
"""Test that three individual responses are stored properly."""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'Spanish', 'Mandarin']
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response, my_survey.response)
unittest.main()
###################################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Process finished with exit code 0
#################################################################################
11.2.4 方法 setUp()
在前面的test_survey.py中,我们在每个测试方法中都创建了一个 AnonymousSurvey
实例,并在每个方法中都创建了答案。unittest.TestCase
类包含方法 setUp()
,让我们只需创建这些对象一次,并在每个测试方法中使用它们。如果你在 TestCase
类中包含了方法 setUp()
,Python将先运行它,再运行各个以test_打头的方法。这样,在你编写的每个测试方法中都可使用在方法 setUp()
中创建的对象了。
下面使用setUp()
来创建一个调查对象和一组答案,供方法test_store_single_response()
和test_store_three_responses()
使用:
"""11.2.2 一个要测试的类 """
"""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_question):
# 存储单份调查答卷
self.responses.append(new_question)
def show_result(self):
# 显示收集到的所有答卷
print("Survey results: ")
for response in self.responses:
print('-' + response)
#################################################################################
"""11.2.3 测试 AnonymousSurvey 类 """
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
# 方法setUp()
# 做了两件事情:创建一个调查对象;创建一个答案列表。
# 存储这两样东西的变量名包含前缀self(即存储在属性中),因此可在这个类的任何地方使用。
# 这让两个测试方法都更简单,因为它们都不用创建调查对象和答案
def setUp(self):
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English', 'Spanish', 'Mandarin']
# 但只能收集一个答案的调查用途
def test_store_single_response(self):
"""Test that a single response is stored properly."""
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0], self.my_survey.responses)
def test_store_three_responses(self):
"""Test that three individual responses are stored properly."""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
unittest.main()
##############################################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Process finished with exit code 0
##############################################################################
方法setUp()
做了两件事情:创建一个调查对象;创建一个答案列表。存储这两样东西的变量名包含前缀self
(即存储在属性中),因此可在这个类的任何地方使用。这让两个测试方法都更简单,因为它们都不用创建调查对象和答案。方法test_store_single_response()
核 实 self.responses
中 的 第 一 个 答 案 ——self.responses[0]
—— 被 妥 善 地 存 储 , 而 方 法test_store_three_response()
核实self.responses
中的全部三个答案都被妥善地存储。
再次运行test_survey.py时,这两个测试也都通过了。如果要扩展AnonymousSurvey
,使其允许每位用户输入多个答案,这些测试将很有用。修改代码以接受多个答案后,可运行这些测试,确认存储单个答案或一系列答案的行为未受影响。
测试自己编写的类时,方法setUp()
让测试方法编写起来更容易:可在setUp()
方法中创建一系列实例并设置它们的属性,再在测试方法中直接使用这些实例。相比于在每个测试方法中都创建实例并设置其属性,这要容易得多。
注意:
运行测试用例时,每完成一个单元测试,Python都打印一个字符:测试通过时打印一个句点;测试引发错误时打印一个E;测试导致断言失败时打印一个F。这就是你运行测试用例时,在输出的第一行中看到的句点和字符数量各不相同的原因。如果测试用例包含很多单元测试,需要运行很长时间,就可通过观察这些结果来获悉有多少个测试通过了。
class Employee():
def __init__(self, last_name, first_name, salary=1000):
self.last_name = last_name
self.first_name = first_name
self.salary = salary
def give_raise(self, added=5000):
self.salary += added
return added
###############################################################
import unittest
from Employee1 import Employee
class TestEmployeeRaise(unittest.TestCase):
def setUp(self):
self.test1 = Employee('Tmo', 'Smith')
self.test2 = Employee('Tmo', 'Smith',3000)
def test_give_default_raise(self):
self.salary1 = self.test1.give_raise()
self.assertEqual(str(self.salary1), '5000')
def test_give_custom_raise(self):
self.salary2 = self.test2.give_raise(3000)
self.assertEqual(str(self.salary2), '3000')
unittest.main()
############################################################
C:\Anaconda3\python.exe H:/python/venv/pizza.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Process finished with exit code 0
##############################################################333
11.3 小结
测试是很多初学者都不熟悉的主题。作为初学者,并非必须为你尝试的所有项目编写测试;但参与工作量较大的项目时,你应对自己编写的函数和类的重要行为进行测试。这样你就能够更加确定自己所做的工作不会破坏项目的其他部分,你就能够随心所欲地改进既有代码了。如果不小心破坏了原来的功能,你马上就会知道,从而能够轻松地修复问题。相比于等到不满意的用户报告bug后再采取措施,在测试未通过时采取措施要容易得多。
如果你在项目中包含了初步测试,其他程序员将更敬佩你,他们将能够更得心应手地尝试使用你编写的代码,也更愿意与你合作开发项目。如果你要跟其他程序员开发的项目共享代码,就必须证明你编写的代码通过了既有测试,通常还需要为你添加的新行为编写测试。
请通过多开展测试来熟悉代码测试过程。对于自己编写的函数和类,请编写针对其重要行为的测试,但在项目早期,不要试图去编写全覆盖的测试用例,除非有充分的理由这样做。