如何在集成测试中使用Python Hypothesis?单次执行问题求解
解答
1. 可以不使用@given获取策略示例
完全可以。直接调用策略的example()虽然能拿到示例,但会触发警告——这是因为Hypothesis不推荐在正式测试里这么用,不过你可以通过hypothesis.settings(verbosity=Verbosity.quiet)关闭警告。更规范的方式是用hypothesis.strategies.data()上下文管理器,它专门用于非@given装饰的测试场景,不会触发警告,示例代码:
from hypothesis import strategies as st from hypothesis.strategies import data def test_integration(): with data() as data_gen: # 用draw()方法从策略中获取示例 foo_instance = data_gen.draw(st.builds(foo, st.integers())) # 执行你的集成测试逻辑 print(f"生成的实例:{foo_instance}")
2. 强制Hypothesis仅运行一次的正确配置
你之前的配置没生效,是因为测试失败时Hypothesis默认会额外运行一次失败案例来确认问题可复现。要彻底禁用这个行为,需要在settings里加上report_multiple_bugs=False,同时保留max_examples=1和phases=[Phase.generate]。修改后的代码:
from hypothesis import given, settings, Phase from hypothesis import strategies as st def foo(foo: int): print("calling foo") return foo @given(st.builds(foo, st.integers())) @settings( max_examples=1, phases=[Phase.generate], report_multiple_bugs=False, deadline=None # 可选,避免超时检查带来的额外操作 ) def test_foo(x: int): print("running test_foo") assert False
这样测试就只会执行一次。
3. 测试执行两次的原因
当测试断言失败时,Hypothesis默认会重新运行一次失败的测试用例,目的是验证这个失败是稳定可复现的,不是偶然因素导致的。这个“复现验证”步骤和max_examples、收缩阶段的设置无关——哪怕你禁用了收缩(phases=[Phase.generate]),这个步骤依然会执行,所以你会看到测试跑了两次。
内容的提问来源于stack exchange,提问作者Rad
相关产品推荐
相关产品推荐

