Stack Overflow Asked by RAbraham on December 16, 2021
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):
...
Answered by Georgy on December 16, 2021
Since you want at most 20 items, generate a random number from 1 to 20:
import random
size = random.randint(1,20)
Then use that number to make N number of independent choices from your source list:
texts = ['t1', 't2', 't3', 't4']
random_texts = []
for _ in range(size):
random_texts.append(random.choice(texts))
Answered by John Gordon on December 16, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP