Jelajahi Sumber

Review tests; some style check.

Stefano Cossu 7 tahun lalu
induk
melakukan
bd56293138

+ 5 - 5
lakesuperior/endpoints/ldp.py

@@ -9,12 +9,14 @@ import arrow
 from flask import (
         Blueprint, current_app, g, make_response, render_template,
         request, send_file)
-from rdflib.namespace import RDF, XSD
+from rdflib.namespace import XSD
 from rdflib.term import Literal
 
 from lakesuperior.dictionaries.namespaces import ns_collection as nsc
 from lakesuperior.dictionaries.namespaces import ns_mgr as nsm
-from lakesuperior.exceptions import *
+from lakesuperior.exceptions import (ResourceNotExistsError, TombstoneError,
+        ServerManagedTermError, InvalidResourceError, SingleSubjectError,
+        ResourceExistsError, IncompatibleLdpTypeError)
 from lakesuperior.model.ldp_factory import LdpFactory
 from lakesuperior.model.ldp_nr import LdpNr
 from lakesuperior.model.ldp_rs import LdpRs
@@ -398,7 +400,7 @@ def tombstone(uid):
     logger.debug('Deleting tombstone for {}.'.format(uid))
     rsrc = Ldpr(uid)
     try:
-        metadata = rsrc.metadata
+        rsrc.metadata
     except TombstoneError as e:
         if request.method == 'DELETE':
             if e.uid == uid:
@@ -514,8 +516,6 @@ def bitstream_from_req():
 
 
 def _get_bitstream(rsrc):
-    out_headers = std_headers
-
     # @TODO This may change in favor of more low-level handling if the file
     # system is not local.
     return send_file(rsrc.local_path, as_attachment=True,

+ 2 - 1
lakesuperior/model/ldp_factory.py

@@ -11,7 +11,8 @@ from rdflib.namespace import RDF
 
 from lakesuperior import model
 from lakesuperior.dictionaries.namespaces import ns_collection as nsc
-from lakesuperior.exceptions import *
+from lakesuperior.exceptions import (IncompatibleLdpTypeError,
+        InvalidResourceError, ResourceNotExistsError)
 
 
 class LdpFactory:

+ 28 - 20
lakesuperior/model/ldpr.py

@@ -3,7 +3,7 @@ import logging
 from abc import ABCMeta
 from collections import defaultdict
 from itertools import accumulate, groupby
-from pprint import pformat
+#from pprint import pformat
 from uuid import uuid4
 
 import arrow
@@ -18,7 +18,8 @@ from lakesuperior.dictionaries.namespaces import ns_collection as nsc
 from lakesuperior.dictionaries.namespaces import ns_mgr as nsm
 from lakesuperior.dictionaries.srv_mgd_terms import  srv_mgd_subjects, \
         srv_mgd_predicates, srv_mgd_types
-from lakesuperior.exceptions import *
+from lakesuperior.exceptions import (RefIntViolationError,
+        ResourceNotExistsError, ServerManagedTermError, TombstoneError)
 from lakesuperior.model.ldp_factory import LdpFactory
 from lakesuperior.store_layouts.ldp_rs.rsrc_centric_layout import (
         VERS_CONT_LABEL)
@@ -49,8 +50,6 @@ def atomic(fn):
             #if hasattr(self.rdfly.store, '_edits'):
             #    # @FIXME ugly.
             #    self.rdfly._conn.optimize_edits()
-            #import pdb; pdb.set_trace()
-            self.rdfly.store.commit()
             for ev in request.changelog:
                 #self._logger.info('Message: {}'.format(pformat(ev)))
                 self._send_event_msg(*ev)
@@ -278,10 +277,7 @@ class Ldpr(metaclass=ABCMeta):
             ) and (
                 # Only include server managed triples if requested.
                 self._imr_options.get('incl_srv_mgd', True)
-                or (
-                    not t[1] in srv_mgd_predicates
-                    and not (t[1] == RDF.type or t[2] in srv_mgd_types)
-                )
+                or not self._is_trp_managed(t)
             ):
                 out_gr.add(t)
 
