Python基礎學習總結(九)

來源:互聯網
上載者:User

標籤:strong   ==   程式編寫   基礎學習   inpu   return   please   quit   enter   

11測試代碼

  編寫函數和類時,還可以編寫測試函數,通過測試可以確定代碼面對各種輸入都能正常工作。在程式中添加新代碼時,也可以對其進行測試,確定他們不會破壞程式的既有程式。要經常測試模組。

  通過python的模組unittest中的工具來測試代碼。將明白測試通過是怎麼樣的,未通過是什麼樣的,知道未通過測試怎麼來改善代碼,知道要為項目編寫多少測試。知道怎麼測試函數和類。

  在程式運行過程中,總會遇到各種各樣的錯誤。有的錯誤是程式編寫有問題造成的,比如本來應該輸出整數結果輸出了字串,這種錯誤我們通常稱之為bug,bug是必須修複的。

11.1測試函數11.1.1單元測試和測試案例

  Python中的unittest模組提供代碼測試載入器,單元測試用來核實函數某個方面沒有問題。測試案例是一組單元測試,確保函數在各個方面都沒有問題。

  全覆蓋式測試案例包含一整套的測試案例,涵蓋了各種可能的函數使用方式。

11.1.2可通過測試

  要為函數編寫測試函數,先匯入模組unittest和要測試的涵數,在建立一個繼承unittest.TestCase的類,並編寫一系列方法對函數行為的不同方面進行測試。命名最好帶有test。

  name_function.py

def get_formatted_name(first, last):   

"""獲得全名."""   

full_name = first + ‘ ‘ + last   

return full_name.title()

  names.py

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 + ‘.‘)

  test_name_function.py

import unittest 

from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):     

"""測試name_function.py"""     

def test_first_last_name(self):         

"""能夠正確地處理像Janis Joplin這樣的姓名嗎?"""          

formatted_name = get_formatted_name(‘janis‘, ‘joplin‘)          self.assertEqual(formatted_name, ‘Janis Joplin‘) 

unittest.main()

  unittest最有用的功能之一:一個斷言方法,assertEqual斷言方法用來核實得到的結果是否和期望的值一樣。

11.1.3不能通過的測試

  測試沒有通過,不要修改測試,而應修複導致測試不能通過的代碼:檢查剛對函數所做的修改,找出導致函數行為不符合預期的修改。

11.2.1模組中的各種斷言方法

  6個常見斷言

方法

用途

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方法setUp()

  unittest.TestCase 類包含方法setUp() ,讓我們只需建立一次對象,並可以在每個測試方法中使用它們。

  survey.py

class AnonymousSurvey():     

"""收集匿名調查問卷的答案"""

        def __init__(self, question):        

        """儲存一個問題,並為儲存答案做準備"""        

            self.question = question         

self.responses = []

        def show_question(self):         

"""顯示調查問卷"""        

            print(question)    

def store_response(self, new_response):        

        """儲存單份調查答卷"""         

self.responses.append(new_response)  

def show_results(self):        

        """顯示收集到的所有答卷"""        

            print("Survey results:")         

for response in responses:          

            print(‘- ‘ + response)

  language_survey.py

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()

  test_survey.py

import unittest 

from survey import AnonymousSurvey 

class TestAnonymousSurvey(unittest.TestCase):     

"""針對AnonymousSurvey類的測試"""     

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()

  方法setUp() 做了兩件事情:建立一個調查對象;建立一個答案列表。儲存這兩樣東西的變數名包含首碼self (即儲存在屬性中),因此可在這個類的任何 地方使用。這讓兩個測試方法都更簡單,因為它們都不用建立調查對象和答案。

Python基礎學習總結(九)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.