代码之家  ›  专栏  ›  技术社区  ›  Hatshepsut

生成具有相同键的听写列表

  •  0
  • Hatshepsut  · 技术社区  · 6 年前

    我想生成一个所有听写都有相同键集的听写列表。

    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
    

    类型错误: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': ''}])
    
    0 回复  |  直到 6 年前
        1
  •  0
  •   Zac Hatfield-Dodds    6 年前

    你错过了 draw(...) 在里面 return draw(st.lists(st.fixed_dictionaries(mapping))) .

    但是,这将导致第二个问题- 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)))
    

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

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