Esempio n. 1
0
def test_context_serialization():
    def custom_resolver(name):
        if name == 'SBKImpl':
            return SBKImpl

    test_resolvers = [custom_resolver] + cirq.DEFAULT_RESOLVERS

    sbki_empty = SBKImpl('sbki_empty')
    assert_json_roundtrip_works(sbki_empty, resolvers=test_resolvers)

    sbki_list = SBKImpl('sbki_list', data_list=[sbki_empty, sbki_empty])
    assert_json_roundtrip_works(sbki_list, resolvers=test_resolvers)

    sbki_tuple = SBKImpl('sbki_tuple', data_tuple=(sbki_list, sbki_list))
    assert_json_roundtrip_works(sbki_tuple, resolvers=test_resolvers)

    sbki_dict = SBKImpl('sbki_dict',
                        data_dict={
                            'a': sbki_tuple,
                            'b': sbki_tuple
                        })
    assert_json_roundtrip_works(sbki_dict, resolvers=test_resolvers)

    sbki_json = str(cirq.to_json(sbki_dict))
    # There should be exactly one context item for each previous SBKImpl.
    assert sbki_json.count('"cirq_type": "_SerializedContext"') == 4
    # There should be exactly two key items for each of sbki_(empty|list|tuple),
    # plus one for the top-level sbki_dict.
    assert sbki_json.count('"cirq_type": "_SerializedKey"') == 7
    # The final object should be a _SerializedKey for sbki_dict.
    final_obj_idx = sbki_json.rfind('{')
    final_obj = sbki_json[final_obj_idx:sbki_json.find('}', final_obj_idx) + 1]
    assert (final_obj == """{
      "cirq_type": "_SerializedKey",
      "key": "sbki_dict"
    }""")

    list_sbki = [sbki_dict]
    assert_json_roundtrip_works(list_sbki, resolvers=test_resolvers)

    dict_sbki = {'a': sbki_dict}
    assert_json_roundtrip_works(dict_sbki, resolvers=test_resolvers)

    assert sbki_list != json_serialization._SerializedKey(sbki_list)
    sbki_other_list = SBKImpl('sbki_list', data_list=[sbki_list])
    with pytest.raises(
            ValueError,
            match='different objects with the same serialization key'):
        _ = cirq.to_json(sbki_other_list)
Esempio n. 2
0
def test_internal_serializer_types():
    sbki = SBKImpl('test_key')
    test_key = json_serialization._SerializedKey(sbki)
    test_context = json_serialization._SerializedContext(sbki)
    test_serialization = json_serialization._ContextualSerialization(sbki)

    key_json = test_key._json_dict_()
    with pytest.raises(TypeError, match='_from_json_dict_'):
        _ = json_serialization._SerializedKey._from_json_dict_(**key_json)

    context_json = test_context._json_dict_()
    with pytest.raises(TypeError, match='_from_json_dict_'):
        _ = json_serialization._SerializedContext._from_json_dict_(**context_json)

    serialization_json = test_serialization._json_dict_()
    with pytest.raises(TypeError, match='_from_json_dict_'):
        _ = json_serialization._ContextualSerialization._from_json_dict_(**serialization_json)