测试代码
编写函数或类时,还可为其编写测试。通过测试,可确定代码面对各种输入都能够按要求的那样工作。在本节中,你将学习如何使用Python模块unittest中的工具来测试代码。
- 测试函数
- 测试类
-------------------------------------------------------------------------------------
一、测试函数
下面是一个简单的函数,它接受名和姓并返回整洁的姓名:
name_function.py
[python] view plain copy
- def get_formatted_name(first, last):
- """Generate a neatly formatted full name."""
- full_name = first + ' ' + last
- return full_name.title()
我们来编写一个使用这个函数的程序。程序names.py 让用户输入名和姓,并显示整洁的全名:
names.py
[python] view plain copy
- 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("Please give me a last name: ")
- if last == 'q':
- break
- formatted_name = get_formatted_name(first, last)
- print("\tNeatly formatted name: " + formatted_name + '.')
这个程序从name_function.py 中导入get_formatted_name() 。用户可输入一系列的名和姓,并看到格式整洁的全名:
[python] view plain copy
- 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() 进行自动测试。
1. 单元测试和测试用例
Python标准库中的模块unittest提供了代码测试工具。单元测试用于核实函数的某个方面没有问题;测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。
2. 可通过的测试
下面是一个只包含一个方法的测试用例,它检查函数get_formatted_name() 在给定名和姓时能否正确地工作:
test_name_ function.py
[python] view plain copy
- 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.assertEqual(formatted_name, 'Janis Joplin')
- unittest.main()
首先,我们导入了模块unittest 和要测试的函数get_formatted_ name();接着,我们创建了一个名为NamesTestCase 的类,用于包含一系列针对get_formatted_name() 的单元测试。NamesTestCase只包含一个方法,用于测试get_formatted_name()的一个方面。在这个示例中,我们使用实参'janis' 和'joplin' 调用get_formatted_name() ,并将结果存储到变量formatted_name 中。
这里我们使用了unittest 类最有用的功能之一:一个断言方法。断言方法用来核实得到的结果是否与期望的结果一致。代码行self.assertEqual(formatted_name, 'Janis Joplin') 的意思是说:
“将formatted_name 的值同字符串'Janis Joplin' 进行比较,如果它们相等,就万事大吉,如果它们不相等,跟我说一声!
代码行unittest.main() 让Python 运行这个文件中的测试。运行test_name_function.py 时,得到的输出如下:
[python] view plain copy
- .
- ----------------------------------------------------------------------
- Ran 1 test in 0.000s
- OK
第1 行的句点表明有一个测试通过了。
3. 不能通过的测试
下面是函数get_formatted_name() 的新版本,它要求通过一个实参指定中间名:
name_ function.py
[python] view plain copy
- def get_formatted_name(first, middle, last):
- """生成整洁的姓名"""
- full_name = first + ' ' + middle + ' ' + last
- return full_name.title()
这个版本应该能够正确地处理包含中间名的姓名,但对其进行测试时,我们发现它再也不能正确地处理只有名和姓的姓名。这次运行程序test_name_function.py 时,输出如下:
[python] view plain copy
- E
- ======================================================================
- ERROR: test_first_last_name (__main__.NamesTestCase)
- ----------------------------------------------------------------------
- Traceback (most recent call last):
- File "test_name_function.py", line 8, 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.000s
- FAILED (errors=1)
第1 行输出只有一个字母E ,它指出测试用例中有一个单元测试导致了错误。接下来,我们看到NamesTestCase 中的test_first_last_name() 导致了错误。我们还看到了一个标准的traceback ,它指出函数调用get_formatted_name('janis', 'joplin') 有问题,因为它缺少一个必不可少的位置实参。
4. 测试不通过该怎么办
不要修改测试,而应修复导致测试不能通过的代码:检查刚对函数所做的修改,找出导致函数行为不符合预期的修改。
get_formatted_name()以前只需要两个实参——名和姓,但现在它要求提供名、中间名和姓。新增的中间名参数是必不可少的,这导致get_formatted_name()的行为不符合预期。就这里而言,最佳的选择是让中间名变为可选的。
name_function.py
[python] view plain copy
- def get_formatted_name(first, last, middle=''):
- """生成整洁的姓名"""
- if middle:
- full_name = first + ' ' + middle + ' ' + last
- else:
- full_name = first + ' ' + last
- return full_name.title()
现在,对于两种不同的姓名,这个函数都应该能够正确地处理。
我们再次运行test_name_function.py :
[python] view plain copy
- .
- ----------------------------------------------------------------------
- Ran 1 test in 0.000s
- OK
5. 添加新测试
我们再编写一个测试,用于测试包含 中间名的姓名。为此,我们在NamesTestCase 类中再添加一个方法:
[python] view plain copy
- 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.assertEqual(formatted_name, 'Janis Joplin')
- def test_first_last_middle_name(self):
- """能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?"""
- formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus')
- self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
- unittest.main()
我们将这个方法命名为test_first_last_middle_name() 。方法名必须以test_ 打头,这样它才会在我们运行test_name_function.py 时自动运行。这些方法由Python 自动调用,你根本不用编写调用它们的代码。
我们再次运行test_name_function.py 时,两个测试都通过了:
[python] view plain copy
- ..
- ----------------------------------------------------------------------
- Ran 2 tests in 0.000s
- OK
二、测试类
前半部分,你编写了针对单个函数的测试,下面来编写针对类的测试。
1. 各种断言方法
Python在unittest.TestCase类中提供了很多断言方法。
2. 一个要测试的类
一个帮助管理匿名调查的类:
survey.py
[python] view plain copy
- class AnonymousSurvey():
- """收集匿名调查问卷的答案"""
- def __init__(self, question):
- """存储一个问题,并为存储答案做准备"""
- self.question = question
- self.responses = []
- def show_question(self):
- """显示调查问卷"""
- print(question)
- def store_response(self, new_response):
- """存储单份调查答卷"""
- self.responses.append(new_response)
- def show_results(self):
- """显示收集到的所有答卷"""
- print("Survey results:")
- for response in responses:
- print('- ' + response)
为证明AnonymousSurvey 类能够正确地工作,我们来编写一个使用它的程序:
language_survey.py
[python] view plain copy
- 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_results()
这个程序定义了一个问题("What language did you first learn to speak? " ),并使用这个问题创建了一个AnonymousSurvey 对象。接下来,这个程序调用show_question() 来显示问题,并提示用户输入答案。收到每个答案的同时将其存储起来。用户输入所有答案(输入q 要求退出)后,调用show_results() 来打印调查结果:
[python] view plain copy
- What language did you first learn to speak?
- Enter 'q' at any time to quit.
- Language: English
- Language: Spanish
- Language: English
- Language: Mandarin
- Language: q
- Thank you to everyone who participated in the survey!
- Survey results:
- - English
- - Spanish
- - English
- - Mandarin
AnonymousSurvey类可用于进行简单的匿名调查。假设我们将它放在了模块survey中,并想进行改进:让每位用户都可输入多个答案;编写一个方法,它只列出不同的答案,并指出每个答案出现了多少次;再编写一个类,用于管理非匿名调查。进行上述修改存在风险,可能会影响AnonymousSurvey 类的当前行为。例如,允许每位用户输入多个答案时,可能不小心修改了处理单个答案的方式。要确认在开发这个模块时没有破坏既有行为,可以编写针对这个类的测试。
3. 测试AnonymousSurvey 类
test_survey.py
[python] view plain copy
- import unittest
- from survey import AnonymousSurvey
- class TestAnonmyousSurvey(unittest.TestCase):
- """针对AnonymousSurvey类的测试"""
- def test_store_single_response(self):
- """测试单个答案会被妥善地存储"""
- question = "What language did you first learn to speak?"
- my_survey = AnonymousSurvey(question)
- my_survey.store_response('English')
- self.assertIn('English', my_survey.responses)
- unittest.main()
第一个测试方法验证调查问题的单个答案被存储后,会包含在调查结果列表中。
self.assertIn('English', my_survey.responses)检查English 是否包含在列表my_survey.responses 中。
当我们运行test_survey.py 时,测试通过了:
[python] view plain copy
- .
- ----------------------------------------------------------------------
- Ran 1 test in 0.001s
- OK
这很好,但只能收集一个答案的调查用途不大。下面来核实用户提供三个答案时,它们也将被妥善地存储。为此,我们在TestAnonymousSurvey 中再添加一个方法:
[python] view plain copy
- import unittest
- from survey import AnonymousSurvey
- class TestAnonymousSurvey(unittest.TestCase):
- """针对AnonymousSurvey类的测试"""
- def test_store_single_response(self):
- """测试单个答案会被妥善地存储"""
- --snip--
- def test_store_three_responses(self):
- """测试三个答案会被妥善地存储"""
- 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.responses)
- unittest.main()
我们将这个方法命名为test_store_three_responses() ,并像test_store_single_response()一样,在其中创建一个调查对象。我们定义了一个包含三个不同答案的列表,再对其中每个答案都调用store_response() 。存储这些答案后,我们使用一个循环来确认每个答案都包含在my_survey.responses 中。
我们再次运行test_survey.py 时,两个测试(针对单个答案的测试和针对三个答案的测试)都通过了:
[python] view plain copy
- ..
- ----------------------------------------------------------------------
- Ran 2 tests in 0.000s
- OK
4. 方法setUp()
在前面的test_survey.py 中,我们在每个测试方法中都创建了一个AnonymousSurvey 实例,并在每个方法中都创建了答案。unittest.TestCase 类包含方法setUp() ,让我们只需创建这些对象一次,并在每个测试方法中使用它们。
下面使用setUp() 来创建一个调查对象和一组答案,供方法test_store_single_response() 和test_store_three_responses() 使用:
[python] view plain copy
- import unittest
- from survey import AnonymousSurvey
- class TestAnonymousSurvey(unittest.TestCase):
- """针对AnonymousSurvey类的测试"""
- 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):
- """测试单个答案会被妥善地存储"""
- self.my_survey.store_response(self.responses[0])
- self.assertIn(self.responses[0], self.my_survey.responses)
- def test_store_three_responses(self):
- """测试三个答案会被妥善地存储"""
- 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()
方法setUp() 做了两件事情:创建一个调查对象;创建一个答案列表。存储这两样东西的变量名包含前缀self(即存储在属性中),因此可在这个类的任何地方使用。这让两个测试方法都更简单,因为它们都不用创建调查对象和答案。方法test_store_three_response()核实self.responses 中的第一个答案——self.responses[0]—— 被妥善地存储, 而方法test_store_three_response() 核实self.responses 中的全部三个答案都被妥善地存储。再次运行test_survey.py 时,这两个测试也都通过了。