要約
乱数が使われていて、一定の確率で失敗する単体テストが失敗した時に、「焦らずもう一回やってみてね」と表示するデコレータ
ソース
randtest.py
import unittest
import numpy as np
def statistical(test):
def do_test(self):
try:
test(self)
except AssertionError as e:
e.args += ("NOTE: this is a statistical test, which may fail.", )
raise
return do_test
class TestHoge(unittest.TestCase):
@statistical
def test_normal(self):
val = np.random.uniform(0, 1, 1)
self.assertTrue(val[0] < 0.8) # 10回に2回くらい失敗する
if __name__ == "__main__":
unittest.main()
statisticalというデコレータを定義しておいて、乱数を使ったテストの前に、@statisticalと置いておく。
実行結果
bash-3.2$ for i in $(seq 10); do ./randtest.py ; done
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
F
======================================================================
FAIL: test_normal (__main__.TestHoge)
----------------------------------------------------------------------
Traceback (most recent call last):
File "./randtest.py", line 14, in do_test
test(self)
File "./randtest.py", line 24, in test_normal
self.assertTrue(val[0] < 0.8)
AssertionError: ('False is not true', 'NOTE: this is a statistical test, which may fail.')
----------------------------------------------------------------------
Ran 1 test in 0.006s
FAILED (failures=1)
...以下略...