我有一个使用
composite
构建的自定义策略,它在内部借鉴了 text
策略。
调试另一个错误(
FailedHealthCheck.data_too_large
)我意识到从text
策略中提取可以导致我的复合策略被调用的频率大约是预期的两倍。
我能够重现以下最小示例:
@hypothesis.strategies.composite
def my_custom_strategy(draw, n):
"""Strategy to generate lists of N strings"""
trace("a")
value = [draw(hypothesis.strategies.text(max_size=256)) for _ in range(n)]
trace("b")
return value
@given(my_custom_strategy(100))
def test_my_custom_strategy(value):
assert len(value) == 100
assert all(isinstance(v, str) for v in value)
在这个场景中,
trace("a")
被调用了206次,而trace("b")
只被调用了100次。这些数字在运行中是一致的。
更有问题的是,我调用 text() 的次数越多,差距就越大,而且是超线性的。当
n=200
时,trace("a")
被调用了305次。 n=400
,984次。 n=500
或更大,测试可靠地暂停,然后在第 11 次迭代后完成(只有 11 次迭代,而不是 100 次!)
这里发生了什么?