Skip to content

Commit

Permalink
[Feat] Prevent objects with uuid names to be serialized to json.
Browse files Browse the repository at this point in the history
  • Loading branch information
fjosw committed Nov 20, 2024
1 parent 779dedf commit 5c4f44f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
7 changes: 7 additions & 0 deletions pyerrors/input/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ def _gen_data_d_from_list(ol):
def _gen_cdata_d_from_list(ol):
dl = []
for name in ol[0].cov_names:
if _is_uuid4_hex(name):
raise ValueError("Cannot safely serialize an Obs derived from a Meas object with a uuid as name. Consider recreating the Meas with an explict name.")
ed = {}
ed['id'] = name
ed['layout'] = str(ol[0].covobs[name].cov.shape).lstrip('(').rstrip(')').rstrip(',')
Expand Down Expand Up @@ -216,6 +218,11 @@ def _jsonifier(obj):
return json.dumps(d, indent=indent, ensure_ascii=False, default=_jsonifier, write_mode=json.WM_COMPACT)


def _is_uuid4_hex(s):
uuid4_hex_pattern = re.compile(r'^[0-9a-f]{32}$')
return bool(uuid4_hex_pattern.match(s))


def dump_to_json(ol, fname, description='', indent=1, gz=True):
"""Export a list of Obs or structures containing Obs to a .json(.gz) file.
Dict keys that are not JSON-serializable such as floats are converted to strings.
Expand Down
11 changes: 11 additions & 0 deletions tests/json_io_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,14 @@ def assert_equal_Obs(to, ro):
print(kw, "does not match.")
return False
return True


def test_meas_uuid(tmp_path):
meas = pe.Meas(0.3, 0.2)

for obs in [meas, meas + 1, meas * pe.pseudo_Obs(0.1, 0.001, "obs|r1")]:
with pytest.raises(ValueError):
jsonio.dump_to_json([obs], "test_file", indent=1, description='[This file should not be writable]')

name_meas = pe.Meas(0.3, 0.2, name="my name")
jsonio.dump_to_json([name_meas], "test_file", indent=1, description='[This file should be writable]')

0 comments on commit 5c4f44f

Please sign in to comment.