tests: add strongly-typed JSON wrappers
authorSimon Marchi <simon.marchi@efficios.com>
Thu, 21 Sep 2023 16:29:47 +0000 (12:29 -0400)
committerPhilippe Proulx <eeppeliteloop@gmail.com>
Fri, 20 Oct 2023 23:29:14 +0000 (19:29 -0400)
commitf3760aea83e0c7593f89510c25424723f31b804a
treeec09deb19d4b742cc83d4a446e04ec0fad04e178
parent0ac40cd4cd6b16ecd99fbab2f51269cfdf59e78e
tests: add strongly-typed JSON wrappers

When using the result of `json.load` as-is, the returned values are not
strongly-typed, so it is up to the code to check that values are of the
expected type.  To facilitate this introduce small wrappers around that,
for objects and arrays, to add automatic type-checking when accessing
children.

    # Obtain the child of an object with type check
    obj: tjson.ObjVal = ...
    child = obj.at("child-key", tjson.BoolVal)

    # Iterate on children of an array with type check
    arr: tjson.ArrayVal = ...
    for integers in arr.iter(tjson.IntVal):
      ...

These expressions throw TypeError if the children are not of the
expected type. `tjson.ArrayVal` and `tjson.ObjVal` are resp. sequence
and mapping types so that you may still use the typical operators to
disable type checking:

    obj: tjson.ObjVal = ...
    child = obj["child-key"]

    arr: tjson.ArrayVal = ...
    for integers in arr:
      ...

The wrappers also help generate relatively precise error messages, by
recording the path to each object, and outputting it in jq filter
format.  For instance:

    TypeError: `.[1].traces[0].path`: expecting a string value

    KeyError: `.[1].traces[0]`: no value has the key `path`

Change-Id: Ic6fbb2de5731851af3b90a476af009315f829665
Signed-off-by: Simon Marchi <simon.marchi@efficios.com>
Signed-off-by: Philippe Proulx <eeppeliteloop@gmail.com>
Reviewed-on: https://review.lttng.org/c/babeltrace/+/10909
Tested-by: jenkins <jenkins@lttng.org>
tests/utils/python/tjson.py [new file with mode: 0644]
This page took 0.024071 seconds and 4 git commands to generate.