[英]Python hypothesis: Ensure that input lists have same length
I'm using hypothesis to test a function that takes two lists of equal length as input.我正在使用假设来测试一个将两个长度相等的列表作为输入的函数。
import hypothesis.strategies as st
from hypothesis import assume, given
@given(st.lists(ints, min_size=1),
st.lists(ints, min_size=1),
)
def test_my_func(x, y):
assume(len(x) == len(y))
# Assertions
This gives me the error message:这给了我错误信息:
FailedHealthCheck: It looks like your strategy is filtering out a lot of data.
FailedHealthCheck:看起来您的策略正在过滤掉大量数据。 Health check found 50 filtered examples but only 4 good ones.
健康检查发现了 50 个过滤的示例,但只有 4 个很好的示例。
The assumption that len(x) == len(y)
is filtering out too many inputs. len(x) == len(y)
过滤掉太多输入的假设。 So I would like to generate a random positive number and use that as the length of both x
and y
.所以我想生成一个随机正数并将其用作
x
和y
的长度。 Is there a way this can be done?有没有办法做到这一点?
I found an answer using the @composite
decorator.我使用
@composite
装饰器找到了答案。
import hypothesis.strategies as st
from hypothesis import given
@st.composite
def same_len_lists(draw):
n = draw(st.integers(min_value=1, max_value=50))
fixed_length_list = st.lists(st.integers(), min_size=n, max_size=n)
return (draw(fixed_length_list), draw(fixed_length_list))
@given(same_len_lists())
def test_my_func(lists):
x, y = lists
# Assertions
You can use flatmap
to generate data that depends on other generated data.您可以使用
flatmap
生成依赖于其他生成数据的数据。
import hypothesis.strategies as st
from hypothesis import assume, given
from hypothesis.strategies import integers as ints
same_len_lists = ints(min_value=1, max_value=100).flatmap(lambda n: st.lists(st.lists(ints(), min_size=n, max_size=n), min_size=2, max_size=2))
@given(same_len_lists)
def test_my_func(lists):
x, y = lists
assume(len(x) == len(y))
It's a little clumsy, and I'm not very happy about having to unpack the lists inside the test body.这有点笨拙,我对不得不在测试体中解压列表不太高兴。
The other solutions give nice reusable strategies.其他解决方案提供了很好的可重用策略。 Here's a short low-tech solution, perhaps better suited to one-off use since you need to do one line of processing in the test function.
这是一个简短的低技术解决方案,可能更适合一次性使用,因为您需要在测试功能中进行一行处理。 We use zip to tranpose a list of pairs (2-element tuples);
我们使用 zip 来转置对列表(2 元素元组); conceptually we're turning a
nx 2
matrix into a 2 xn
matrix.从概念上讲,我们将
nx 2
矩阵转换为2 xn
矩阵。
import hypothesis.strategies as st
from hypothesis import given
pair_lists = st.lists(st.tuples(st.integers(), st.integers()), min_size=1)
@given(pair_lists)
def test_my_func(L):
x, y = map(list, zip(*L))
Warning: It is crucial to have min_size=1
because zip
will give nothing if the list is empty.警告:使
min_size=1
至关重要,因为如果列表为空, zip
将不会给出任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.