【Python】11 測試代碼

前言:用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以及要測試的函數,再創(chuàng)建一個繼承unittest.TestCase的類,并編寫一系列方法對函數行為的不同方面進行測試。

import unittest  #導入模塊
from name_function import get_formatted_name # 導入函數

class NameTestCase(unittest.TestCase): #創(chuàng)建類,包含單元測試,必須繼承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():  
"""創(chuàng)建一個類,收集匿名調查問卷的答案"""

    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

#定義一個問題,并創(chuàng)建一個表示調查的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()

只需創(chuàng)建一次對象,在每個測試方法中使用。

import unittest
from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase):

    def setUp(self):
        """創(chuàng)建一個調查對象和一組答案,供使用的測試方法使用"""
        question =  "what language did you first learn to speak?" 
        self.my_survey = AnonymousSurvey(question) #創(chuàng)建調查對象
        self. responses = ['english','spanish','mandarin']#創(chuàng)建答案列表
        """存儲在屬性中,因此可在類的任何地方使用"""

    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
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容