I am looking for a way to build a Hypothesis strategy such that each element in a given list is present in the generated list.

e.g.

Assuming that we have

values = [0, 1, 2, 3, 5, 8]

we want a strategy that generates lists from given values such that each element appears at least once, e.g.

[0, 1, 2, 3, 5, 8]
[2, 1, 0, 3, 5, 8]
[0, 0, 1, 2, 3, 5, 8]
[0, 0, 0, 1, 2, 3, 5, 8]
[5, 2, 5, 2, 8, 2, 0, 8, 3, 2, 0, 5, 5, 3, 5, 5, 5, 1]

I am getting errors in my program because I need to select a value that does not exist in a list that uses the sampled_from strategy. (presumably with a large enough list, the probability that such a value would appear grows, however I am working with expensive objects, and that seems like a workaround)

I have spent quite some time trying to figure out if any of the strategies enforce that certain values will appear in the generated values -- fixed_dictionaries seems to be the only one -- and I am struggling to even come up with a simple composite strategy.

1

There are 1 best solutions below

0
On

We can use strategies.lists and then concatenate with values so that every value is presented and then shuffle

from hypothesis import strategies

sub_values = (strategies.lists(strategies.sampled_from(values))
              .map(lambda sublist: sublist + values)
              .flatmap(strategies.permutations))