diff --git a/pyerrors/input/json.py b/pyerrors/input/json.py index ca3fb0d2..1273db0f 100644 --- a/pyerrors/input/json.py +++ b/pyerrors/input/json.py @@ -59,6 +59,8 @@ def create_json_string(ol, description='', indent=1): 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(',') @@ -216,6 +218,11 @@ def create_json_string(ol, description='', indent=1): 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. diff --git a/tests/json_io_test.py b/tests/json_io_test.py index dafaaa41..428704fc 100644 --- a/tests/json_io_test.py +++ b/tests/json_io_test.py @@ -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]')