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

如何用Hypothesis生成值类型各异的Python字典?

如何用Hypothesis生成值含多种不同类型的字典

嘿,这个问题我之前做测试的时候也碰到过!确实st.dictionaries没有像st.lists那样的unique_by参数来约束值的类型,直接生成很容易出现值类型单一的情况。这里给你几个实用的解决方案,按简洁度和效率排序:

方案一:先生成多类型值列表,再映射为字典

这个方法利用st.lists的unique_by先确保我们有至少两种不同类型的值,再基于这些值生成字典,既高效又直观:

from hypothesis import given
import hypothesis.strategies as st

@given(
    # 第一步:生成至少2个不同类型的非空、非bool值的列表
    st.lists(
        st.from_type(type)
        .flatmap(st.from_type)
        .filter(lambda x: not isinstance(x, (type(None), bool))),
        min_size=2,
        unique_by=lambda x: type(x)  # 保证每个元素类型唯一
    ).flatmap(lambda values: 
        # 第二步:基于这个多类型值列表生成字典
        st.dictionaries(
            st.text(min_size=1, max_size=10),
            st.sampled_from(values),  # 从已有的多类型值里选,确保类型多样性
            min_size=2,
            max_size=len(values)  # 可选:限制字典大小不超过值列表的长度
        )
    )
)
def test_dict_with_multiple_value_types(dictionary):
    # 可选验证:确保值的类型数量至少为2
    assert len({type(v) for v in dictionary.values()}) >= 2

方案二:直接过滤生成后的字典

如果不想嵌套太多策略,也可以直接对生成的字典做过滤,不过要注意这种方法可能会降低Hypothesis的生成效率(因为会丢弃很多不符合条件的样本):

from hypothesis import given
import hypothesis.strategies as st

@given(
    st.dictionaries(
        st.text(min_size=1, max_size=10),
        st.from_type(type)
        .flatmap(st.from_type)
        .filter(lambda x: not isinstance(x, (type(None), bool))),
        min_size=2
    ).filter(lambda d: len({type(v) for v in d.values()}) >= 2)  # 过滤出类型数≥2的字典
)
def test_dict_with_multiple_value_types(dictionary):
    assert len({type(v) for v in dictionary.values()}) >= 2

方案三:手动构造多类型键值对再扩展

这种方法更“手动”,先强制生成两个不同类型的键值对,再额外添加任意键值对,适合需要更精细控制的场景:

from hypothesis import given
import hypothesis.strategies as st

@given(
    # 先生成两个类型不同、键不重复的键值对
    st.tuples(
        st.text(min_size=1, max_size=10),
        st.from_type(type).flatmap(st.from_type).filter(lambda x: not isinstance(x, (type(None), bool))),
        st.text(min_size=1, max_size=10).filter(lambda k: k != st.tuples[0]),
        st.from_type(type).flatmap(st.from_type).filter(lambda x: not isinstance(x, (type(None), bool)) and type(x) != type(st.tuples[1]))
    ).flatmap(lambda parts: 
        # 生成额外的键值对(可选),然后合并到初始的两个键值对中
        st.dictionaries(
            st.text(min_size=1, max_size=10).filter(lambda k: k not in parts[:2]),
            st.from_type(type).flatmap(st.from_type).filter(lambda x: not isinstance(x, (type(None), bool))),
            min_size=0
        ).map(lambda extra: {parts[0]: parts[1], parts[2]: parts[3]} | extra)
    )
)
def test_dict_with_multiple_value_types(dictionary):
    assert len({type(v) for v in dictionary.values()}) >= 2

为什么原来的方法会生成单一类型字典?

因为st.dictionaries的value策略是独立生成每个值的,即使你的value策略支持多种类型,Hypothesis也可能随机生成多个同类型的值。而st.lists的unique_by可以直接约束元素的类型唯一性,所以我们可以借助这个特性来间接实现字典值的类型多样性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:48:41