Python匿名调查并测试类(unittest)

Python匿名调查并测试类(unittest),第1张

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.title()}")
#一个调查实例调查母语
question='What is your mother tongue?'
my_survey=AnonymousSurvey(question)
my_survey.show_question()
print("Enter 'q' to quit.\n")
while True:
    response=input("Language: ")
    if response=='q':
        break
    my_survey.store_response(response)
print("\nThank you for everyone who participated in the survey!")
my_survey.show_results()
#测试类
import unittest
class TestAnonymousSurvey(unittest.TestCase):
    def test_store_single_response(self):
    #检测单个答案能否被妥善保存
        question="What is your mother tongue?"
        my_survey=AnonymousSurvey(question)
        my_survey.store_response('English')
        self.assertIn('English',my_survey.responses)
    def test_store_three_responses(self):
        #测试多个答案能否被妥善保存
        question="What is your mother tongue?"
        my_survey=AnonymousSurvey(question)
        responses=['english','spanish','chinese']
        for response in responses:
            my_survey.store_response(response)
        for response in responses:
            self.assertIn(response,my_survey.responses)
if __name__=='__main__':#在这里可以省略这个判断
    unittest.main()
#使用setUp方法简化测试
class TestAnonymousSurvey(unittest.TestCase):
    def setUp(self):#setUp中包含的内容可被测试中的任何方法使用
    #创建一个调查对象和一组答案
      question="What is your mother tongue?"
      self.my_survey=AnonymousSurvey(question)
      self.responses=['english','spanish','chinese']
    def test_store_single_response(self):
        self.my_survey.store_response(self.response[0])
        self.assertIn(self.response[0],self.my_survey.responses)#(self.my_survey).responses. 是 AnonymousSurvey中的self.responses,与下面的self.responses的意思不一样
        for response in self.responses:#self.responses的意思是setUp方法中的一组答案。在55行
            self.my_survey.store_response(response)
        for response in self.responses:
            self.assertIn(response,self.my_survey.responses)
if __name__=='__main__':#在这里可以省略这个判断
    unittest.main()
What is your mother tongue?
Enter 'q' to quit.

Language: chinese
Language: english
Language: french
Language: spanish
Language: q

Thank you for everyone who participated in the survey!
Survey results:
-Chinese
-English
-French
-Spanish
..
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK
>>> 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/943250.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-18
下一篇 2022-05-18

发表评论

登录后才能评论

评论列表(0条)

保存