@@ -487,7 +483,7 @@ class Ldpr(metaclass=ABCMeta):
         '''
         tstone_trp = set(self.rdfly.extract_imr(self.uid, strict=False).graph)
 
-        ver_rsp = self.version_info.query('''
+        ver_rsp = self.version_info.graph.query('''
         SELECT ?uid {
           ?latest fcrepo:hasVersionLabel ?uid ;
             fcrepo:created ?ts .
@@ -495,8 +491,9 @@ class Ldpr(metaclass=ABCMeta):
         ORDER BY DESC(?ts)
         LIMIT 1
         ''')
+        #import pdb; pdb.set_trace()
         ver_uid = str(ver_rsp.bindings[0]['uid'])
-        ver_trp = set(self.rdfly.get_metadata(self.urn, ver_uid))
+        ver_trp = set(self.rdfly.get_metadata(self.uid, ver_uid).graph)
 
         laz_gr = Graph()
         for t in ver_trp:
@@ -531,7 +528,7 @@ class Ldpr(metaclass=ABCMeta):
 
 
     @atomic
-    def create_version(self, ver_uid):
+    def create_version(self, ver_uid=None):
         '''
         Create a new version of the resource.
 
@@ -553,30 +550,38 @@ class Ldpr(metaclass=ABCMeta):
         '''
         Revert to a previous version.
 
-        NOTE: this will create a new version.
-
         @param ver_uid (string) Version UID.
-        @param backup (boolean) Whether to create a backup copy. Default is
+        @param backup (boolean) Whether to create a backup snapshot. Default is
         true.
         '''
         # Create a backup snapshot.
         if backup:
-            self.create_version(uuid4())
+            self.create_version()
 
-        ver_gr = self.rdfly.get_metadata(self.uid, ver_uid)
+        ver_gr = self.rdfly.extract_imr(self.uid, ver_uid=ver_uid,
+                incl_children=False)
         self.provided_imr = Resource(Graph(), self.urn)
 
         for t in ver_gr.graph:
-            if t[1] not in srv_mgd_predicates and not (
-                t[1] == RDF.type and t[2] in srv_mgd_types
-            ):
+            if not self._is_trp_managed(t):
                 self.provided_imr.add(t[1], t[2])
+            # @TODO Check individual objects: if they are repo-managed URIs
+            # and not existing or tombstones, they are not added.
 
         return self._create_or_replace_rsrc(create_only=False)
 
 
     ## PROTECTED METHODS ##
 
+    def _is_trp_managed(self, t):
+        '''
+        Return whether a triple is server-managed.
+        This is true if one of its terms is in the managed terms list.
+        '''
+        return t[1] in srv_mgd_predicates or (
+                t[1] == RDF.type and t[2] in srv_mgd_types)
+
+
     def _create_or_replace_rsrc(self, create_only=False):
         '''
         Create or update a resource. PUT and POST methods, which are almost
@@ -685,6 +690,9 @@ class Ldpr(metaclass=ABCMeta):
         Perform version creation and return the internal URN.
         '''
         # Create version resource from copying the current state.
+        self._logger.info(
+                'Creating version snapshot {} for resource {}.'.format(
+                    ver_uid, self.uid))
         ver_add_gr = set()
         vers_uid = '{}/{}'.format(self.uid, VERS_CONT_LABEL)
         ver_uid = '{}/{}'.format(vers_uid, ver_uid)
@@ -744,7 +752,7 @@ class Ldpr(metaclass=ABCMeta):
         try:
             type = self.types
             actor = self.metadata.value(nsc['fcrepo'].createdBy)
-        except ResourceNotExistsError:
+        except (ResourceNotExistsError, TombstoneError):
             type = set()
             actor = None
             for t in add_trp:

+ 1 - 1
lakesuperior/store_layouts/ldp_rs/bdb_connector.py

@@ -37,4 +37,4 @@ class BdbConnector(BaseConnector):
         '''
         Close store connection.
         '''
-        self.store.close(commit_pending_transaction=False)
+        self.ds.close(commit_pending_transaction=False)

+ 2 - 3
lakesuperior/store_layouts/ldp_rs/rsrc_centric_layout.py

@@ -218,8 +218,7 @@ class RsrcCentricLayout:
 
     def get_metadata(self, uid, ver_uid=None, strict=True):
         '''
