【问题标题】:Multiple strategies for same function parameter in python hypothesispython假设中相同函数参数的多种策略
【发布时间】:2021-12-12 22:38:09
【问题描述】:

我正在使用 Hypothesis 包在 Python 中编写一个简单的测试代码。有没有办法对同一个函数参数使用多种策略?例如,使用integers()floats() 测试我的values 参数而不编写两个单独的测试函数?

from hypothesis import given
from hypothesis.strategies import lists, integers, floats, sampled_from
@given(
    integers() ,floats()
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

上面的代码不起作用,但它代表了我想要实现的目标。

注意:我已经尝试过使用两种不同策略创建两个不同测试的简单解决方案:

def _test_lt(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

test_lt_operator_interval_bin_int = given(integers())(_test_lt)

test_lt_operator_interval_bin_float = given(floats())(_test_lt)

但是我想知道是否有更好的方法来做到这一点:当策略的数量变得更大时,它作为代码是相当冗余的。

【问题讨论】:

  • 所以你的值可以是整数()或浮点数()?如果是这样,你可以简单地做@given(integers() | floats())
  • 有可能吗?我不知道。如果它有效,它解决了我的问题
  • 是的,这行得通!您也可以使用st.one_of(integers(), floats()),这可能更易于编程使用。
  • 好吧,你可以添加一个答案,我会接受它!

标签: python pytest python-hypothesis


【解决方案1】:

一般而言,如果您需要将您的值作为几件事之一(例如您的示例中的 ints 或 floats),那么我们可以将单独事物的策略与 | 运算符(操作类似为 sets 之一——联合运算符,通过调用 __or__ magic method) 工作:

from hypothesis import given
from hypothesis.strategies import integers, floats
@given(
    integers() | floats()
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

或者您可以使用@Zac Hatfield-Dodds 提到的strategies.one_of,它的作用几乎相同:

from hypothesis import given
from hypothesis.strategies import integers, floats, one_of
@given(
    one_of(integers(), floats())
)
def test_lt_operator_interval_bin_numerical(values):
    interval_bin = IntervalBin(10, 20, IntervalClosing.Both)
    assert (interval_bin < values) == (interval_bin.right < values)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 2017-10-05
    相关资源
    最近更新 更多