如何使用假设从给定列表生成可变大小的列表?

How do I generate a variable sized list from a given list using Hypothesis?

对于基于 属性 的测试,给定一个固定的值列表,我需要生成一个可变大小的列表,其中顺序很重要并且允许重复。例如,如果我的固定列表是

texts = ['t1', 't2', 't3', 't4']

我想生成不同的变体,例如

['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.

我目前使用的是permutations策略

from hypothesis import given, strategies as st

@given(st.permutations(texts))
def test_x(some_text):
   ...
   pass

但这并没有给我可变大小,重复

其他要求:

由于您最多需要 20 个项目,因此生成一个 1 到 20 之间的随机数:

import random
size = random.randint(1,20)

然后使用该数字从您的来源列表中做出 N 次独立选择:

texts = ['t1', 't2', 't3', 't4']
random_texts = []
for _ in range(size):
    random_texts.append(random.choice(texts))

您正在寻找 lists and the sampled_from 策略的组合:

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):
    ...

或者如果您希望能够更改不同测试的源列表:

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):
    ...