3

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?

UdiM
  • 480
  • 3
  • 19

1 Answers1

2

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
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
  • Correct on both counts - it's generally nicer to stick to Hypothesis if you can, but if not using the data() strategy to draw inside your test function is the only option (and while inelegant it works very well). – Zac Hatfield-Dodds Apr 07 '20 at 14:15