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

如何让pytest结合Hypothesis发现首个反例后立即终止测试?

让Hypothesis发现首个反例后立即停止生成用例的方案

1. 用Hypothesis专属命令行参数

在执行pytest时添加--hypothesis-stop-on-first-failure参数,Hypothesis会在找到第一个触发失败的测试用例后,立刻停止当前测试的用例生成流程,不会继续生成更多用例或尝试简化反例。

执行命令示例:

pytest --hypothesis-stop-on-first-failure

2. 结合pytest全局停止参数(可选)

如果希望整个测试套件在遇到第一个失败的测试后直接终止运行(而非仅当前测试停止生成用例),可以同时加上pytest的-x(或--exitfirst)参数:

pytest -x --hypothesis-stop-on-first-failure

补充:代码层面临时配置

如果需要针对单个测试临时生效,也可以通过settings装饰器设置max_examples=1,但这种方式灵活性不如命令行:

from hypothesis import given, settings, strategies as st

def foo(value):
    return vslue + 1 # 拼写错误

@given(st.integers())
@settings(max_examples=1)
def test_foo(x):
    assert foo(x) == x + 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:56:01