0

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

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': ''}])
4

1 回答 1

0

你错过了draw(...)in return draw(st.lists(st.fixed_dictionaries(mapping)))

但是,这将导致您遇到第二个问题 -st.fixed_dictionaries将键映射到values 的策略,但mapping这里将是一个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)))

更新:上面的代码片段将从共享集中绘制不同的键。对于所有字典的相同键,我会写:

@st.composite
def list_of_dicts_with_keys_matching(draw, keys=st.text(), values=st.text()):
    shared_keys = draw(st.sets(keys))
    return draw(st.lists(st.fixed_dictionaries(
        {k: values for k in shared_keys}
    )))
于 2019-05-20T02:55:22.917 回答