使用Hypothesis生成測試數據
- 2019 年 10 月 3 日
- 筆記
Hypothesis是Python的一個高級測試庫。它允許編寫測試用例時參數化,然後生成使測試失敗的簡單易懂的測試數據。可以用更少的工作在程式碼中發現更多的bug。
安裝
pip install hypothesis
如何設計測試數據
通過介紹也許你還不了解它是幹嘛的,沒關係!我們舉個例子。
首先,我有一個需要測試的函數:
def add(a, b): """實現加法運算""" return a + b
測試程式碼是這樣的:
import unittest class 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 unittest from random import randint class 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-> 11503 b-> -784 a-> -31548 b-> 13057 a-> 22033 b-> 3618 a-> -32249 b-> 28025 a-> -15429 b-> 31055 a-> 16095 b-> 13445 a-> -31536 b-> 14606 a-> 18655 b-> -18039 a-> 17923 b-> -12079 a-> -9256 b-> -26440 . ------------------------ Ran 1 test in 0.002s OK
用 hypothesis生成測試數據
上面的測試數據很難隨機到 邊界值,除非我手動設計數據,而且用for循環也不是太好的設計。是時候讓hypothesis登場了。
import unittest from hypothesis import given, settings import hypothesis.strategies as st class 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-> -3607224505277606703 a-> 324106882 b-> 23975 a-> 23272 b-> 4917 a-> 107 b-> -155 a-> -4500 b-> -8303 a-> 2683 b-> 4384 a-> 27 b-> -81 a-> -122472823694675410551869872440384533757 b-> -89 a-> 19075 b-> 4362 . ------------------------------------------------- Ran 1 test in 0.032s
hypothesis 生成的數據會更具有 測試價值,對吧? hypothesis 還可以生成更多類型的測試數據。例如 email格式和text格式。
email-> [email protected] text-> email-> ^[email protected] text-> - email-> 6a#@T.HKt text-> ↕ email-> '/YAw/[email protected] text-> +� email-> *xh*-#t5$0-L8O&r10XnXU-**+e%[email protected] text-> #�����/���+ �)�▲� email-> 2U!N0+|*%[email protected] text-> email-> &i/o!F*@xuW--03.p00-t0Y-0Z0.MW.K-000-n-sB0rR-0L.Y.y2u.NXptL0bgG-0U.XN--FLw351E text-> �0▲-��� email-> oK*[email protected] text-> ☺ email-> /@mOL.Y-Q.j.p.d-3Mzi.i.Utv-M.yachts text-> ( email-> 4ql$y2%[email protected] text->
這些數據看上去就具有很高的測試價值。好吧!測試一定明白我在說什麼。
問題來了,我們可以將 hypothesis 生成的數據應用到 Web或介面自動化測試中么?