Skip to content

Commit

Permalink
document: fix contribution error
Browse files Browse the repository at this point in the history
We need to prevent internal server error when MEF resolver returns
no metadata for the linked agent.

* Updates `replace_refs` method.
* Writes some tests.

Co-Authored-by: Lauren-D <[email protected]>
  • Loading branch information
lauren-d committed Oct 25, 2022
1 parent dcd9711 commit a2c9d16
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
7 changes: 6 additions & 1 deletion rero_ils/modules/documents/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,16 @@ def get_document_pids_by_issn(cls, issn_number: str):
def replace_refs(self):
"""Replace $ref with real data."""
from ..contributions.api import Contribution
for contribution in self.get('contribution', []):
contributions = self.get('contribution', [])
# we need to iterate over a copy of the list if we want to remove an
# element on the original list
for contribution in list(contributions):
if ref := contribution['agent'].get('$ref'):
agent, _ = Contribution.get_record_by_ref(ref)
if agent:
contribution['agent'] = agent
else:
contributions.remove(contribution)
for subjects in ['subjects', 'subjects_imported']:
for subject in self.get(subjects, []):
subject_ref = subject.get('$ref')
Expand Down
33 changes: 33 additions & 0 deletions tests/ui/documents/test_documents_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,36 @@ def test_document_indexing(document, export_document):
document['title'].pop(-1)
document['title'][0]['mainTitle'][1]['value'] = orig_title
document.update(document, dbcommit=True, reindex=True)


def test_document_replace_refs(document):
"""Test document replace refs."""
data = document.replace_refs()
assert len(data.get('contribution')) == 1

# add wrong referenced contribution agent
contributions = document.get('contribution', [])
contributions.append({
'agent': {
'type': 'bf:Person',
'$ref': 'https://mef.rero.ch/api/agents/iderf/WRONGIDREF'
},
'role': [
'aut'
]
})
data = document.replace_refs()
assert len(data.get('contribution')) == 1

# add MEF contribution agent
contributions.append({
'agent': {
'type': 'bf:Person',
'$ref': 'https://mef.rero.ch/api/agents/rero/A017671081'
},
'role': [
'aut'
]
})
data = document.replace_refs()
assert len(data.get('contribution')) == 2

0 comments on commit a2c9d16

Please sign in to comment.