测试类及方法
!/usr/bin/env python
coding:utf-8
class AnonymousSurvey():
#收集匿名调查的答案
'''
要创建这个类的实例,只需提供一个问题即可。有
了表示调查的实例后,就可使用show_question()
来显示其中的问题,可使用store_response()
来存储答案,并使用show_results()
来显示调查结果。
'''
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 ('-'+response)
"""
AnonymousSurvey类可用于进行简单的匿名调查。假设我们将它放在了模块survey中,并想进 行改进:
让每位用户都可输入多个答案;
编写一个方法,它只列出不同的答案,并指出每个答案 出现了多少次;
再编写一个类,用于管理非匿名调查。 13进行上述修改存在风险,可能会影响AnonymousSurvey类的当前行为。
例如,允许每位用户输 入多个答案时,可能不小心修改了处理单个答案的方式。
要确认在开发这个模块时没有破坏既有 行为,可以编写针对这个类的测试。
"""
print (AnonymousSurvey('What id ?'))
!/usr/bin/env python
coding:utf-8
from survey import AnonymousSurvey
定义一个问题,并创建一个表示调查的AnonymousSurvey对象
question = 'What language did you first learn to speak?'
my_survey = AnonymousSurvey(question) #创建实例my_survey
显示问题并存储答案
my_survey.show_question()
print ("\nEnter 'q' any time to quit ")
while True:
response = raw_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()
!/usr/bin/env python
coding:utf-8
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
#针对AnonymousSurveyde测试
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):
#测试单个答案会被妥善的存储
# question = 'What language did you first learn to speak?'
# my_survey = AnonymousSurvey(question)
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0],self.my_survey.responses)
def test_store_three_response(self):
# question = 'What language did you first learn to speak?'
# my_survey = AnonymousSurvey(question)
# responses = ['English','Spanish','Mandarin']
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response,self.my_survey.responses)
def runTest(self):
pass
勤學如春起之苗,不見其增,日有所長。綴學如磨刀之石,不見其損,日有所虧。