Help us understand the problem. What is going on with this article?

# 乱数を使った単体テストのためのデコレータ

More than 5 years have passed since last update.

# ソース

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)
...以下略...
```
GPSデータの分析を専門とするDocomo系列のスタートアップです。
https://www.datawise.co.jp/
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away