【问题标题】:Combining unit and property-based tests in pytest and Hypothesis在 pytest 和 Hypothesis 中结合基于单元和属性的测试
【发布时间】:2021-12-08 04:43:07
【问题描述】:

我需要在 Python 中混合运行单元测试和基于属性的测试。我当前的测试代码分别运行它们,因此重复了一些代码:

@pytest.mark.parametrize("values", list_of_values)
def test_my_function(a_value):
    call_test(a_value)

@given(st.arbitrary_values())
def test_hypothesis_my_function(a_value):
    call_test(a_value)

上面有一个代码重复:test_my_functiontest_hypothesis_my_function 是一样的,只是分别由基于单元和基于属性的基础设施触发。

我宁愿消除上面的代码重复以获得这样的东西:

@pytest.mark.parametrize("values", list_of_values)
@given(st.arbitrary_values())
def test_my_function(a_value):
    call_test(a_value)

能达到这个效果吗?提前致谢。

【问题讨论】:

  • 你试过后者吗?发生了什么?
  • 好问题,谢谢。 pytest 抱怨test_my_function: function uses no argument 'values'。如果我交换 @pytest 和 @given 调用,也会发生这种情况。
  • 请为call_test 添加导入和一些示例代码,以便代码可以运行。我尝试导入import hypothesis.strategies as st,但由于缺少arbitrary_values而得到了AttributeError

标签: python pytest python-hypothesis


【解决方案1】:

如果你的参数列表是源代码中的文字,你可以translate that to a sequence of @example() decorators:

@given(text())
@example("Hello world")
@example(x="Some very long string")
def test_some_code(x):
    pass

如果它是一个显式列表,您可以编写一个辅助函数来为您应用它们:

def parametrize(list_of_args):
    def inner(f):
        for a in list_of_kwargs:
            f = hypothesis.example(*a)(f)
        return f
    return inner

@parametrize(list_of_args_tuples)
@given(text())
def test_some_code(x):
    pass

【讨论】:

  • 谢谢扎克。辅助功能非常有用。
猜你喜欢
  • 2017-07-29
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 2020-03-06
  • 2011-03-10
相关资源
最近更新 更多