如何让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
相关产品推荐
相关产品推荐

