带有可选键的字典策略

Strategy for dictionary with optional keys

目前我正在使用假设 fixed_dictionaries 策略来生成一个字典,其中包含对我的应用程序有效的特定键和数据类型。我需要一种策略来生成这个固定字典以及其他删除了特定键的字典。或具有特定最小键集和可选附加键的字典,最好以产生这些可选键的各种组合的方式。

这是需要验证的 json 架构示例,包含 2 个可选字段。我想为此架构生成所有可能的有效数据。

'user_stub': {
    '_id':        {'type': 'string'},
    'username':   {'type': 'string'},
    'social':     {'type': 'string'},
    'api_name':   {'type':     'string',
                   'required': False},
    'profile_id': {'type':     'integer',
                   'required': False},
}

这是我想出的,但它是不正确的,因为它保留了键,但使用 None 作为值,而我希望键被删除。

return st.fixed_dictionaries({
    '_id':        st.text(),
    'username':   st.text(),
    'social':     st.text(),
    'api_name':   st.one_of(st.none(),
                            st.text()),
    'profile_id': st.one_of(st.none(),
                            st.integers()),
})

编辑:更新复合策略 ->

似乎最好根据返回的数据类型分离额外的可选字典,否则可能会得到具有不匹配值的键。

@st.composite
def generate_data(draw):
    base_data = st.fixed_dictionaries({
        '_id':      st.text(),
        'username': st.text(),
        'social':   st.text(),
    })
    optional_strs = st.dictionaries(
        keys=st.just('api_name'),
        values=st.text()
    )
    optional_ints = st.dictionaries(
        keys=st.just('profile_id'),
        values=st.integers()
    )

    b = draw(base_data)
    s = draw(optional_strs)
    i = draw(optional_ints)
    return {**b, **s, **i}  # noice

fixed_dictionaries strategy for the required entries and from a dictionaries strategy for the optional ones. Then combine them into one dictionary by merging 中抽取。

您可以在测试中执行此操作,也可以创建一个 composite strategy 来为您执行此操作。

das-g 提供了可行的解决方案!

另一种方法是

fixed_dictionaries(dict(
    required=text(),
    optional=none()|text(),  # note None first, for shrinking
)).map(
    lambda d: {k: v for k, v in d.items() if v is not None}
)