【问题标题】:Make hypothesis test all values对所有值进行假设检验
【发布时间】:2021-08-04 16:29:08
【问题描述】:

我正在寻找一种方法来使假设执行以下操作:

@given(device=st.test_every_value_of(["cpu", "gpu"])
def test_a_thing(self, device):
  do_something_with_device(device)

但是我还没有找到像st.test_every_value_of这样的策略。

有什么好的方法吗?

【问题讨论】:

    标签: python python-hypothesis


    【解决方案1】:

    事实证明有两种可能的解决方案。

    首先是使用st.sampled_from

    @given(device=st.sampled_from(["cpu", "gpu"]))
    def test_a_thing(self, device):
      do_something_with_device(device)
    

    st.sampled_from 不能保证测试所有传递给它的值。但是,Hypothesis 默认情况下会根据指定的策略生成 100 个测试用例。如果st.sampled_from 包含>100 个项目或者如果它与其他策略结合使用,那么它可能不会测试所有值;但是,对于较小的测试,它可能工作正常。

    更好的解决方案大概是使用pytest的parameterize

    import pytest
    
    @pytest.mark.parameterize("device", ["cpu", "gpu"])
    def test_a_thing(self, device):
      do_something_with_device(device)
    

    如果这与假设一起使用,那么假设将为参数化生成的每个实例运行 100 次测试。

    【讨论】:

      猜你喜欢
      • 2017-10-27
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2021-07-13
      • 2021-09-09
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多