Search code examples
pythonpython-hypothesis

Using given with parametrize


I was wondering if it is possible to use given with parameters comes from pytest's parametrize function.
Example:


import pytest
from hypothesis import given
from hypothesis import strategies as st


@st.composite
def my_strategy(draw, attribute):
    # Body of my strategy
    return # Something...

@pytest.mark.parametrize("attribute", [1, 2, 3])
@given(my_strategy(attribute))
def test_foo(strategy):
    pass

On @given(my_strategy(attribute)) I want that attribute will be parametrize's attribute and generate new my_strategy every run with the wanted attribute

How can I do that?


Solution

  • The one possible workaround I can think of is to construct strategy inside the test and use data strategy to draw examples, something like

    import pytest
    from hypothesis import given
    from hypothesis import strategies as st
    
    
    @st.composite
    def my_strategy(draw, attribute):
        # Body of my strategy
        return # Something...
    
    @given(data=st.data())
    @pytest.mark.parametrize("attribute", [1, 2, 3])
    def test_foo(attribute, data):
        strategy = my_strategy(attribute)
    
        example = data.draw(strategy)
        ...  # rest of the test
    

    But I think the best way will be to write strategy without mixing it with mark.parametrize:

    @given(st.sampled_from([1, 2, 3]).flatmap(my_strategy))
    def test_foo(example):
        ...  # rest of the test