目前我正在使用假设 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},
}
Run Code Online (Sandbox Code Playgroud)
这是我想出的,但它是不正确的,因为它保留了键,但使用 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()),
})
Run Code Online (Sandbox Code Playgroud)
编辑:更新复合策略 ->
似乎最好根据返回的数据类型分离额外的可选字典,否则可能会得到值不匹配的键。
@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 …
Run Code Online (Sandbox Code Playgroud)