2

I'm trying to generate sample data using the fixed_dictionaries strategy where two of the keys have lists as values that must be of equal length, e.g.:

{'ids': [1, 2, 3],
 'words': ['foo', 'bar', 'baz']}

How can I enforce this constraint? I thought I might be able to define one as a composite in terms of the other, but I'm not sure how to do that. Something like:

import hypothesis.strategies as st

ids = st.lists(elements=st.integers())

@st.composite
def words(draw, elements=st.text()):
    draw(sample_ids) # ???
tkocmathla
  • 901
  • 11
  • 24

1 Answers1

6

Here's one way to solve this:

@composite
def my_dicts(draw):
    size = draw(st.integers(min_value=0))
    ids = st.lists(min_size=size, max_size=size)
    words = st.lists(min_size=size, max_size=size)
    dicts = st.fixed_dictionaries({'ids': ids, 'words': words})

    return draw(st.lists(dicts))
tkocmathla
  • 901
  • 11
  • 24