python学习10:测试代码
1 测试函数
python标准库中的模块unittest提供了代码测试工具。
单元测试用于核实函数的某个方面没有问题。测试用例是一组单元测试,核实各种情形。
要测试的代码:
def get_formatted_name(first, last):
"""generate neat names"""
full_name = f"{first} {last}"
return full_name.title()
测试代码:
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""test name_function.py"""
def test_first_last_name(self):
"""can you handle names like liu yang correctly"""
formatted_name = get_formatted_name('liu', 'yang')
self.assertEqual(formatted_name, 'Liu Yang')
if __name__ == '__main__':
unittest.main()
- 先导入模块
unittest
和要测试的函数,再创建一个继承unittest.TestCase
的类,并编写一系列方法对函数行为的不同进行测试。 - 该类中包含一个方法,用于测试
get_formatted_name
的一个方面,方法命名为test_first_last_name()
,因为所有开头为test_
的方法都会自动运行 - 使用了unittest类最有用的功能之一:断言方法。核实得到的结果是否与期望的结果一致
- 测试未通过时,不要修改测试,而应该修复导致测试不能通过的代码。
2 测试类
2.1 各种断言方法
使用下述方法可核实返回值等或不等于预期值,返回值为True或False,以及返回的值是否在列表中,且只能再继承unittest.TestCase
的类中使用这些方法。
方法 | 用途 |
---|---|
assertEqual(a,b) | 核实a==b |
assertNotEqual(a,b) | 核实a!=b |
assertTrue(a,b) | 核实x为True |
assertFalse(x) | 核实x为False |
assertIn(item,list) | 核实item在list中 |
assertNotIn(item,list) | 核实item不在list中 |
2.2 一个要测试的类
类如下:
class AnonymousSurvey:
"""collect answers to anonymous questionnaires"""
def __init__(self, question):
"""store q question and prepare for storing answers"""
self.question = question
self.responses = []
def show_question(self):
"""show questionnaire"""
print(self.question)
def store_response(self, new_response):
"""store a single questionnaire"""
self.responses.append(new_response)
def show_results(self):
"""display all questionnaires collected"""
print("Survey results:")
for response in self.responses:
print(f"- {response}")
2.3 测试类
核实用户提供一个或三个答案时可以被妥善存储。
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
"""test for AnonymousSurvey class"""
def test_store_single_response(self):
"""the single answers to the test will be stored properly"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
def test_store_three_response(self):
"""three answers to the test will be stored properly"""
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
responses = ['English', 'spanlish', 'chinese']
for response in responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response, my_survey.responses)
if __name__ == '__main__':
unittest.main()
2.4 方法setUp()
unittest.TestCase
类包含的方法setUp()
让我们只需创建这些对象一次,就能在每个测试方法中使用。- 如果在
TestCase
类中包含了方法setUp()
,python将先运行它,再运行各个以test_打头的方法。