gpt4 book ai didi

python - 使用 given with parametrize

转载 作者:行者123 更新时间:2023-12-04 15:32:05 26 4
gpt4 key购买 nike

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


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 属性

我该怎么做?

最佳答案

我能想到的一种可能的解决方法是在测试中构建策略并使用 data strategy画例子,比如

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

关于python - 使用 given with parametrize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61064866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com