【发布时间】:2020-08-18 14:25:18
【问题描述】:
在使用hypothesis 库对程序代码中的断言进行基于属性的测试时,什么被认为是最佳实践?
我创建了一个非常简单的函数来说明我的观点。该函数只是将两个数字相除。如果分母为零,我提出了一个失败的断言。
当我运行测试时,由于断言错误,一旦hypothesis 为参数b(分母)选择0,它就会失败。但是,函数中的断言是为了处理这种特殊情况。
from hypothesis import given
from hypothesis import strategies as st
def divide(a: float, b: float) -> float:
assert b != 0, "Denominator must not be zero!"
return a / b
@given(b=st.floats())
def test_divide(b):
assert isinstance(divide(100, b), (int, float))
我应该如何调整代码以使参数值b=0 的测试通过?什么是pythonic方式?
编辑:
在我看来,建议的重复问题 (Exception handling and testing with pytest and hypothesis) 并不能解决问题。
如果我使用以下代码会发生什么?
@given(b=st.floats())
def test_divide(b):
try:
assert isinstance(divide(100, b), (int, float))
except AssertionError:
assume(False)
据我了解,只要try 块中的断言为False,except-path 就会被执行,并且特定的测试用例将被忽略。也就是说,每个真正的测试失败(由hypothesis 发现)都将被忽略。
与建议的重复问题相比,我的divide-函数将抛出AssertionError 而不是ZeroDivisionError 用于b=0。每个其他失败的测试用例也会导致AssertionError (try-block)。
【问题讨论】:
-
我不这么认为。我编辑了我原来的问题。
标签: python assert python-hypothesis