目录
第11章 测试代码
11.1 测试函数
11.1.1 单元测试和测试用例
11.1.2 可通过的测试
11.1.3 未通过的测试
11.1.4 测试未通过时怎么办
11.1.5 添加新测试
11.2 测试类
11.2.1 各种断言方法
11.2.2 一个要测试的类
11.2.3 测试AnonymousSurvey类
11.2.4 方法setUp()
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 last name: ")
if last == 'q':
break
formatted_name = get_formatted_name(first, last)
print(f"\tNeatly formatted name: {formatted_name}.")
Enter 'q' at any time to quit.
Please give me a first name: jack
Please give me last name: rose
Neatly formatted name: Jack Rose.
单元测试用于核实函数的某个方面没有问题。测试用例是一组单元测试,它们一道核实函数在各种情形下的行为都符合要求。全覆盖的测试用例包含一整套单元测试,涵盖了各种可能的函数使用方式。
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')
if __name__ == '__main__':
unittest.main()
============================= test session starts =============================
collecting ... collected 1 item
03.py::NamesTestCase::test_first_last_name PASSED [100%]
======================== 1 passed, 1 warning in 0.10s =========================
def get_formatted_name(first, middle, last):
"""生成整洁的姓名。"""
full_name = f"{first} {middle} {last}"
return full_name.title()
============================= test session starts =============================
collecting ... collected 1 item
03.py::NamesTestCase::test_first_last_name FAILED [100%]
03.py:9 (NamesTestCase.test_first_last_name)
self = <03.NamesTestCase testMethod=test_first_last_name>
def test_first_last_name(self):
"""能够正确地处理像Janis Joplin这样的姓名吗?"""
> formatted_name = get_formatted_name('janis', 'joplin')
E TypeError: get_formatted_name() missing 1 required positional argument: 'last'
03.py:12: TypeError
def get_formatted_name(first, last, middle=''):
"""生成整洁的姓名。"""
if middle:
full_name = f"{first} {middle} {last}"
else:
full_name = f"{first} {last}"
return full_name.title()
Testing started at 10:21 ...
Launching pytest with arguments D:/Projects/2022/202204/0419/03.py --no-header --no-summary -q in D:\Projects\2022\202204\0419
============================= test session starts =============================
collecting ... collected 1 item
03.py::NamesTestCase::test_first_last_name PASSED [100%]
======================== 1 passed, 1 warning in 0.02s =========================
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', 'amadaeus'
)
self.assertEqual(formatted_name, 'Wolfgang Amadaeus Mozart')
if __name__ == '__main__':
unittest.main()
============================= test session starts =============================
collecting ... collected 2 items
03.py::NamesTestCase::test_first_last_middle_name PASSED [ 50%]
03.py::NamesTestCase::test_first_last_name PASSED [100%]
======================== 2 passed, 1 warning in 0.01s =========================
断言方法检查你认为应该满足的条件是否确实满足。如果该条件确实满足,你对程序行为的假设就得到了确认,可以确信其中没有错误。如果你认为应该满足的条件实际上并不满足,Python将引发异常。
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_results(self):
"""显示收集到的所有答卷。"""
print('Survey results:')
for response in self.responses:
print(f"- {response}")
from survey import 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()
Enter 'q' at any time to quit.
Language: chinese
Language: french
Language: q
Thank you to everyone who participated in the survey!
Survey results:
- chinese
- french
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)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
if __name__ == "__main__":
unittest.main()
============================= test session starts =============================
collecting ... collected 1 item
test_survey.py::TestAnonymousSurvey::test_store_single_response PASSED [100%]
======================== 1 passed, 1 warning in 0.02s =========================
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)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
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)
if __name__ == "__main__":
unittest.main()
============================= test session starts =============================
collecting ... collected 2 items
test_survey.py::TestAnonymousSurvey::test_store_single_response PASSED [ 50%]
test_survey.py::TestAnonymousSurvey::test_store_three_responses PASSED [100%]
======================== 2 passed, 1 warning in 0.04s =========================
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_response(self):
"""测试三个答案会被妥善地存储。"""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response, self.my_survey.responses)
if "__name__" == '__main__':
unittest.main()
============================= test session starts =============================
collecting ... collected 2 items
test_survey.py::TestAnonymousSurvey::test_store_single_response PASSED [ 50%]
test_survey.py::TestAnonymousSurvey::test_store_three_response PASSED [100%]
======================== 2 passed, 1 warning in 0.01s =========================