【发布时间】: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