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

使用Hypothesis与Pytest调试属性测试单个失败示例的便捷方法

调试Hypothesis属性测试失败示例的便捷方法

当用pytest + Hypothesis做属性测试时,遇到用例失败后,想要针对触发失败的特定示例做断点调试,不用像之前那样繁琐替换装饰器。比如原测试代码:

@given(a=st.integers())
def test(a):
    assert a != 4

下面是几种更便捷的方法:

方法1:用@example配合--hypothesis-max-examples=1

测试失败时,Hypothesis会在输出里给出最小化后的失败示例(比如这里的a=4)。不用注释@given,直接给测试函数加上@example装饰器指定失败用例,然后运行测试时限制只跑这一个示例:

from hypothesis import given, example
import hypothesis.strategies as st

@given(a=st.integers())
@example(a=4)
def test(a):
    breakpoint()
    assert a != 4

执行命令:

pytest test_file.py -xvs --hypothesis-max-examples=1

-x确保遇到失败就停止,-vs显示详细输出,--hypothesis-max-examples=1让Hypothesis只运行指定的@example用例,直接触发断点调试。

方法2:利用失败重现种子

Hypothesis测试失败后,会在输出里生成一个种子值,比如:

Falsifying example: test(a=4)
Run with --hypothesis-seed=123456789 to reproduce this failure

直接用这个种子命令运行测试,就能精准重现失败场景,同时触发断点:

pytest test_file.py -xvs --hypothesis-seed=123456789

不用修改任何代码,直接复用种子值即可。

方法3:规范使用pytest.mark.parametrize

如果想临时去掉@given,直接用pytest的参数化,注意要把参数值放在可迭代对象里(比如列表),不用改函数结构:

import pytest

@pytest.mark.parametrize("a", [4])
def test(a):
    breakpoint()
    assert a != 4

这种写法比之前直接传单个值更规范,避免语法问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:35:24