Python hypothesis: Ensure that input lists have same length
I found an answer using the @composite
decorator.
import hypothesis.strategies as st
from hypothesis import given
@st.composite
def same_len_lists(draw):
n = draw(st.integers(min_value=1, max_value=50))
fixed_length_list = st.lists(st.integers(), min_size=n, max_size=n)
return (draw(fixed_length_list), draw(fixed_length_list))
@given(same_len_lists())
def test_my_func(lists):
x, y = lists
# Assertions
You can use flatmap
to generate data that depends on other generated data.
import hypothesis.strategies as st
from hypothesis import assume, given
from hypothesis.strategies import integers as ints
same_len_lists = ints(min_value=1, max_value=100).flatmap(lambda n: st.lists(st.lists(ints(), min_size=n, max_size=n), min_size=2, max_size=2))
@given(same_len_lists)
def test_my_func(lists):
x, y = lists
assume(len(x) == len(y))
It's a little clumsy, and I'm not very happy about having to unpack the lists inside the test body.