【问题标题】:Hypothesis - reuse @given between tests假设 - 在测试之间重用 @given
【发布时间】:2022-04-14 18:27:47
【问题描述】:

我已经使用hypothesis 有一段时间了。我想知道如何重用@given parts

我有一些是 20 行,我将整个 @given 部分复制到几个测试用例上方。

一个简单的测试示例

@given(
    some_dict=st.fixed_dictionaries(
        {
            "test1": st.just("name"),
            "test2": st.integers()
            }
        )
    )
def test_that uses_some_dict_to_initialize_object_im_testing(some_dict):
    pass

重用@given 块的最佳方法是什么?

【问题讨论】:

    标签: python python-hypothesis


    【解决方案1】:

    策略被设计为可组合的对象,重复使用它们没有问题。

    因此,接受答案的替代方案只是将配置的子策略存储为可重用的全局变量,例如

    a_strategy = st.fixed_dictionaries({ "test1": st.just("name"), "test2": st.integers()})
    
    @given(some_dict=a_strategy)
    def test_uses_some_dict_to_initialize_object_im_testing(some_dict):
        ...
    
    @given(some_dict=a_strategy, value=st.integers())
    def test_other(some_dict, value):
        ...
    

    timezones 示例显示了该模式,它定义了一个 aware_datetimes 策略并在多个测试中使用该策略,由可变数量的兄弟组成。

    【讨论】:

      【解决方案2】:

      创建自己的装饰器:

      def fixed_given(func):
          return given(
              some_dict=st.fixed_dictionaries(
                  {
                      "test1": st.just("name"),
                      "test2": st.integers()
                  }
              )
          )(func)
      
      
      @fixed_given
      def test_that_uses_some_dict_to_initialize_object_in_testing(some_dict):
          pass
      

      【讨论】:

        猜你喜欢
        • 2018-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-01
        • 2017-04-26
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        相关资源
        最近更新 更多