Skip to content

Commit

Permalink
Merge pull request #123 from ResearchObject/fix_entity_getitem
Browse files Browse the repository at this point in the history
Fix Entity.__getitem__
  • Loading branch information
simleo authored May 5, 2022
2 parents 854ba36 + 8689c76 commit 08d3c6d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
14 changes: 12 additions & 2 deletions rocrate/model/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,20 @@ def _empty(self):

def __getitem__(self, key):
v = self._jsonld[key]
if v is None or isinstance(v, str) or key.startswith("@"):
if v is None or key.startswith("@"):
return v
values = v if isinstance(v, list) else [v]
deref_values = [self.crate.dereference(_["@id"], _["@id"]) for _ in values]
deref_values = []
for entry in values:
if isinstance(entry, dict):
try:
id_ = entry["@id"]
except KeyError:
raise ValueError(f"no @id in {entry}")
else:
deref_values.append(self.crate.get(id_, id_))
else:
deref_values.append(entry)
return deref_values if isinstance(v, list) else deref_values[0]

def __setitem__(self, key: str, value):
Expand Down
27 changes: 26 additions & 1 deletion test/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,10 +317,23 @@ def test_entity_as_mapping(tmpdir, helpers):
{"@id": "ro-crate-metadata.json",
"@type": "CreativeWork",
"about": {"@id": "./"},
"encodingFormat": [
"application/json",
{"@id": "https://www.json.org"},
],
"conformsTo": {"@id": "https://w3id.org/ro/crate/1.1"}},
{"@id": "./",
"@type": "Dataset",
"correction": [
"Fixed typo.",
{"@id": "#correction"},
"http://example.org/correction",
],
"author": {"@id": orcid}},
{"@id": "#correction",
"@type": "CorrectionComment",
"badProp": {"k": "v"},
"text": "Previous version was ugly."},
{"@id": orcid,
"@type": "Person",
"name": None,
Expand All @@ -334,7 +347,7 @@ def test_entity_as_mapping(tmpdir, helpers):
json.dump(metadata, f, indent=4)
crate = ROCrate(crate_dir)
person = crate.dereference(orcid)
exp_len = len(metadata["@graph"][2])
exp_len = len([_ for _ in metadata["@graph"] if _["@id"] == orcid][0])
assert len(person) == exp_len
assert len(list(person)) == exp_len
assert set(person) == set(person.keys()) == {"@id", "@type", "name", "givenName", "familyName"}
Expand Down Expand Up @@ -368,3 +381,15 @@ def test_entity_as_mapping(tmpdir, helpers):
assert twin == person
assert Person(crate, orcid) != person
assert crate.root_dataset["author"] is person
correction = crate.get("#correction")
assert set(crate.root_dataset["correction"]) == {
"Fixed typo.",
correction,
"http://example.org/correction"
}
assert set(crate.metadata["encodingFormat"]) == {
"application/json",
"https://www.json.org",
}
with pytest.raises(ValueError):
correction["badProp"]

0 comments on commit 08d3c6d

Please sign in to comment.