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

如何在Hypothesis中编写使用共享维度数组的测试生成策略

解决方案

直接使用Hypothesis内置的shared策略即可实现你期望的写法,无需编写额外的复合策略样板代码,完整可运行示例如下:

from hypothesis import given, shared, integers
from hypothesis.extra.numpy import arrays
from numpy import float32

# 用shared包装共享维度策略,指定key保证唯一匹配
batch_size = shared(integers(min_value=1, max_value=512), key="test_batch_size")
hidden_state_size = shared(integers(min_value=1, max_value=10_000), key="test_hidden_size")

@given(
    arrays(dtype=float32, shape=(batch_size, integers(min_value=1, max_value=10_000))),
    arrays(dtype=float32, shape=(batch_size, hidden_state_size)),
    arrays(dtype=float32, shape=(batch_size, hidden_state_size, integers(min_value=1, max_value=10_000))),
)
def test_code(input_array, initial_state, encoder_state):
    # 维度一致性校验,运行时自动满足
    assert input_array.shape[0] == initial_state.shape[0] == encoder_state.shape[0]
    assert initial_state.shape[1] == encoder_state.shape[1]
    # 你的测试逻辑
    ...

实现说明

  • shared策略的作用是保证同一测试用例的单次执行中,所有引用同个shared实例的位置都会拿到相同的生成值,刚好适配多张量共享维度的场景。
  • Hypothesis的arrays生成器的shape参数本身就支持传入整数策略作为维度值,不需要提前转为int类型。

注意事项

  • 建议给shared策略指定显式的key参数,避免Hypothesis自动推导key时出现匹配错误,尤其是跨测试复用策略定义时可以保证逻辑稳定,这也是多数人调试shared策略失败的核心原因。
  • 若运行报错,先升级Hypothesis到6.0及以上版本,低版本对shape参数传入策略的支持存在兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:06:07