Skip to content

Commit

Permalink
Merge pull request #193 from simleo/handle_set_prop_value_no_id
Browse files Browse the repository at this point in the history
Raise exception if trying to set a dict with no id as property value
  • Loading branch information
elichad authored Sep 11, 2024
2 parents 352deab + 1391dc3 commit ad8e816
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions rocrate/model/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
8 changes: 8 additions & 0 deletions test/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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): # 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:
json.dump(metadata, f, indent=4)
crate = ROCrate(crate_dir)
Expand Down Expand Up @@ -411,6 +416,9 @@ def test_entity_as_mapping(tmpdir, helpers):
"application/json",
"https://www.json.org",
}
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"]

Expand Down

0 comments on commit ad8e816

Please sign in to comment.