Repository: scieloorg/catalogmanager

Issue:
Incluir no registro de attachments as propriedades do arquivo
Para retornar os ativos digitais, foi detectado a falta do content_type. Para solucionar isso, precisamos armazenar este dados, explicitamente.

Relacionado com #2

Comments:

Patch:
diff --git a/catalog_persistence/databases.py b/catalog_persistence/databases.py
index 954921e..9dd6f9a 100644
--- a/catalog_persistence/databases.py
+++ b/catalog_persistence/databases.py
@@ -55,16 +55,13 @@ class BaseDBManager(metaclass=abc.ABCMeta):
     def list_attachments(self, id) -> list:
         return NotImplemented
 
-    @abc.abstractmethod
-    def attachment_exists(self, id, file_id) -> bool:
-        return NotImplemented
-
 
 class InMemoryDBManager(BaseDBManager):
 
     def __init__(self, **kwargs):
         self._database_name = kwargs['database_name']
         self._attachments_key = 'attachments'
+        self._attachments_properties_key = 'attachments_properties'
         self._database = {}
 
     @property
@@ -103,7 +100,7 @@ class InMemoryDBManager(BaseDBManager):
         selector: criterio para selecionar campo com determinados valores
             Ex.: {'type': 'ART'}
         fields: lista de campos para retornar. Ex.: ['name']
-        sort: lista de dict com nome de campo e sua ordenacao. [{'name': 'asc'}]
+        sort: lista de dict com nome de campo e sua ordenacao.[{'name': 'asc'}]
 
         Retorno:
         Lista de registros de documento registrados na base de dados
@@ -141,6 +138,18 @@ class InMemoryDBManager(BaseDBManager):
             content_properties['content_size']
         self.database.update({id: doc})
 
+    def _add_attachment_properties(self, record, file_id, file_properties):
+        """
+        """
+        if not record.get(self._attachments_properties_key):
+            record[self._attachments_properties_key] = {}
+        if not record[self._attachments_properties_key].get(file_id):
+            record[self._attachments_properties_key][file_id] = {}
+
+        record[self._attachments_properties_key][file_id].update(
+            file_properties)
+        return record
+
     def get_attachment(self, id, file_id):
         doc = self.read(id)
         if (doc.get(self._attachments_key) and
@@ -152,15 +161,13 @@ class InMemoryDBManager(BaseDBManager):
         doc = self.read(id)
         return list(doc.get(self._attachments_key, {}).keys())
 
-    def attachment_exists(self, id, file_id):
-        return file_id in self.list_attachments(id)
-
 
 class CouchDBManager(BaseDBManager):
 
     def __init__(self, **kwargs):
         self._database_name = kwargs['database_name']
         self._attachments_key = '_attachments'
+        self._attachments_properties_key = 'attachments_properties'
         self._database = None
         self._db_server = couchdb.Server(kwargs['database_uri'])
         self._db_server.resource.credentials = (
@@ -215,7 +222,7 @@ class CouchDBManager(BaseDBManager):
         selector: criterio para selecionar campo com determinados valores
             Ex.: {'type': 'ART'}
         fields: lista de campos para retornar. Ex.: ['name']
-        sort: lista de dict com nome de campo e sua ordenacao. [{'name': 'asc'}]
+        sort: lista de dict com nome de campo e sua ordenacao.[{'name': 'asc'}]
 
         Retorno:
         Lista de registros de documento registrados na base de dados
@@ -225,7 +232,10 @@ class CouchDBManager(BaseDBManager):
             'fields': fields,
             'sort': sort,
         }
-        return [dict(document) for document in self.database.find(selection_criteria)]
+        return [
+            dict(document)
+            for document in self.database.find(selection_criteria)
+        ]
 
     def put_attachment(self, id, file_id, content, content_properties):
         """
@@ -241,6 +251,18 @@ class CouchDBManager(BaseDBManager):
             content_type=content_properties.get('content_type')
         )
 
+    def _add_attachment_properties(self, record, file_id, file_properties):
+        """
+        """
+        if not record.get(self._attachments_properties_key):
+            record[self._attachments_properties_key] = {}
+        if not record[self._attachments_properties_key].get(file_id):
+            record[self._attachments_properties_key][file_id] = {}
+
+        record[self._attachments_properties_key][file_id].update(
+            file_properties)
+        return record
+
     def get_attachment(self, id, file_id):
         doc = self.read(id)
         attachment = self.database.get_attachment(doc, file_id)
@@ -252,9 +274,6 @@ class CouchDBManager(BaseDBManager):
         doc = self.read(id)
         return list(doc.get(self._attachments_key, {}).keys())
 
-    def attachment_exists(self, id, file_id):
-        return file_id in self.list_attachments(id)
-
 
 class DatabaseService:
     """
@@ -371,7 +390,7 @@ class DatabaseService:
         selector: criterio para selecionar campo com determinados valores
             Ex.: {'type': 'ART'}
         fields: lista de campos para retornar. Ex.: ['name']
-        sort: lista de dict com nome de campo e sua ordenacao. [{'name': 'asc'}]
+        sort: lista de dict com nome de campo e sua ordenacao.[{'name': 'asc'}]
 
         Retorno:
         Lista de registros de documento registrados na base de dados
@@ -403,6 +422,11 @@ class DatabaseService:
             'content': document['content'],
             'created_date': document['created_date']
         }
