Python中unittest用法實例
本文實例講述了Python中unittest的用法,分享給大家供大家參考。具體用法分析如下:
1. unittest module包含了編寫運行unittest的功能,自定義的test class都要集成unitest.TestCase類,test method要以test開頭,運行順序根據(jù)test method的名字排序,特殊方法:
① setup():每個測試函數(shù)運行前運行
② teardown():每個測試函數(shù)運行完后執(zhí)行
③ setUpClass():必須使用@classmethod 裝飾器,所有test運行前運行一次
④ tearDownClass():必須使用@classmethod裝飾器,所有test運行完后運行一次
2. 示例代碼:
#文件名runtest.py
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = list(range(10))
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, list(range(10)))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
3.運行方式:在命令行直接運行這個runtest.py
可以使用unitest.skip裝飾器族跳過test method或者test class,這些裝飾器包括:
① @unittest.skip(reason):無條件跳過測試,reason描述為什么跳過測試
② @unittest.skipif(conditition,reason):condititon為true時跳過測試
③ @unittest.skipunless(condition,reason):condition不是true時跳過測試
可以自定義skip decorator
#這是一個自定義的skip decorrator
def skipUnlessHasattr(obj, attr):
if hasattr(obj, attr):
return lambda func: func
return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))
skip decorator示例代碼:
class MyTestCase(unittest.TestCase):
@unittest.skip("demonstrating skipping")
def test_nothing(self):
self.fail("shouldn't happen")
@unittest.skipIf(mylib.__version__ < (1, 3),
"not supported in this library version")
def test_format(self):
# Tests that work for only a certain version of the library.
pass
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
def test_windows_support(self):
# windows specific testing code
pass
@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
def test_not_run(self):
pass
4.expected failure:使用@unittest.expectedFailure裝飾器,如果test失敗了,這個test不計入失敗的case數(shù)目
希望本文所述對大家Python程序設計的學習有所幫助。
相關文章
使用Python+Bright Data MCP實時抓取Google搜索結果完整教程
在 AI 應用和智能代理(Agent)的開發(fā)中,實時性數(shù)據(jù)往往是決定效果的關鍵,但傳統(tǒng)的網(wǎng)頁數(shù)據(jù)獲取方式存在明顯痛點,而 Bright Data 的 Web MCP Server正好可以解決這些問題,本文就給大家介紹了使用Python+Bright Data MCP實時抓取Google搜索結果完整教程2025-08-08
一個基于flask的web應用誕生 記錄用戶賬戶登錄狀態(tài)(6)
一個基于flask的web應用誕生第六篇,這篇文章主要介紹了記錄用戶賬戶登錄狀態(tài)功能開發(fā),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
python中enumerate函數(shù)遍歷元素用法分析
這篇文章主要介紹了python中enumerate函數(shù)遍歷元素用法,結合實例形式分析了enumerate函數(shù)遍歷元素的相關實現(xiàn)技巧,需要的朋友可以參考下2016-03-03
Python如何實現(xiàn)強制數(shù)據(jù)類型轉換
這篇文章主要介紹了Python如何實現(xiàn)強制數(shù)據(jù)類型轉換,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11

