【发布时间】:2021-06-16 10:56:07
【问题描述】:
我刚刚开始使用假设进行测试生成。使用假设时,如何允许测试函数中出现某些错误?
简单的例子是一个除法函数,它适用于大于 0 的整数:
def divide(a: int, b: int) -> float:
return a/b
当我在没有明确排除 0 的情况下编写假设检验时,我当然会出错:
from hypothesis import given, strategies as st
@given(a=st.integers(), b=st.integers())
def test_divide(a, b):
assert isinstance(divide(a,b), float)
由于假设使用整数 0 我得到ZeroDivisionError:
---------------------------
Falsifying example: test_divide(
a=0, b=0,
)
============================
FAILED test.py::test_divide - ZeroDivisionError: division by zero
这当然是意料之中的,在这个简单的例子中,我可以简单地排除 0,因为我知道错误会发生。在其他函数中,尤其是那些使用字符串的函数中,很难排除所有我知道会引发错误的东西。在许多情况下,尽管错误是可以的,例如在字符串函数中使用空字节时。
是否有可能以某种方式“允许”某些类型的错误?
或者我是否必须重新考虑在使用假设时如何编写测试?
【问题讨论】:
-
只需从除数策略中排除零,例如
b=st.integers().filter(bool) -
并使用
b=st.just(0)在不同的测试用例中单独测试零