+        document_record = self.db_manager._add_attachment_properties(
+                document_record,
+                file_id,
+                file_properties
+            )
         self.update(document_id, document_record)
 
     def get_attachment(self, document_id, file_id):


Test patch:
diff --git a/catalog_persistence/tests/test_databases.py b/catalog_persistence/tests/test_databases.py
index 9916c25..46ef971 100644
--- a/catalog_persistence/tests/test_databases.py
+++ b/catalog_persistence/tests/test_databases.py
@@ -181,9 +181,10 @@ def test_put_attachment_to_document(setup, database_service, xml_test):
         article_record['document_id'],
         article_record
     )
+    file_id = "href_file"
     database_service.put_attachment(
         document_id=article_record['document_id'],
-        file_id="href_file",
+        file_id=file_id,
         content=xml_test.encode('utf-8'),
         file_properties={
             'content_type': "text/xml",
@@ -195,17 +196,16 @@ def test_put_attachment_to_document(setup, database_service, xml_test):
         database_service.db_manager.database[article_record['document_id']]
     )
     assert record_check is not None
-    assert database_service.db_manager.attachment_exists(
-        article_record['document_id'],
-        "href_file"
+    assert file_id in database_service.db_manager.list_attachments(
+        article_record['document_id']
     )
 
 
 @patch.object(DatabaseService, 'update')
 def test_put_attachment_to_document_update(mocked_update,
-                                                    setup,
-                                                    database_service,
-                                                    xml_test):
+                                           setup,
+                                           database_service,
+                                           xml_test):
     article_record = get_article_record({'Test': 'Test9'})
     database_service.register(
         article_record['document_id'],
@@ -226,15 +226,23 @@ def test_put_attachment_to_document_update(mocked_update,
         'document_id': record['document_id'],
         'document_type': record['document_type'],
         'content': record['content'],
-        'created_date': record['created_date']
+        'created_date': record['created_date'],
+        database_service.db_manager._attachments_properties_key:
+            {
+                attachment_id:
+                {
+                    'content_type': "text/xml",
+                    'content_size': len(xml_test)
+                }
+            }
     }
     mocked_update.assert_called_with(
         article_record['document_id'], document_record)
 
 
 def test_put_attachment_to_document_update_dates(setup,
-                                        database_service,
-                                        xml_test):
+                                                 database_service,
+                                                 xml_test):
     article_record = get_article_record({'Test': 'Test9'})
     database_service.register(
         article_record['document_id'],
@@ -441,3 +449,26 @@ def test_sort_result():
     expected.append({'name': 'Ana', 'num': 200, 'type': 'B'})
     got = sort_results(results, sort)
     assert expected == got
+
+
+def test_add_attachment_properties(setup, database_service, xml_test):
+    expected = {
+        database_service.db_manager._attachments_properties_key:
+            {
+                'href_file':
+                {
+                    'content_type': "text/xml",
+                    'content_size': len(xml_test)
+                }
+            }
+        }
+    file_properties = {
+            'content_type': "text/xml",
+            'content_size': len(xml_test)
+        }
+    record = {}
+    assert expected == database_service.db_manager._add_attachment_properties(
+            record,
+            'href_file',
+            file_properties
+        )