You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Hypothesis测试含可选参数(可传None)的函数且无需多测试函数

如何用Hypothesis测试带可选None参数的函数

不用为每种参数组合单独写测试函数,我们可以直接修改Hypothesis的参数生成策略,让start和step既可以生成指定范围的整数,也能生成None,然后在测试函数内部处理参数为None时的默认值逻辑就行,具体步骤如下:

1. 调整参数生成策略

把start和step的生成策略改成st.one_of(st.none(), st.integers(...)),这样Hypothesis会自动生成包含None和整数的测试用例:

from hypothesis import given, settings, Verbosity
from hypothesis.strategies import st
from pytest import raises

@given(
    start=st.one_of(st.none(), st.integers(min_value=-1000, max_value=1000)),
    stop=st.integers(min_value=-1000, max_value=1000),
    step=st.one_of(st.none(), st.integers(min_value=-1000, max_value=1000))
)
@settings(verbosity=Verbosity.verbose)
def test_XXX_for_integer(start, stop, step):
    # 2. 处理参数为None的情况,替换成myrange3的默认值
    # 这里假设myrange3的默认start=0,step=1,你需要根据实际函数定义调整
    actual_start = start if start is not None else 0
    actual_step = step if step is not None else 1

    # 3. 原有测试逻辑保持不变,调用函数时传原始参数以模拟真实场景
    if actual_step == 0:
        with raises(ValueError) as excinfo:
            _ = myrange3(start, stop, step)
        assert 'arg 3 must not be zero' in str(excinfo.value)
    else:
        output = myrange3(start, stop, step)
        # 计算预期结果时使用处理后的实际参数值
        expected = list(range(actual_start, stop, actual_step))  # 示例逻辑,需根据你的函数调整
        assert output == expected

关键说明:

  • 用st.one_of(st.none(), ...)可以让Hypothesis自动覆盖start为None、step为None、两者都为None、两者都不为None的所有组合,不用手动拆分测试函数
  • 处理actual_start和actual_step是为了在计算预期结果时使用正确的参数值,而调用被测函数时直接传原始的start和step,这样才能模拟用户不传可选参数的真实调用场景
  • 如果你的myrange3函数对None的处理逻辑不同(比如默认值不是0和1),只需要修改actual_start和actual_step的替换值就行

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:00:24