1. 程式人生 > >Python基礎學習總結(九)

Python基礎學習總結(九)

nbsp you ons quest border lease sta 不能 lang

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基礎學習總結(九)