简体   繁体   English

假设检验:如何从另一种策略中取样?

[英]Hypothesis tests: how to sample_from values from another strategy?

I have to test some function with a sample data: 我必须使用示例数据测试一些函数:

data = [
    [[10, 20, 30], 10],
    [[20, 30], 20],
    [[40], 30],
]

where the first element in each row, lists, contains N=(1 to 5) random integer elements generated via: 其中每行中的第一个元素list包含通过以下方式生成的N =(1到5)个随机整数元素:

st.lists(
          st.integers(min_value=10),
          min_size=2,
          max_size=5,
          unique=True)

Second elements in each row contain a random sample from a set of all unique integers from all generated lists. 每行中的第二个元素包含来自所有生成列表的所有唯一整数的集合中的随机样本。

So for my data example: 所以对于我的data示例:

  • lists contains values from unique set (10,20,30,40); 列表包含来自唯一集合的值(10,20,30,40);
  • second elements in each row contain a random integer sample from that set; 每行中的第二个元素包含该集合中的随机整数样本;

How do I implement such a strategy with Hypothesis testing framework? 如何使用假设检验框架实施这样的策略?

This one does not works: 这个不起作用:

int_list = st.integers(min_value=10)

@given(st.lists(
    elements=st.tuples(
        int_list, 
        st.sampled_from(int_list))

Check out the docs on adapting strategies - you can do this with .flatmap(...) , but defining a custom strategy with @composite might be simpler. 查看有关适应策略的文档 - 您可以使用.flatmap(...)执行此.flatmap(...) ,但使用@composite定义自定义策略可能更简单。

# With flatmap
elem_strat = lists(
    integers(), min_size=2, max_size=5, unique=True
).flatmap(
    lambda xs: tuples(just(xs), sampled_from(xs)).map(list)
)

# With @composite
@composite
def elem_strat_func(draw):
    xs = draw(lists(
        integers(), min_size=2, max_size=5, unique=True
    )
    an_int = draw(sampled_from(xs))
    return [xs, an_int]
elem_strat = elem_strat_func()

# then use either as
@given(lists(elem_strat))
def test_something(xs): ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对于假设策略,如何从 max_value 而不是 min_value 开始测试用例? - How to start test cases starting from max_value instead of min_value for a Hypothesis strategy? 如何生成一个假设策略来生成一个列表,该列表至少包含它从中采样的每个元素中的一个? - How can I generate a hypothesis strategy to generate a list that contains at least one of each element it samples from? Python假设 - 为许多测试构建策略一次? - Python Hypothesis - building strategy once for many tests? 假设策略:对于每个“桶”,从桶中提取一个值 - Hypothesis strategy: for each “bucket”, draw one value from the bucket 如何在@given中参数化假设策略 - How to parametrize Hypothesis strategy in @given 不同类型值字典的假设搜索策略 - Hypothesis search strategy for dictionaries with different types of values 创建返回唯一值的假设策略 - Create hypothesis strategy that returns unique values 如何从值列表中的样本中获取排名? - How to get ranks from a sample in a list of values? 如何从列表中的python值中随机采样? - How to randomly sample from python values in a list? 如何直接从数据类生成带有假设的测试样本? - How to generate test samples with Hypothesis directly from dataclasses?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM