【问题标题】:Generate list of dicts with the same keys生成具有相同键的字典列表
【发布时间】:2019-10-05 07:27:33
【问题描述】:

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

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

【问题讨论】:

    标签: python python-hypothesis


    【解决方案1】:

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

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

    更新:上面的 sn-p 将从共享集中提取不同的键。对于所有字典的相同键,我会写:

    @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}
        )))
    

    【讨论】:

    • 这个答案不太管用。例如,它产生[{'': ''}, {'0': ''}],它没有共享密钥。
    猜你喜欢
    • 2019-11-19
    • 2019-11-04
    • 2019-03-12
    • 2021-12-07
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多