首頁  >  文章  >  後端開發  >  Python基礎匯總

Python基礎匯總

巴扎黑
巴扎黑原創
2017-07-17 15:56:281740瀏覽

測試程式碼

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

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

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

測試函數

單元測試和測試案例

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

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

可透過測試

  要為函數編寫測試函數,先導入模組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 真:   

first = input("\nPlease give me a first name: ")   

if first == '  

break   

last = input("Please give me a last name: ")   

if last == 'q':      #  #formatted_name = get_formatted_name(first, last)   

print("\tNeatly formatted name: " + formatted_name + '.')

import unittest #class NamesTestCase(unittest.TestCase> ):     """測試name_function.py"""     不能通過的測試  測試沒有通過,不要修改測試,而應修復導致測試不能通過的程式碼:檢查剛對函數所做的修改,找出導致函數行為不符合預期的修改。   6個常見斷言方法assertEqual(a, b)

#' ##  test_name_function.py

from name_function import get_formatted_name

def test_first_last_name(self):      ## ?

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

模組中的各種斷言方法

##用途

######核實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中################################################################################################################# ########

 

方法setUp()

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

  survey.py

#question = "What language did you first learn to speak?"

#class AnonymousSurvey():     

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

        def __init__(self, question):        

              self. question = question         

#self.responses = []

        def

#question(self): 

#            print( question)    

def store_response(self, new_response):        

#       )  

def show_results(self):        

        """顯示收集到的所有答案「""               

for response in responses:          

o 和

##from survey import AnonymousSurvey

##定義一個問題,並建立一個表示調查的AnonymousSurvey物件

#question = "What language did you first learn to物件

#question = "What language did you first learn to物件
my_survey = AnonymousSurvey(question)

#顯示問題並儲存答案my_survey.show_question()

print("Enter 'q' at any time to quit .\n")while 真:   
response = input("Language: ")   

if response == 'q':     

##if response == 'q':     

##if response == 'q':     #"

break

break#break

#break#break#"

my_survey.store_response(response)

 # 顯示調查結果

print("\nThank you to everyone who participated in the survey!")

############################################################################################################################################################# my_survey.show_results()###############

  test_survey.py

使用int() 來輸入數字  因為input()回傳的資料型別是str(字串),python會把直接輸入的數字轉換成字串。 str不能直接和整數比較,必須先把str轉換成整數。 Python提供了int()函數來完成這件事

import unittest 

from survey import AnonymousSurvey 

#class TestAnonymousSurvey (unittest.TestCase):     

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

#def setUp(self):      

#def setUp(self):    組答案,供使用的測試方法使用"""         

question = "What language did you first learn to speak?"       

#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) test.    

"""測試三個答案會被妥善儲存"""         

for response in self.responses:           

for response in self.responses:             

self.assertIn(response, self.my_survey.responses) 

##unittest.main(

unittest.main(

  方法setUp()

做了兩件事:建立一個調查物件;建立一個答案清單。

儲存這兩樣東西的變數名稱包含前綴self (即儲存在屬性中),因此可在這個類別的任何 地方使用。這讓兩個測試方法都更簡單,因為它們都不需要建立調查對象和答案。

height = input("How tall are you, in inches? ")

height = int(height) #轉換為整數

   


#求模運算子

#  處理數值資訊時,求模運算子(%)是一個很有用的工具,它將兩個數相除並傳回餘數:


>>> 4 % 3

1 >>> 5 % 3#2

>>> 6 % 3

#0

#>>> 6 % 3

#0

>>> 7 % 3

 1

若一個數可被另一個數整除,餘數就為0,因此求模運算子將會回傳0。你可利用這一點來判斷一個數是奇數還是偶數。

以上是Python基礎匯總的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn