3

我想知道是否可以使用given来自 pytestparametrize函数的参数。
例子:


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

@given(my_strategy(attribute))希望这attribute将是参数化的属性,并在my_strategy每次运行时生成所需的新属性attribute

我怎样才能做到这一点?

4

1 回答 1

2

我能想到的一种可能的解决方法是在测试中构建策略并使用data策略来绘制示例,例如

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

但我认为最好的方法是编写策略而不将其与以下内容混合mark.parametrize

@given(st.sampled_from([1, 2, 3]).flatmap(my_strategy))
def test_foo(example):
    ...  # rest of the test
于 2020-04-06T21:02:39.273 回答