anonymousSurvey.py
class AnonymousSurvey(): """收集匿名调查问卷的答案""" def __init__(self, question): """存储一个问题,并为存储答案做准备""" self.question = question self.responses = [] def show_question(self): """显示调查问卷""" print(self.responses) def store_response(self, new_response): """存储单份调查答卷""" self.responses.append(new_response) def show_results(self): """显示收集到的所有答卷""" print("Survey results:") for response in self.responses: print('- ' + response)
getFormattedName.py
def get_formatted_name(firstname, lastname, middle=''): if middle: full_name = firstname + ' ' + middle + ' ' + lastname else: full_name = firstname + ' ' + lastname return full_name.title()
09.test.py
import unittest from getFormattedName import get_formatted_name from anonymousSurvey import AnonymousSurvey class NameTestCase(unittest.TestCase): """测试""" def test_pizza(self): """能够正确地处理像Janis Joplin这样的姓名吗?""" full_name = get_formatted_name('Janis', 'Joplin') self.assertEqual(full_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') # question = "What language did you first learn to speak?" # my_surver = AnonymousSurvey(question) # my_surver.show_question() # print("Enter 'q' at any time to quit.\n") # while True: # response = input("language:") # if response == 'q': # break # my_surver.store_response(response) # my_surver.show_results() class TestAnormyousSurvey(unittest.TestCase): """针对AnonymousSurvey类的测试""" def test_store_singke_response(self): """测试单个答案会被妥善地存储""" question = "What language did you first learn to speak?" my_surver = AnonymousSurvey(question) my_surver.store_response('English') self.assertIn('English', my_surver.responses) def test_store_three_response(self): """测试单个答案会被妥善地存储""" question = "What language did you first learn to speak?" my_surver = AnonymousSurvey(question) responses = ['English', 'Spanish', 'Mandarin'] for response in responses: my_surver.store_response(response) for response in responses: self.assertIn(response, my_surver.responses) # setUp() 来创建一个调查对象和一组答案, # 供方法test_store_single_response() 和test_store_three_responses() 使用 class TestAnonymousSurveyUseSetUp(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()