Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise exception if trying to set a dict with no id as property value #193

Merged
merged 2 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading