本文介绍如何在使用 pytest 和 Hypothesis 进行属性测试时,在发现第一个反例后立即停止测试。通过配置 Hypothesis 的设置,我们可以创建一个 “failfast” 模式,该模式仅运行显式测试、重用测试和生成测试阶段,从而避免耗时的缩减过程,提高调试效率。
在使用 Hypothesis 进行测试时,默认情况下,它会在找到一个反例后尝试 缩减 这个反例,以便找到一个更简单的、更容易理解的触发错误的情况。虽然这在许多情况下很有用,但在某些情况下,我们可能只想在找到第一个反例后立即停止测试,以便更快地定位和修复问题。
以下是如何使用 Pytest 和 Hypothesis 实现快速失败测试的方法:
1. 创建一个 Hypothesis 设置 Profile
首先,我们需要创建一个自定义的 Hypothesis 设置 Profile,该 Profile 将禁用缩减阶段。这可以通过在 conftest.py 文件中注册一个新的 Profile 来实现。
from hypothesis import settings, Phase settings.register_profile( "failfast", phases=[Phase.explicit, Phase.reuse, Phase.generate] )
- settings.register_profile(“failfast”, …): 注册一个名为 “failfast” 的 Profile。
- phases=[Phase.explicit, Phase.reuse, Phase.generate]: 指定该 Profile 只运行显式测试、重用测试和生成测试阶段。 重要的是要排除 Phase.shrink 以避免缩减反例。
2. 使用命令行选项运行测试
接下来,我们需要使用 Pytest 的命令行选项 –hypothesis-profile 来指定我们创建的 “failfast” Profile。
pytest tests --hypothesis-profile failfast
- pytest tests: 运行 tests 目录下的所有测试。
- –hypothesis-profile failfast: 使用名为 “failfast” 的 Hypothesis Profile。
示例
假设我们有以下测试代码:
from hypothesis import given import hypothesis.strategies as st def foo(value): return vslue 1 # a silly typo @given(st.integers()) def test_foo(x): assert foo(x) == x 1
当我们运行 pytest tests –hypothesis-profile failfast 时,Hypothesis 将在找到第一个反例后立即停止测试。 这可以帮助我们快速识别代码中的错误(例如,上面代码中的拼写错误)。
注意事项
- conftest.py 文件需要位于测试目录的根目录或其父目录中,以便 Pytest 能够找到它。
- 确保安装了 pytest 和 hypothesis 库。可以使用 pip install pytest hypothesis 安装它们。
- 如果需要全局应用此设置,可以将 profile 设置为默认值:settings.load_profile(“failfast”),但这可能会影响其他测试,因此建议仅在需要时使用命令行选项。
总结
通过使用 Hypothesis 的设置 Profile 功能,我们可以轻松地配置 Pytest 测试在发现第一个反例后立即停止。这可以显著提高调试效率,尤其是在处理大型代码库或复杂测试用例时。 通过注册一个禁用缩减阶段的 Profile,我们可以避免不必要的计算,并更快地定位和修复问题。