From df66defbf88996a62d93295bbbeb60e0211829db Mon Sep 17 00:00:00 2001 From: simleo Date: Thu, 5 Sep 2024 13:02:09 +0200 Subject: [PATCH 1/2] raise exc if trying to set a dict with no id as prop value --- rocrate/model/entity.py | 3 +++ test/test_model.py | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/rocrate/model/entity.py b/rocrate/model/entity.py index 22e69a55..fc23eada 100644 --- a/rocrate/model/entity.py +++ b/rocrate/model/entity.py @@ -102,6 +102,9 @@ def __setitem__(self, key: str, value): if key.startswith("@"): raise KeyError(f"cannot set '{key}'") values = value if isinstance(value, list) else [value] + for v in values: + if isinstance(v, dict) and "@id" not in v: + raise ValueError(f"no @id in {v}") ref_values = [{"@id": _.id} if isinstance(_, Entity) else _ for _ in values] self._jsonld[key] = ref_values if isinstance(value, list) else ref_values[0] diff --git a/test/test_model.py b/test/test_model.py index 4465ecee..f6e18af0 100644 --- a/test/test_model.py +++ b/test/test_model.py @@ -363,6 +363,11 @@ def test_entity_as_mapping(tmpdir, helpers): } crate_dir = tmpdir / "in_crate" crate_dir.mkdir() + with open(crate_dir / helpers.METADATA_FILE_NAME, "wt") as f: + json.dump(metadata, f, indent=4) + with pytest.raises(ValueError): + crate = ROCrate(crate_dir) + del metadata["@graph"][2]["badProp"] with open(crate_dir / helpers.METADATA_FILE_NAME, "wt") as f: json.dump(metadata, f, indent=4) crate = ROCrate(crate_dir) @@ -411,6 +416,7 @@ def test_entity_as_mapping(tmpdir, helpers): "application/json", "https://www.json.org", } + correction._jsonld["badProp"] = {"k": "v"} with pytest.raises(ValueError): correction["badProp"] From 1391dc370510e61dfaad3e473a6703ee714f0643 Mon Sep 17 00:00:00 2001 From: simleo Date: Wed, 11 Sep 2024 17:06:22 +0200 Subject: [PATCH 2/2] update test_entity_as_mapping --- test/test_model.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/test_model.py b/test/test_model.py index f6e18af0..c452e211 100644 --- a/test/test_model.py +++ b/test/test_model.py @@ -365,7 +365,7 @@ def test_entity_as_mapping(tmpdir, helpers): crate_dir.mkdir() with open(crate_dir / helpers.METADATA_FILE_NAME, "wt") as f: json.dump(metadata, f, indent=4) - with pytest.raises(ValueError): + with pytest.raises(ValueError): # due to "badProp", which has no "@id" crate = ROCrate(crate_dir) del metadata["@graph"][2]["badProp"] with open(crate_dir / helpers.METADATA_FILE_NAME, "wt") as f: @@ -416,7 +416,9 @@ def test_entity_as_mapping(tmpdir, helpers): "application/json", "https://www.json.org", } - correction._jsonld["badProp"] = {"k": "v"} + with pytest.raises(ValueError): + correction["badProp"] = {"k": "v"} # value has no "@id" + correction._jsonld["badProp"] = {"k": "v"} # force set using _jsonld with pytest.raises(ValueError): correction["badProp"]