基本
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_dict(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_dict(a): # A(str, float)がaに渡ってくる ...
pytestとの併用
fixtureを使用しつつstrategiesをgiveする
- pytestではfixtureと同じ名前の引数を定義しておけばそれが勝手に引数に渡ってくる
@pytest.fixture def some_int() yield 1 def test_int(some_int): print(some_int) # テストを実行すると`1`が出力
- hypothesisのgivenと一緒に使用するときはgivenでどの引数に値を渡すかを指定するfixtureと併用できる
@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が出力される
View Comments