python 測試代碼
阿新 • • 發佈:2018-04-22
() false bubuko 測試方法 esp unit resp first self
編寫函數或者類時進行測試,確保代碼正常工作
python模塊unittest 提供了代碼測試工具。
單元測試用於核實函數的某個方面沒有問題;
測試用例是一組單元測試,這些單元測試一起核實函數在各種情況選的行為都符合要求
# Author:song import unittest class TestString(unittest.TestCase): def test_upper(self): self.assertEqual(‘Foo‘.upper(),‘FOO‘) def test_isupper(self): self.assertTrue(‘FOO‘.isupper()) self.assertFalse(‘Foo‘.isupper()) def test_split(self): s= ‘hello world‘ self.assertEqual(s.split(),[‘hello‘,‘world‘]) with self.assertRaises(TypeError): s.split(2) if __name__=="__main__": unittest.main()
unittest.main():使用它可以將一個單元測試模塊變為可直接運行的測試腳本,main()方法使用TestLoader類來搜索所有包含在該模塊中以“test”命名開頭的測試方法,並自動執行
Python在unittest.TestCase類中提供了很多斷言方法
常見幾個
unittest.TestCase類包含方法setUp(),讓我們只需創建這些對象一 次,並在每個測試方法中使用它們。
AnonymousSurvey.py
class AnonymousSurvey():#創建匿名調查的類 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 result:‘) for response in self.responses: print(‘-‘+response)
測試代碼,
import unittest class TestAnonymousSurvey(unittest.TestCase): 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(即存儲在屬性中),因此可在這個類的任何地方使用。這讓兩個測試方法都更簡單,因為它們都不用創建調查對象和答案。方法setUp()讓測試方法編寫起來更容易,相比於在每個測試方法中都創 建實例並設置其屬性,這要容易得多。
運行結果
.. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK
運行測試用例時,每完成一個單元測試,Python都打印一個字符:測試通過時打印一個 句點;測試引發錯誤時打印一個E;測試導致斷言失敗時打印一個F。這就是你運行測試 用例時,在輸出的第一行中看到的句點和字符數量各不相同的原因。如果測試用例包含 很多單元測試,需要運行很長時間,就可通過觀察這些結果來獲悉有多少個測試通過了
python 測試代碼