使用相同的键生成字典列表

时间:2019-05-18 01:36:07

标签: python python-hypothesis

我想生成一个字典列表,其中所有字典都具有相同的键集。

import json
import hypothesis
from hypothesis import strategies as st


@st.composite
def list_of_dicts_with_keys_matching(draw,dicts=st.dictionaries(st.text(), st.text())):
    mapping = draw(dicts)

    return st.lists(st.fixed_dictionaries(mapping))

@hypothesis.given(list_of_dicts_with_keys_matching())
def test_simple_json_strategy(obj):
    dumped = json.dumps(obj)
    assert isinstance(obj, list)
    assert json.dumps(json.loads(dumped)) == dumped
  

TypeError:LazyStrategy类型的对象不可JSON序列化

我该如何解决?

编辑:第二次尝试:

import string

import pytest
import hypothesis
import hypothesis.strategies as st


@st.composite
def list_of_dicts_with_keys_matching(draw, keys=st.text(), values=st.text()):
    shared_keys = draw(st.lists(keys, min_size=3))
    return draw(st.lists(st.dictionaries(st.sampled_from(shared_keys), values, min_size=1)))


@hypothesis.given(list_of_dicts_with_keys_matching())
def test_shared_keys(dicts):
    assert len({frozenset(d.keys()) for d in dicts}) in [0, 1]


# Falsifying example: test_shared_keys(dicts=[{'': ''}, {'0': ''}])

1 个答案:

答案 0 :(得分:0)

您在draw(...)中缺少return draw(st.lists(st.fixed_dictionaries(mapping)))

但是,这将导致您遇到第二个问题-st.fixed_dictionaries将键映射到价值策略,但是mapping这里是{{1} }。也许:

Dict[str, str]

更新:上面的代码片段将从一个共享集中提取各种密钥。对于所有字典相同的键,我会写:

@st.composite
def list_of_dicts_with_keys_matching(draw, keys=st.text(), values=st.text()):
    shared_keys = draw(st.lists(keys, min_size=3))
    return draw(st.lists(st.dictionaries(st.sampled_from(shared_keys), values)))
相关问题