Random sampling with Hypothesis
<p>In Hypothesis, there is an <a href="http://hypothesis.readthedocs.io/en/latest/data.html#choices" rel="nofollow">corresponding <code>sampled_from()</code> strategy</a> to <a href="https://docs.python.org/3/library/random.html#random.choice" rel="nofollow"><code>random.choice()</code></a>:</p>

<pre><code>In [1]: from hypothesis import find, strategies as st

In [2]: find(st.sampled_from(('ST', 'LT', 'TG', 'CT')), lambda x: True)
Out[2]: 'ST'
</code></pre>

<p>But, is there a way to have <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample()</code></a>-like strategy to produce subsequences of length N out of a sequence?</p>

<pre><code>In [3]: import random

In [4]: random.sample(('ST', 'LT', 'TG', 'CT'), 2)
Out[4]: ['CT', 'TG']
</code></pre>

<p>It feels like this should be possible with the <code>lists</code> strategy, but I couldn't make it work. By aping the <a href="https://github.com/HypothesisWorks/hypothesis-python/blob/3.5.1/src/hypothesis/strategies.py#L400-L418" rel="nofollow"><code>sampled_from</code></a> code, I was able to make something that seems to work.</p>

<pre><code>from random import sample
from hypothesis.searchstrategy.strategies import SearchStrategy
from hypothesis.strategies import defines_strategy


class SampleMultipleFromStrategy(SearchStrategy):
    def __init__(self, elements, n):
        super(SampleMultipleFromStrategy, self).__init__()
        self.elements = tuple(elements)
        if not self.elements:
            raise ValueError
        self.n = int(n)

    def do_draw(self, data):
        return sample(self.elements, self.n)

@defines_strategy
def sample_multiple_from(elements, n):
    return SampleMultipleFromStrategy(elements, n)
</code></pre>

<p>Sample result:</p>

<pre><code>&gt;&gt;&gt; find(sample_multiple_from([1, 2, 3, 4], 2), lambda x: True)
[4, 2]
</code></pre>

python unit-testing testing random python-hypothesis