-        This is an optimized query to get everything the application needs to
-        insert new contents, and nothing more.
+        This is an optimized query to get only the administrative metadata.
         '''
         if ver_uid:
             uid = self.snapshot_uid(uid, ver_uid)
@@ -384,7 +383,7 @@ class RsrcCentricLayout:
 
     def snapshot_uid(self, uid, ver_uid):
         '''
-        Create a versioned UID string from a main UID and a versio n UID.
+        Create a versioned UID string from a main UID and a version UID.
         '''
         if VERS_CONT_LABEL in uid:
             raise InvalidResourceError(uid,

+ 21 - 14
tests/endpoints/test_ldp.py

@@ -273,7 +273,7 @@ class TestLdp:
 
         uri = g.webroot + '/test_patch_ssr'
 
-        nossr_qry = 'INSERT { <http://bogus.org> a <urn:ns:A> . } WHERE {}'
+        #nossr_qry = 'INSERT { <http://bogus.org> a <urn:ns:A> . } WHERE {}'
         abs_qry = 'INSERT {{ <{}> a <urn:ns:A> . }} WHERE {{}}'.format(uri)
         frag_qry = 'INSERT {{ <{}#frag> a <urn:ns:A> . }} WHERE {{}}'\
                 .format(uri)
@@ -345,7 +345,7 @@ class TestLdp:
         '''
         Test delete response codes.
         '''
-        create_resp = self.client.put('/ldp/test_delete01')
+        #create_resp = self.client.put('/ldp/test_delete01')
         delete_resp = self.client.delete('/ldp/test_delete01')
         assert delete_resp.status_code == 204
 
@@ -518,9 +518,9 @@ class TestPrefHeader:
         cont_resp = cont_structure['response']
         cont_subject = cont_structure['subject']
 
-        minimal_resp = self.client.get(parent_path, headers={
-            'Prefer' : 'return=minimal',
-        })
+        #minimal_resp = self.client.get(parent_path, headers={
+        #    'Prefer' : 'return=minimal',
+        #})
 
         incl_embed_children_resp = self.client.get(parent_path, headers={
             'Prefer' : 'return=representation; include={}'\
@@ -580,16 +580,19 @@ class TestPrefHeader:
         '''
         verify the "inbound relationships" prefer header.
         '''
-        parent_path = cont_structure['path']
-        cont_resp = cont_structure['response']
-        cont_subject = cont_structure['subject']
+        self.client.put('/ldp/test_target')
+        data = '<> <http://ex.org/ns#shoots> <{}> .'.format(
+                g.webroot + '/test_target')
+        self.client.put('/ldp/test_shooter', data=data,
+                headers={'Content-Type': 'text/turtle'})
 
-        incl_inbound_resp = self.client.get(parent_path, headers={
-            'Prefer' : 'return=representation; include={}'\
+        cont_resp = self.client.get('/ldp/test_target')
+        incl_inbound_resp = self.client.get('/ldp/test_target', headers={
+            'Prefer' : 'return=representation; include="{}"'\
                     .format(Ldpr.RETURN_INBOUND_REF_URI),
         })
-        omit_inbound_resp = self.client.get(parent_path, headers={
-            'Prefer' : 'return=representation; omit={}'\
+        omit_inbound_resp = self.client.get('/ldp/test_target', headers={
+            'Prefer' : 'return=representation; omit="{}"'\
                     .format(Ldpr.RETURN_INBOUND_REF_URI),
         })
 
@@ -597,9 +600,13 @@ class TestPrefHeader:
         incl_gr = Graph().parse(data=incl_inbound_resp.data, format='turtle')
         omit_gr = Graph().parse(data=omit_inbound_resp.data, format='turtle')
 
+        subject = URIRef(g.webroot + '/test_target')
+        inbd_subject = URIRef(g.webroot + '/test_shooter')
         assert isomorphic(omit_gr, default_gr)
-        assert set(incl_gr[ : : cont_subject ])
-        assert not set(omit_gr[ : : cont_subject ])
+        assert len(set(incl_gr[inbd_subject : : ])) == 1
+        assert incl_gr[
+            inbd_subject : URIRef('http://ex.org/ns#shoots') : subject]
+        assert not len(set(omit_gr[inbd_subject : :]))
 
 
     def test_srv_mgd_triples(self, cont_structure):