我想生成一个字典列表,其中所有字典都具有相同的键集。
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': ''}])