zoukankan      html  css  js  c++  java
  • python基础(十)

    测试代码

    使用python模块unittest中的工具来测试代码,如何测试函数和类

     
    #测试函数
    #
    name_function.py 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("
    please 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("	name: " + formatted_name + '.')
      File "<ipython-input-6-cffaabe8f05a>", line 4
        first = input("
    please give me a first name:")
        ^
    IndentationError: unexpected indent
    
    
    
     
    '''
    enter 'q' at any time to quit.
    please give me a first name:peng
    please give me a last name:yuyan
        name: Peng Yuyan.
    please give me a first name:
    '''
     
    #单元测试和测试用例
    #单元测试用于核实函数的某个方面没有问题;测试用例是一组单元测试,这些单元测试一起核实函数在各种情形下的行为都符合要求。全覆盖式测试包含一整套单元测试,涵盖了各种可能的函数使用方式。
    #可通过的测试
    #test_name_function.py
    
    import unittest
    
    from name_function import get_formatted_name
    
    ​
    
    class NamesTestCase(unittest.TestCase):
    
        def test_first_last_name(self):
    
            formatted_name = get_formatted_name('janis','joplin')
    
            self.assertEqual(formatted_name, 'Janis Joplin')
    
    unittest.main()
     
    '''
    ----------------------------------------------------------------------
    Ran 1 test in 0.023s
    OK
    '''
     
    #不能通过的测试
    
    def get_formatted_name(first, middle, last):
    
        full_name = first + ' ' + middle + ' ' +last
    
        return full_name.title()
     
    '''
    E
    ======================================================================
    ERROR: test_first_last_name (__main__.NamesTestCase)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "D:/02-1python/2019.10.3-入门基础/20200630-从入门到实践/7.13-11/test_name_function.py", line 7, in test_first_last_name
        formatted_name = get_formatted_name('janis','joplin')
    TypeError: get_formatted_name() missing 1 required positional argument: 'last'
    ----------------------------------------------------------------------
    Ran 1 test in 0.049s
    FAILED (errors=1)
    '''
     
    #测试未通过时怎么办
    
    def get_formatted_name(first, last, middle = ''):
    
        if middle:
    
            full_name = first + ' ' + middle + ' ' +last
    
        else:
    
            full_name = first + ' ' +last
    
        return full_name.title()
     
    '''
    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.046s
    OK
    '''
     
    #添加新测试
    
    import unittest
    
    from name_function import get_formatted_name
    
    ​
    
    class NamesTestCase(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()
     
    '''
    ..
    ----------------------------------------------------------------------
    Ran 2 tests in 0.045s
    OK
    '''
     
    #测试类
    
    #各种断言方法
    
    #survey.py
    
    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)
     
    #language_survey.py
    
    from survey import AnonymousSurvey
    
    ​
    
    question = "What language do you first learn to speak?"
    
    my_survey = AnonymousSurvey(question)
    
    ​
    
    my_survey.show_question()
    
    print("Enter 'q' at any time to quit.")
    
    while True:
    
        response = input("Language: ")
    
        if response == 'q':
    
            break
    
        my_survey.store_response(response)
    
    ​
    
    print("
    Thank you to everyone who participated in the survey!")
    
    my_survey.show_results()
     
    '''
    What language do you first learn to speak?
    Enter 'q' at any time to quit.
    Language: Chinese
    Language: English
    Language: French
    Language: q
    Thank you to everyone who participated in the survey!
    Survey results:
    - Chinese
    - English
    - French
    '''
     
    #测试AnonymousSurvey类
    
    #test_survey
    
    import unittest
    
    from survey import AnonymousSurvey
    
    ​
    
    class TestAnonymousSurvey(unittest.TestCase):
    
        """Tests for the class AnonymousSurvey"""
    
        def setUp(self):
    
            """
    
            Create a survey and a set of responses for use in all test methods.
    
            """
    
            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):
    
            """Test that a single response is stored properly."""
    
            self.my_survey.store_response(self.responses[0])
    
            self.assertIn(self.responses[0], self.my_survey.responses)
    
    ​
    
        def test_store_three_responses(self):
    
            """Test that three individual responses are stored properly."""
    
            for response in self.responses:
    
                self.my_survey.store_response(response)
    
            for response in self.responses:
    
                self.assertIn(response, self.my_survey.responses)
    
    ​
    
    if __name__ == '__main__':
    
        unittest.main()
     
    '''
    collecting ... collected 2 items
    test_survey.py::TestAnonymousSurvey::test_store_single_response PASSED   [ 50%]
    test_survey.py::TestAnonymousSurvey::test_store_three_responses PASSED   [100%]
    ========================== 2 passed in 0.02 seconds ===========================
    '''
  • 相关阅读:
    借助magicwindow sdk plugin快速集成sdk
    Deeplink做不出效果,那是你不会玩!
    iOS/Android 浏览器(h5)及微信中唤起本地APP
    C#回顾 Ado.Net C#连接数据库进行增、删、改、查
    C# 文件操作(全部) 追加、拷贝、删除、移动文件、创建目录 修改文件名、文件夹名
    C#中的静态方法|如何调用静态方法
    SpringBoot实体类对象和json格式的转化
    SpringBoot + kaptcha 生成、校对 验证码
    SpringBoot配置自定义美化Swagger2
    Spring Boot关于layui的通用返回类
  • 原文地址:https://www.cnblogs.com/Cookie-Jing/p/13507514.html
Copyright © 2011-2022 走看看