第 11 章 测试代码
>>> from name_function import get_formatted_name
>>> print("Enter 'q' at any time to quit.")
Enter 'q' at any time to quit.
>>> while True:
... first = input("\nPlease give me a first name: ")
... if first == 'q':
... break
... last = input("\nPlease give me a last name: ")
... if last == 'q':
... break
... formatted_name = get_formatted_name(first,last)
... print("\tNeatly formatted name: " + formatted_name + '.')
...
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
>>>
1 class AnonymousSurvey():
2 """收集匿名调查问卷的答案"""
3
4 def __init__(self, question):
5 """存储一个问题,并为存储答案做准备"""
6 self.question = question
7 self.responses = []
8
9 def show_question(self):
10 """显示调查问卷"""
11 print(question)
12
13 def store_response(self, new_response):
14 """存储单份调查答卷"""
15 self.responses.append(new_response)
16
17 def show_results(self):
18 """显示收集到的所有答卷"""
19 print("Survey results:")
20 for response in responses:
21 print('- ' + response)
1 from survey import AnonymousSurvey
2
3 #定义一个问题,并创建一个表示调查的AnonymousSurvey对象
4 question = "What language did you first learn to speak?"
5 my_survey = AnonymousSurvey(question)
6
7 #显示问题并储存答案
8 my_survey.show_question()
9 print("Enter 'q' at any time to quit.\n")
10 while True:
11 response = input("Language: ")
12 if response == 'q':
13 break
14 my_survey.store_response(response)
15 #显示调查结果
16 print("\nThank you to everyone who participated in the survey!")
17 my_survey.show_results()
1 import unittest
2 from survey import AnonymousSurvey
3
4 class TestAnonymousSurvey(unittest.TestCase):
5 """针对AnonymousSurvey类的测试"""
6 def test_store_single_response(self):
7 """测试单个答案会被妥善地存储"""
8 question = "What language did you first learn to speak?"
9 my_survey = AnonymousSurvey(question)
10 my_survey.store_response('English')
11 self.assertIn('English', my_survey.response)
12
13 unittest.main()
1 import unittest
2 from survey import AnonymousSurvey
3
4 class TestAnonymousSurvey(unittest.TestCase):
5 """针对AnonymousSurvey类的测试"""
6 def test_store_single_response(self):
7 """测试单个答案会被妥善地存储"""
8 question = "What language did you first learn to speak?"
9 my_survey = AnonymousSurvey(question)
10 my_survey.store_response('English')
11 self.assertIn('English', my_survey.response)
12
13 def test_store_three_responses(self):
14 """测试三个答案会被妥善地存储"""
15 question = "What language did you first learn to speak?"
16 my_survey = AnonymousSurvey(question)
17 responses = ['English', 'Spanish', 'Mandarin']
18 for response in responses:
19 my_survey.store_response(response)
20
21 for response in responses:
22 self.assertIn(response, my_survey.responses)
23
24 unittest.main()