Python基于Hypothesis測試庫生成測試數據
Hypothesis是Python的一個高級測試庫。它允許編寫測試用例時參數化,然后生成使測試失敗的簡單易懂的測試數據。可以用更少的工作在代碼中發現更多的bug。
安裝
pip install hypothesis
如何設計測試數據
通過介紹也許你還不了解它是干嘛的,沒關系!我們舉個例子。
首先,我有一個需要測試的函數:
def add(a, b):'''實現加法運算'''return a + b
測試代碼是這樣的:
import unittestclass AddTest(unittest.TestCase): def test_case1(self): c = add(1, 2) self.assertEqual(c, 3) def test_case2(self): c = add(0, 2) self.assertEqual(c, 2) def test_case3(self): c = add(-2, 2) self.assertEqual(c, 0)if __name__ == ’__main__’: unittest.main()
為了更全面的驗證的 add() 函數,我必須設計足夠多的 測試數據, 同樣也需要很多條用例!
當然,為了測試足夠多的數據,我們也可以將代碼改稱這樣。
import unittestfrom random import randintclass AddTest(unittest.TestCase): def test_case(self): for i in range(10): a = randint(-32768, 32767) b = randint(-32768, 32767) print('a->', a) print('b->', b) c1 = a + b c2 = add(a, b) self.assertEqual(c1, c2)if __name__ == ’__main__’: unittest.main()
通過調用 randint() 函數生成隨機數。循環10次(也可以是100次,1000次),用更少的代碼做更多的測試,測試的數據越多,發現bug的可能性越大。
測試結果如下:
> python test_hypothesis_demo.py
a-> 11503b-> -784a-> -31548b-> 13057a-> 22033b-> 3618a-> -32249b-> 28025a-> -15429b-> 31055a-> 16095b-> 13445a-> -31536b-> 14606a-> 18655b-> -18039a-> 17923b-> -12079a-> -9256b-> -26440.------------------------Ran 1 test in 0.002s
OK
用 hypothesis生成測試數據
上面的測試數據很難隨機到 邊界值,除非我手動設計數據,而且用for循環也不是太好的設計。是時候讓hypothesis登場了。
import unittestfrom hypothesis import given, settingsimport hypothesis.strategies as stclass AddTest(unittest.TestCase): @settings(max_examples=10) @given(a=st.integers(), b=st.integers()) def test_case(self, a, b): print('a->', a) print('b->', b) c1 = a + b c2 = add(a, b) self.assertEqual(c1, c2)if __name__ == ’__main__’: unittest.main()
通過@given() 裝飾測試用例,調用strategies 模塊下面的 integers() 方法生成隨機的測試數。在@setting()裝飾器中通過max_examples用來控制隨機數的個數。
運行結果如下:
> python test_hypothesis_demo.py
a-> 0 b-> 0 a-> 5980 b-> -3607224505277606703a-> 324106882b-> 23975a-> 23272b-> 4917 a-> 107b-> -155 a-> -4500b-> -8303a-> 2683 b-> 4384 a-> 27b-> -81a-> -122472823694675410551869872440384533757 b-> -89a-> 19075b-> 4362 .-------------------------------------------------Ran 1 test in 0.032s
hypothesis 生成的數據會更具有 測試價值,對吧? hypothesis 還可以生成更多類型的測試數據。例如 email格式和text格式。
email-> [email protected]>email-> ^[email protected] text-> -email-> 6a#@T.HKttext-> ↕email-> ’/YAw/[email protected]> +�email-> *xh*-#t5$0-L8O&r10XnXU-**+e%[email protected]> #�����/���+�)�▲�email-> 2U!N0+|*%[email protected]>email-> &i/o!F*@xuW--03.p00-t0Y-0Z0.MW.K-000-n-sB0rR-0L.Y.y2u.NXptL0bgG-0U.XN--FLw351Etext-> �0▲-���email-> oK*[email protected]> ☺email-> /@mOL.Y-Q.j.p.d-3Mzi.i.Utv-M.yachtstext-> (email-> 4ql$y2%[email protected]>
這些數據看上去就具有很高的測試價值。好吧!測試一定明白我在說什么。
問題來了,我們可以將 hypothesis 生成的數據應用到 Web或接口自動化測試中么?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: