Skip to content

declearn.test_utils.assert_json_serializable_dict

Assert that an input is JSON-serializable using declearn hooks.

This function tries to dump the input dict into a JSON string, then to reload it. It does so using declearn.utils.json_pack and json_unpack functions to extend JSON (en|de)coding. It also asserts that the recovered dict is similar to the initial one, using the assert_dict_equal util (which tolerates list- to-tuple conversions induced by JSON).

Parameters:

Name Type Description Default
sdict Dict[str, Any]

Dictionary, the JSON-serializability of which to assert.

required

Raises:

Type Description
AssertionError

If sdict or the JSON-reloaded object is not a dict, or if the latter has different keys and/or values compared to the former.

Exception

Other exceptions may be raised if the JSON encoding (or decoding) operation goes wrong.

Source code in declearn/test_utils/_assertions.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def assert_json_serializable_dict(sdict: Dict[str, Any]) -> None:
    """Assert that an input is JSON-serializable using declearn hooks.

    This function tries to dump the input dict into a JSON string,
    then to reload it. It does so using `declearn.utils.json_pack`
    and `json_unpack` functions to extend JSON (en|de)coding. It
    also asserts that the recovered dict is similar to the initial
    one, using the `assert_dict_equal` util (which tolerates list-
    to-tuple conversions induced by JSON).

    Parameters
    ----------
    sdict: Dict[str, Any]
        Dictionary, the JSON-serializability of which to assert.

    Raises
    ------
    AssertionError
        If `sdict` or the JSON-reloaded object is not a dict, or
        if the latter has different keys and/or values compared
        to the former.
    Exception
        Other exceptions may be raised if the JSON encoding (or
        decoding) operation goes wrong.
    """
    assert isinstance(sdict, dict)
    dump = json.dumps(sdict, default=json_pack)
    load = json.loads(dump, object_hook=json_unpack)
    assert isinstance(load, dict)
    assert_dict_equal(load, sdict)