【问题标题】:Given a Hypothesis Strategy, can I get the minimal example?给定假设策略,我可以得到最小的例子吗?
【发布时间】:2021-06-02 17:18:14
【问题描述】:

我想获得一个复杂课程的最低要求,我已经为此编写了策略。

是否可以提出假设来简单地给我一个给定策略的最小示例?

这里的上下文是写一个策略和一个默认最小值(用于@hypothesis.example)——肯定后者的信息已经包含在前者中了吗?

import dataclasses
import hypothesis
from hypothesis import strategies

@dataclasses.dataclass
class Foo:
    bar: int
    # Foo has many more attributes which are strategised over...

    @classmethod
    def strategy(cls):
        return hypothesis.builds(cls, bar=strategies.integers())

    @classmethod
    def minimal(cls):
        return hypothesis.minimal(cls.strategy())

【问题讨论】:

    标签: python-hypothesis


    【解决方案1】:

    找到答案。 使用hypothesis.find

    """返回给定策略 specifier 的最小示例 匹配谓词函数condition

    所以我们想要上面例子的以下代码:

    minimal = hypothesis.find(
        specifier=Foo.strategy(),
        condition=lambda _: True,
    )
    

    【讨论】:

      【解决方案2】:

      hypothesis.find(s, lambda _: True) 是正确的做法。


      这里的上下文是编写一个策略和一个默认最小值(用于@hypothesis.example())- 肯定后者的信息已经包含在前者中吗?

      它不仅包含在其中,而且生成示例几乎总是从生成最小示例开始* - 因为如果失败,我们可以立即停止!所以你可能根本不需要这样做;-)

      (罕见的例外是具有复杂过滤器的策略,其中尝试的最小示例被过滤器拒绝 - 我们只是转向合理最小的示例,而不是缩小以找到最小的示例)


      我还要注意st.builds() has native support for dataclasses,因此对于没有比“类型的任何实例”更具体的约束的任何参数,您都可以省略策略(或传递hypothesis.infer)。比如上面的bar=st.integers()就不用传了!

      【讨论】:

        猜你喜欢
        • 2017-04-24
        • 1970-01-01
        • 2015-11-14
        • 2022-09-30
        • 2015-05-05
        • 2018-07-17
        • 1970-01-01
        • 1970-01-01
        • 2014-11-10
        相关资源
        最近更新 更多