For property-based testing, given a fixed list of values, I need to generate a variable-sized list where order is important and duplicates are allowed. For example, if my fixed list is
texts = ['t1', 't2', 't3', 't4']
I would like to generate different variations, e.g.
['t2']
['t4', 't1'] # Subset and different order
[]
['t3', 't1', 't2'] # Different order
['t4', 't4', 't4', 't1'] # Repetition of t4
['t1', 't2', 't1'] # Repetition but at different location
['t1', 't2']
['t2', 't1'] # different order from the one above and considered different.
What I have managed to use currently is the permutations
strategy
from hypothesis import given, strategies as st
@given(st.permutations(texts))
def test_x(some_text):
...
pass
But that does not give me variable size, repetitions
Other requirements:
You are looking for a combination of the lists
and the sampled_from
strategies:
from hypothesis import strategies as st
texts = ['t1', 't2', 't3', 't4']
lists_from_texts = st.lists(st.sampled_from(texts), max_size=20)
...
@given(lists_from_texts)
def test_x(some_text):
...
or if you want to be able to change the source list for different tests:
from typing import List
def lists_from_texts(source: List[str]) -> st.SearchStrategy[List[str]]:
return st.lists(st.sampled_from(source), max_size=20)
...
@given(lists_from_texts(texts))
def test_x(some_text):
...