美文网首页
【Python】11 测试代码

【Python】11 测试代码

作者: 吃葡萄的小兔纸 | 来源:发表于2019-08-27 23:46 被阅读0次

    前言:用unittest模块工具来测试代码。

    11.1 测试函数

    def get_formatted_name(first,last):
        """生成整洁的姓名"""
        full_name = first + ' ' + last
        return full_name.title()
    
    from name_function import get_formatted_name
    print("enter 'q' at any time to quit.")
    while True:
        first = input("\nplease give me a first name: ")
        if first == 'q':
            break
        last = input("please give me a last name: ")
        if last == 'q':
            break
    
        formatted_name = get_formatted_name(first,last)
        print("\tneatly formatted name: " + formatted_name + '.')
    

    11.1.1 单元测试和测试用例

    标准库模块unittest提供代码测试工具。
    单元测试用于核实函数的某个方面没有问题;测试用例是一组单元测试,核实某种情形下函数的有效性;全覆盖式测试用例包含一整套单元测试,涵盖了各种可能的函数使用方式。

    11.1.2 可通过的测试

    先导入unittest以及要测试的函数,再创建一个继承unittest.TestCase的类,并编写一系列方法对函数行为的不同方面进行测试。

    import unittest  #导入模块
    from name_function import get_formatted_name # 导入函数
    
    class NameTestCase(unittest.TestCase): #创建类,包含单元测试,必须继承unittest.TestCase
        def test_first_last_name(self):
            formatted_name = get_formatted_name('janis','joplin')
            self.assertEqual(formatted_name,'janis Joplin') #断言方法,用来核实得到的结果时否与预期的一致
    
    unittest.main()
    
    测试通过.png

    11.1.3 不能通过的测试

    测试未通过.png

    11.1.4 测试未通过时怎么办

    不要修改测试,而应修复导致测试不能通过的代码,检查对函数所做的修改

    11.1.5 添加新测试

    import unittest
    from name_function import get_formatted_name
    
    class NameTestCase(unittest.TestCase):
        def test_first_last_name(self):
            formatted_name = get_formatted_name('janis','joplin')
            self.assertEqual(formatted_name,'Janis Joplin')
    
        def test_first_last_middle_name(self):
            formatted_name = get_formatted_name('wolfgang','mozart','amadeus')
            self.assertEqual(formatted_name,"Wolfgang Amadeus Mozart")
            
    unittest.main()
    
    多个测试通过.png

    11.2 测试类

    11.2.1 各种断言方法

    • assertEqual(a,b) ---> 核实a == b
    • assertNotEqual(a,b) ---> 核实a != b
    • assertTrue(x) ---> 核实x为true
    • assertFalse(x) ---> 核实x为false
    • assertIn(item, list)--->核实item在list中
    • assertNotIn(item, list)--->核实item不在list中

    11.2.2 一个要测试的类

    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("- " + response)
    
    from survey import AnonymousSurvey
    
    #定义一个问题,并创建一个表示调查的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()
    

    what language did you first learn to speak?
    enter 'q' at any time to quit.

    language: English
    language: japanese
    language: chinese
    language: French
    language: q

    thank you to everyone who participated in the survey!
    Survey results:
    -English
    -japanese
    -chinese
    -French

    11.2.3 测试AnonymousSurvey类

    import unittest
    from survey import AnonymousSurvey
    
    class TestAnonymousSurvey(unittest.TestCase):
    """针对anonymoussurvey类的测试"""
    
        def test_store_single_response(self):
            """测试的单个答案会被妥善的 存储"""
            question = "what language did you first learn to speak?"
            my_survey = AnonymousSurvey(question)
            my_survey.store_response('English')
    
        def test_store_three_responses(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.responses)
            
    unittest.main()
    
    测试类.png

    11.1.4 方法setUp()

    只需创建一次对象,在每个测试方法中使用。

    import unittest
    from survey import AnonymousSurvey
    
    class TestAnonymousSurvey(unittest.TestCase):
    
        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()
    
    测试类.png

    相关文章

      网友评论

          本文标题:【Python】11 测试代码

          本文链接:https://www.haomeiwen.com/subject/ncoyectx.html