測試代碼
編寫函數和類時,還可以編寫測試函數,通過測試可以確定代碼面對各種輸入都能正常工作。在程式中添加新代碼時,也可以對其進行測試,確定他們不會破壞程式的既有程式。要經常測試模組。
通過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 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斷言方法用來核實得到的結果是否和期望的值一樣。
不能通過的測試
測試沒有通過,不要修改測試,而應修複導致測試不能通過的代碼:檢查剛對函數所做的修改,找出導致函數行為不符合預期的修改。
模組中的各種斷言方法
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中 |
方法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 (即儲存在屬性中),因此可在這個類的任何 地方使用。這讓兩個測試方法都更簡單,因為它們都不用建立調查對象和答案。
使用int() 來輸入數字
因為input()返回的資料類型是str(字串),python會把直接輸入的數字轉換成字串。str不能直接和整數比較,必須先把str轉換成整數。Python提供了int()函數來完成這件事情
height = input("How tall are you, in inches? ")
height = int(height) #轉化為整數
求模運算子
處理數值資訊時,求模運算子 (%)是一個很有用的工具,它將兩個數相除並返回餘數:
>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7 % 3
1
如果一個數可被另一個數整除,餘數就為0,因此求模運算子將返回0。你可利用這一點來判斷一個數是奇數還是偶數。