diff --git a/rero_ils/modules/documents/api.py b/rero_ils/modules/documents/api.py index 2336e83a0e..bdfeddea68 100644 --- a/rero_ils/modules/documents/api.py +++ b/rero_ils/modules/documents/api.py @@ -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') diff --git a/tests/ui/documents/test_documents_api.py b/tests/ui/documents/test_documents_api.py index ff7416b4a0..9fbb69262b 100644 --- a/tests/ui/documents/test_documents_api.py +++ b/tests/ui/documents/test_documents_api.py @@ -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