#survey.py
#-*- coding:utf-8 -*-
#一个要测试的类
class AnonymousSurvey():
def __init__(self, question):
self.question = question
self.response = []
def show_question(self):
print(self.question)
def store_response(self, new_response):
self.response.append(new_response)
def show_results(self):
print("Survey results:")
for response in self.response:
print('- ' + response)
——————————————————
#language_survey.py
#-*- coding:utf-8 -*-
#导入测试类
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()
——————————————————
#test_survey.py
#-*- coding:utf-8 -*-
import unittest
from survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
#判断English是否被存储
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.response)
#判断多个答案是否被存储
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 responses:
my_survey.store_response(response)
for response in responses:
self.assertIn(response, my_survey.response)
unittest.main()
——————————————————