![victor-grabarczyk-yLFCOI9VVGs-unsplash.jpg](/_next/image?url=https%3A%2F%2Fimages.ctfassets.net%2Fai4vjpehjr3j%2F6pBvWqH9tJrLx73LsYO8OE%2F2466cbd9ae79ae92b6c1c02a4997ef28%2Fvictor-grabarczyk-yLFCOI9VVGs-unsplash.jpg&w=3840&q=75)
Pythonのproperty based testingライブラリhypothesisの使い方
![Kazuki Moriyama](/_next/image?url=https%3A%2F%2Fimages.ctfassets.net%2Fai4vjpehjr3j%2F2Oa6QzkYOe51LQiER7VEtN%2F6e819c38a98a1c649401b86861c40d53%2Fimage.png&w=96&q=75)
Kazuki Moriyama (森山 和樹)
基本
strategies
- pbtに必要な値の生成を担う
- 他のフレームワークでいうgenみたいなもの
strategies
dictionaryやクラスなどの複雑な値のstrategiesを作りたい
builds
メソッドを使う- buildにはcallableなtargetオブジェクトと、そのcallに必要な値のstrategiesを渡す
def make_dict(a, b):
return {"a": a, "b": b}
class A:
def __init__(self, a, b):
self.a = a
self.b = b
@given(builds(make_dict, text(), floats()))
def test_dict(d):
# {"a": str, "b": float} 型の値がdに渡って来てそれを用いてテストできる
...
@given(builds(A, text(), floats()))
def test_class(a):
# A(str, float)がaに渡ってくる
...
- targetのにtype hintを与えてやると引数になるstrategiesを渡さなくても自動で推測して値を生成してくれる
def make_dict(a: str, b: float):
return {"a": a, "b": b}
class A:
def __init__(self, a: str, b: float):
self.a = a
self.b = b
@given(builds(make_dict))
def test_dict(d):
# {"a": str, "b": float} 型の値がdに渡って来てそれを用いてテストできる
...
@given(builds(A))
def test_class(a):
# A(str, float)がaに渡ってくる
...
pytestとの併用
fixtureを使用しつつstrategiesをgiveする
- pytestではfixtureと同じ名前の引数を定義しておけばそれが勝手に引数に渡ってくる
import pytest
@pytest.fixture
def some_int():
yield 1
def test_int(some_int):
print(some_int) # テストを実行すると`1`が出力
- hypothesisのgivenと一緒に使用するときはgivenでどの引数に値を渡すかを指定するfixtureと併用できる
import pytest
from hypothesis import given
from hypothesis.strategies import text
@pytest.fixture
def some_int():
yield 1
@given(some_str=text())
def test_int(some_int, some_str):
print(some_int) # テストを実行すると`1`が出力
print(some_str) # ランダムなstringが出力される