Hypothesis中禁用测试收缩阶段的合规方法(无需导入私有模块)
I need to disable the shrinking phase for a test case, and currently I'm implementing it with this code:
from hypothesis import given, settings, strategies as st from hypothesis._settings import Phase @settings(report_multiple_bugs=False, phases=list(Phase)[:-1]) @given(my_composite_generator()) def test_legacy_rack_conversion(input): assert_stuff_about(input)
But I don't want to import private content (like hypothesis._settings.Phase) that starts with an underscore from the third-party library. Is there a more recommended way to disable the shrinking phase?
Answer:
Great call avoiding private APIs—this keeps your code way more resilient to Hypothesis updates! You don’t need to touch that underscore-prefixed Phase enum at all, since Hypothesis exposes a public way to control test phases using string sets.
Here’s the clean, recommended approach:
from hypothesis import given, settings, strategies as st @settings(report_multiple_bugs=False, phases=settings.default.phases - {"shrink"}) @given(my_composite_generator()) def test_legacy_rack_conversion(input): assert_stuff_about(input)
Let me break this down for you:
settings.default.phasesreturns the default set of enabled phases as human-readable strings (no private enums required).- By subtracting the
"shrink"string from this set, you’re explicitly excluding the shrinking phase while keeping all other default phases active. - This uses Hypothesis’s public, supported API, so you won’t have to worry about your code breaking if the internal
Phaseimplementation changes in future versions.
If you prefer to explicitly list the phases you want to keep instead of subtracting, you can also do this (it achieves the exact same result):
@settings(report_multiple_bugs=False, phases={"explicit", "reuse", "generate", "target"})
These are all the default phases minus the shrinking step.
Either method lets you disable shrinking without relying on private library internals—perfect for maintaining clean, future-proof test code.
内容的提问来源于stack exchange,提问作者mac01021

