예제 #1
0
 def testRegex(self):
     # raise SkipTest("Known issue.")
     g = self.graph
     g.parse(data=testN3, format="n3")
     try:
         for s,p,o in g.triples((None,implies,None)):
             formulaA = s
             formulaB = o
         
         assert type(formulaA)==QuotedGraph and type(formulaB)==QuotedGraph
         a = URIRef('http://test/a')
         b = URIRef('http://test/b')
         c = URIRef('http://test/c')
         d = URIRef('http://test/d')
         
         universe = ConjunctiveGraph(g.store)
         
         #REGEX triple matching
         assert len(list(universe.triples((None,REGEXTerm('.*22-rdf-syntax-ns.*'),None))))==1
         assert len(list(universe.triples((None,REGEXTerm('.*'),None))))==3
         assert len(list(universe.triples((REGEXTerm('.*formula.*$'),None,None))))==1
         assert len(list(universe.triples((None,None,REGEXTerm('.*formula.*$')))))==1
         assert len(list(universe.triples((None,REGEXTerm('.*implies$'),None))))==1
         for s,p,o in universe.triples((None,REGEXTerm('.*test.*'),None)):
             assert s==a
             assert o==c
         
         for s,p,o in formulaA.triples((None,REGEXTerm('.*type.*'),None)):
             assert o!=c or isinstance(o,BNode)
         
         #REGEX context matching
         assert len(list(universe.contexts((None,None,REGEXTerm('.*schema.*')))))==1
         assert len(list(universe.contexts((None,REGEXTerm('.*'),None))))==3
         
         #test optimized interfaces
         assert len(list(g.store.subjects(RDF.type,[RDFS.Class,c])))==1
         for subj in g.store.subjects(RDF.type,[RDFS.Class,c]):
             assert isinstance(subj,BNode)
         
         assert len(list(g.store.subjects(implies,[REGEXTerm('.*')])))==1
         
         for subj in g.store.subjects(implies,[formulaB,RDFS.Class]):
             assert subj.identifier == formulaA.identifier
         
         assert len(list(g.store.subjects(REGEXTerm('.*'),[formulaB,c])))==2
         assert len(list(g.store.subjects(None,[formulaB,c])))==2
         assert len(list(g.store.subjects(None,[formulaB,c])))==2
         assert len(list(g.store.subjects([REGEXTerm('.*rdf-syntax.*'),d],None)))==2
         
         assert len(list(g.store.objects(None,RDF.type)))==1
         assert len(list(g.store.objects(a,[d,RDF.type])))==1
         assert len(list(g.store.objects(a,[d])))==1
         assert len(list(g.store.objects(a,None)))==1
         assert len(list(g.store.objects(a,[REGEXTerm('.*')])))==1
         assert len(list(g.store.objects([a,c],None)))==1
     
     except:
         g.store.destroy(configString)
         raise
예제 #2
0
    def testAperture(self):

        g = ConjunctiveGraph()

        g.parse("test/trix/aperture.trix", format="trix")
        c = list(g.contexts())

        #print list(g.contexts())
        t = sum(map(len, g.contexts()))

        self.assertEquals(t, 24)
        self.assertEquals(len(c), 4)
예제 #3
0
    def testAperture(self): 

        g=ConjunctiveGraph()

        g.parse("test/trix/aperture.trix",format="trix")
        c=list(g.contexts())

        #print list(g.contexts())
        t=sum(map(len, g.contexts()))

        self.assertEquals(t,24)
        self.assertEquals(len(c),4)
예제 #4
0
    def testAperture(self):

        g = ConjunctiveGraph()

        trix_path = os.path.relpath(
            os.path.join(TEST_DIR, 'trix/aperture.trix'), os.curdir)
        g.parse(trix_path, format="trix")
        c = list(g.contexts())

        # print list(g.contexts())
        t = sum(map(len, g.contexts()))

        self.assertEqual(t, 24)
        self.assertEqual(len(c), 4)
예제 #5
0
    def check(kws):
        cg = ConjunctiveGraph()
        cg.parse(**kws)

        for g in cg.contexts():
            gid = g.identifier
            assert isinstance(gid, Identifier)
예제 #6
0
    def check(kws):
        cg = ConjunctiveGraph()
        cg.parse(**kws)

        for g in cg.contexts():
            gid = g.identifier
            assert isinstance(gid, Identifier)
예제 #7
0
    def testModel(self):
        g = ConjunctiveGraph()
        g.parse(data=test_data, format="n3")
        i = 0
        for s, p, o in g:
            if isinstance(s, Graph):
                i += 1
        self.assertEquals(i, 3)
        self.assertEquals(len(list(g.contexts())), 13)

        g.close()
예제 #8
0
    def testModel(self):
        g = ConjunctiveGraph()
        g.parse(data=test_data, format="n3")
        i = 0
        for s, p, o in g:
            if isinstance(s, Graph):
                i += 1
        self.assertEquals(i, 3)
        self.assertEquals(len(list(g.contexts())), 13)

        g.close()
예제 #9
0
 def setUp(self):
     register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')
     # self.graph = Graph()
     #self.proj_context_uri = 'http://127.0.0.1:8000/contexts/projects/3.json'
     self.proj_context_uri = '/127.0.0.1:8000/contexts/projects/3.json'
     self.context_file = settings.STATIC_IMPORTS_ROOT + '3-context.json'
     self.data_file = settings.STATIC_IMPORTS_ROOT + 'dt-bone.json'
     self.context_str = self.request_json_str(self.proj_context_uri)
     self.data_str = self.load_json_file_str(self.data_file)
     g_context = ConjunctiveGraph(identifier=self.proj_context_uri)
     g_context.parse(data=self.context_str, format='json-ld')
     proj_graph_obj = URIRef(self.proj_context_uri)
     print('N3: ' + str(g_context.__str__()))
     for c in g_context.contexts():
         print(str(c))
     print('-------Triples for context-graph------')
     self.test_type_linking(g_context)
     g_data = ConjunctiveGraph().parse(data=self.data_str, format='json-ld')
     print('-------Triples for data-record--------')
     self.test_type_linking(g_data)
예제 #10
0
 def setUp(self):
     register('json-ld',
              Parser,
              'rdflib_jsonld.parser',
              'JsonLDParser')
     # self.graph = Graph()
     self.proj_context_uri = 'http://127.0.0.1:8000/contexts/projects/3.json'
     self.context_file = settings.STATIC_IMPORTS_ROOT + '3-context.json'
     self.data_file = settings.STATIC_IMPORTS_ROOT + 'dt-bone.json'
     self.context_str = self.request_json_str(self.proj_context_uri)
     self.data_str = self.load_json_file_str(self.data_file)
     g_context = ConjunctiveGraph(identifier=self.proj_context_uri)
     g_context.parse(data=self.context_str, format='json-ld')
     proj_graph_obj = URIRef(self.proj_context_uri)
     print('N3: ' + str(g_context.__str__()))
     for c in g_context.contexts():
         print(str(c))
     print('-------Triples for context-graph------')
     self.test_type_linking(g_context)
     g_data = ConjunctiveGraph().parse(data=self.data_str, format='json-ld')
     print('-------Triples for data-record--------')
     self.test_type_linking(g_data)
예제 #11
0
 def setUp(self):
     register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')
     # self.graph = Graph()
     # self.proj_context_uri = 'http://127.0.0.1:8000/contexts/projects/3FAAA477-5572-4B05-8DC1-CA264FE1FC10.json'
     self.proj_context_uri = '/contexts/projects/3FAAA477-5572-4B05-8DC1-CA264FE1FC10.json'
     self.context_file = settings.STATIC_IMPORTS_ROOT + '3-context.json'
     self.data_file = settings.STATIC_IMPORTS_ROOT + 'dt-bone.json'
     #self.context_str = self.request_json_str(self.proj_context_uri)
     client = Client()
     response = client.get(self.proj_context_uri, follow=True)
     assert response.status_code in [200, 301]
     self.context_str = response.content
     self.data_str = self.load_json_file_str(self.data_file)
     g_context = ConjunctiveGraph(identifier=self.proj_context_uri)
     g_context.parse(data=self.context_str, format='json-ld')
     proj_graph_obj = URIRef(self.proj_context_uri)
     print('N3: ' + str(g_context.__str__()))
     for c in g_context.contexts():
         print(str(c))
     print('-------Triples for context-graph------')
     self.test_type_linking(g_context)
     g_data = ConjunctiveGraph().parse(data=self.data_str, format='json-ld')
     print('-------Triples for data-record--------')
     self.test_type_linking(g_data)
예제 #12
0
    def test_n3_store(self):
        # Thorough test suite for formula-aware store

        implies = URIRef("http://www.w3.org/2000/10/swap/log#implies")
        testN3 = """
@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix : <http://test/> .
{:a :b :c;a :foo} => {:a :d :c,?y}.
_:foo a rdfs:Class.
:a :d :c."""

        g = self.open_graph()
        g.parse(data=testN3, format="n3")

        formulaA = BNode()
        formulaB = BNode()
        for s,o in g.subject_objects(predicate=implies):
            formulaA = s
            formulaB = o
        assert type(formulaA)==QuotedGraph and type(formulaB)==QuotedGraph

        a = URIRef('http://test/a')
        b = URIRef('http://test/b')
        c = URIRef('http://test/c')
        d = URIRef('http://test/d')
        v = Variable('y')
        
        universe = ConjunctiveGraph(g.store)
        
        # test formula as terms
        assert len(list(universe.triples((formulaA, implies, formulaB)))) == 1
        
        # test variable as term and variable roundtrip
        assert len(list(formulaB.triples((None,None,v)))) == 1
        for s,p,o in formulaB.triples((None,d,None)):
            if o != c:
                assert isinstance(o, Variable)
                assert o == v

        s = list(universe.subjects(RDF.type, RDFS.Class))[0]
        assert isinstance(s, BNode)
        assert len(list(universe.triples((None,implies,None)))) == 1
        assert len(list(universe.triples((None,RDF.type,None)))) == 1

        assert len(list(formulaA.triples((None,RDF.type,None)))) == 1
        assert len(list(formulaA.triples((None,None,None)))) == 2

        assert len(list(formulaB.triples((None,None,None)))) == 2
        assert len(list(formulaB.triples((None,d,None)))) == 2

        assert len(list(universe.triples((None,None,None)))) == 3 
        assert len(list(universe.triples((None,d,None)))) == 1
        
        # context tests
        # test contexts with triple argument
        assert len(list(universe.contexts((a,d,c))))==1
        
        # remove test cases
        universe.remove((None,implies,None))
        assert len(list(universe.triples((None,implies,None)))) == 0
        assert len(list(formulaA.triples((None,None,None)))) == 2
        assert len(list(formulaB.triples((None,None,None)))) == 2
        
        formulaA.remove((None,b,None))
        assert len(list(formulaA.triples((None,None,None)))) == 1

        formulaA.remove((None,RDF.type,None))
        assert len(list(formulaA.triples((None,None,None)))) == 0
        
        universe.remove((None,RDF.type,RDFS.Class))
        
        # remove_context tests
        universe.remove_context(formulaB)
        assert len(list(universe.triples((None,RDF.type,None)))) == 0
        assert len(universe) == 1
        assert len(formulaB) == 0
        
        universe.remove((None,None,None))
        assert len(universe) == 0
class py_drone_graph_core:
    '''
    sample instantiation,
    d_graph = ldg.py_drone_graph(ontology_myID, load_graph_file)
    where,
    1. ontology_myID, uuid for this drone
      e.g. "MjlmNmVmZTAtNGU1OS00N2I4LWI3MzYtODZkMDQ0MTRiNzcxCg=="
    2. load_graph_file, turtle file or (folder) for db initialization
      e.g. base.ttl

    has the following sections,
    1. initialization and graph i/o
    2. utility functions like generating uuid etc.
    '''
    #################
    # class variables
    #################
    g = None  # graph
    Id = None  # local drone id
    files_loaded = False  # flag to prevent ontology reload
    my_host_name = None  # host_name
    BASE = None  # base namespace

    # initialization and graph i/o #############################################
    #######################
    # class initialization
    #######################
    def __init__(self, ontology_myid, graph_dict, my_base, my_host_name):
        '''
        Args:
            ontology_myid (str):    uuid for this drone
            graph_dict (dict.):     configuration data
        '''
        # save hostname
        self.my_host_name = my_host_name + '/'

        # fix base
        self.BASE = rdflib.Namespace(my_base)

        # set base id
        self.Id = ontology_myid

        # load graph, include ttl to load if required
        self.setup_graph(graph_dict)

    ##########################
    # setup and load graph
    ##########################
    def setup_graph(self, graph_dict):
        '''
        Args:
            graph_dict (dict.):     configuration data
        '''
        # get config for graph name, physical db location and it's format
        # added extraction of load_graph_file
        self.graph_name = graph_dict.get('name', ontology_db)
        graph_location = graph_dict.get('db_location', ontology_db_location)
        graph_file_format = graph_dict.get('file_format',
                                           ontology_landrs_file_format)
        load_graph_file = graph_dict.get('file', ontology_db_file)

        # test created instances with pyshacl?
        pshac = graph_dict.get('pyshacl', 'False')
        if pshac == 'False':
            self.pyshacl = False
        else:
            self.pyshacl = True

        shacl_filename = graph_dict.get('shacl_filename', '*shape.ttl')
        ontology_filename = graph_dict.get('ontology_filename', 'ontology.ttl')

        # other shape files
        flight_shacl_filename = graph_dict.get('flight_shacl_filename',
                                               extra_shape_file)
        shacl_constraint_filename = graph_dict.get('shacl_constraint_filename',
                                                   '*shapes.ttl')

        # added file reload startegy
        graph_file_reload = graph_dict.get('file_reload', 'False')

        # does the db exist?
        reload_db = True
        if graph_file_reload == 'False' and os.path.isfile(graph_location +
                                                           '.sqlite'):
            reload_db = False

        # check any folders exist
        os.makedirs(os.path.dirname(graph_location), exist_ok=True)

        # store location
        uri = Literal("sqlite:///%(here)s/%(loc)s.sqlite" % {
            "here": os.getcwd(),
            "loc": graph_location
        })

        # create store
        store_ident = URIRef('store_' + self.graph_name)
        self.store = plugin.get("SQLAlchemy", Store)(identifier=store_ident)

        # was self.g.open
        self.store.open(uri, create=True)

        # and ConjunctiveGraph
        self.g = ConjunctiveGraph(self.store)

        # vars for first graph context
        ident = self.BASE.term(self.graph_name)

        # create and load graph
        self.g1 = Graph(self.store, identifier=ident)

        # vars for shape graph context
        ident2 = self.BASE.term(self.graph_name + '_shape')

        # create and load shape graph
        self.g2 = Graph(self.store, identifier=ident2)

        # vars for config shape graph context
        ident3 = self.BASE.term(self.graph_name + '_config')

        # create and load shape graph
        self.g_config = Graph(self.store, identifier=ident3)

        # print graphs
        print("Graphs")
        for c in self.g.contexts():
            print("-- %s " % c)

        # add LANDRS and other namespaces, this converts the pythonized names to
        # something more readable
        self.g.namespace_manager.bind('landrs', LANDRS)
        self.g.namespace_manager.bind('sosa', SOSA)
        #self.g.namespace_manager.bind('base', BASE)
        #self.g.namespace_manager.bind('qudt-unit-1-1', QUDT_UNIT)
        self.g.namespace_manager.bind('qudt-1-1', QUDT)
        self.g.namespace_manager.bind('geo', GEO)
        self.g.namespace_manager.bind('rdfg', RDFG)

        # Load graph?
        if load_graph_file and not self.files_loaded and reload_db:
            # folder or file?
            if os.path.isdir(load_graph_file):

                # get the list of files
                files_in_graph_folder = os.walk(load_graph_file)
                print("Folder provided for import.")
                # loop
                for (dirpath, dirnames, filenames) in files_in_graph_folder:
                    for file in filenames:
                        file_path = os.path.join(dirpath, file)
                        # each file if turtle
                        if os.path.splitext(file_path)[-1].lower(
                        ) == "." + graph_file_format:
                            if os.path.isfile(file_path):
                                print("file", file_path)
                                self.files_loaded = True
                                # load the individual file
                                try:
                                    # test for shacl files, seperate graph
                                    if fnmatch.fnmatch(
                                            os.path.basename(file_path),
                                            shacl_filename):
                                        self.g2.load(
                                            file_path,
                                            format=graph_file_format,
                                            publicID=self.my_host_name)
                                    else:
                                        self.g1.load(
                                            file_path,
                                            format=graph_file_format,
                                            publicID=self.my_host_name)
                                except Exception as ex:
                                    print("Could not load graph file: " +
                                          str(ex))

            else:
                print("File provided for import.")
                if os.path.isfile(load_graph_file):
                    self.files_loaded = True
                    # load the file
                    try:
                        self.g1.load(load_graph_file,
                                     format=graph_file_format,
                                     publicID=self.my_host_name)
                    except Exception as ex:
                        print("Could not load graph file: " + str(ex))

                    # turn off pyshacl if no seperate shape graph
                    self.pyshacl = False

            # additional config shape files, folder?
            if os.path.isdir(flight_shacl_filename):
                file_list = glob.glob(flight_shacl_filename +
                                      shacl_constraint_filename)
                for fn in file_list:
                    # extract target graph name
                    pos = fn.find(shacl_constraint_filename[1:]) - 1
                    pos2 = fn.rfind('/') + 1

                    # set name
                    g_name = fn[pos2:pos]
                    print("file", fn, g_name)

                    # create graph
                    # vars for config shape graph context
                    identn = self.BASE.term(g_name)

                    # create and load shape graph
                    self.g_tmp = Graph(self.store, identifier=identn)

                    # try to create
                    try:
                        self.g_tmp.load(fn,
                                        format=graph_file_format,
                                        publicID=self.my_host_name)
                    except Exception as ex:
                        print("Could not load shape file: " + str(ex))

            # stand alone?
            elif os.path.isfile(flight_shacl_filename):
                print("file", flight_shacl_filename)
                try:
                    self.g_config.load(flight_shacl_filename,
                                       format=graph_file_format,
                                       publicID=self.my_host_name)
                except Exception as ex:
                    print("Could not load shape file: " + str(ex))

    #############
    # create uuid
    #############
    def generate_uuid(self):
        return base64.urlsafe_b64encode(
            uuid.uuid4().bytes)[:-2].decode('utf-8')

    ######################
    # dump graph as turtle
    ######################
    def dump_graph(self, id):
        graph = self.g.get_context(self.BASE.term(id))
        if graph:
            return graph.serialize(format="turtle", base=self.my_host_name)
        else:
            return None

    #######################
    # dump graphs as turtle
    #######################
    def list_graphs(self):
        ret = '@prefix rdfg: <http://www.w3.org/2004/03/trix/rdfg-1/> .\n' + \
            '@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n' + \
            '@prefix rdflib: <http://rdflib.net/projects#> .\n\n'
        # loop over graphs and append
        for c in self.g.contexts():
            ret = ret + str(c) + '\n'

        # return it
        return ret

    ###########################################
    # find namespace for node from uuid
    # solves problem of having objects created
    # on ld.landrs.org OR the drone.
    # Also test existance.
    ###########################################
    def find_node_from_uuid(self, uuid, id_type=None):
        '''
        Args:
            uuid (str):    uuid to find

        Returns:
           URIRef: node associated with uuid
        '''
        # check drone definition exists and if it is local or on ld.landrs.org
        id_node = LDLBASE.term(uuid)
        if not (id_node, RDF.type, id_type) in self.g:
            # from myself?
            id_node = self.BASE.term(uuid)
            if not (id_node, RDF.type, id_type) in self.g:
                # return info
                return None

        # if here, exists and node resolved
        return id_node

    ##########################################
    # recursive drill down through blank nodes
    ##########################################
    def blank_node_recursion(self, blnk, grph):
        # check blank
        if isinstance(blnk, BNode):
            # get nodes
            for sn, pn, on in self.g.triples((blnk, None, None)):
                grph.add((sn, pn, on))
                # recurse
                self.blank_node_recursion(on, grph)

    #########################################
    # get graph with node and its blank nodes
    #########################################
    def get_graph_with_node(self, id_node):
        '''
        Args:
            id_node (str): node id to put into graph

        Returns:
           graph: graph of id_node
        '''
        node_graph = Graph()
        # get id's triples
        for s, p, o in self.g.triples((id_node, None, None)):
            node_graph.add((s, p, o))
            # if associated blank not, get its tripples
            self.blank_node_recursion(o, node_graph)

        # return the new graph
        return node_graph

    ##########################
    # get triples for an id
    ##########################
    def get_id_data(self, id, json=False):
        '''
        Args:
            id (str): uuid to query

        Returns:
           dict.: query result
        '''
        # dictionary
        id_data = {}

        # is the id a local graph?
        # if so return the graph as turtle
        g = self.g.get_context(self.BASE.term(id))
        if g:
            # return info
            return g.serialize(format="turtle",
                               base=self.my_host_name)  # id_data

        # check drone definition exists and if it is local or on ld.landrs.org
        # we will support ld.landrs.org ids due to potential connectivity problems
        id_node = self.find_node_from_uuid(id)
        if not id_node:
            # return info
            return {"status": "id: " + id + " not found."}

        if not json:
            node_graph = self.get_graph_with_node(id_node)

            # return info
            return node_graph.serialize(format="turtle",
                                        base=self.my_host_name)  # id_data
        else:
            # get id's triples
            for s, p, o in self.g.triples((id_node, None, None)):
                print("{} is a {}".format(p, o))
                id_data.update({p: o})

            # return json here
            return id_data

    ##################################
    # routine to convert graph to json
    ##################################
    def graph_to_json(self, g):
        """
        Pass in a rdflib.Graph and get back a chunk of JSON using
        the Talis JSON serialization for RDF:
        http://n2.talis.com/wiki/RDF_JSON_Specification
        """
        g_json = {}

        # go through all the triples in the graph
        for s, p, o in g:

            # initialize property dictionary if we've got a new subject
            if not s in g_json.keys():
                # if not json.has_key(s):
                g_json[s] = {}

            # initialize object list if we've got a new subject-property combo
            if not p in g_json[s].keys():
                # if not json[s].has_key(p):
                g_json[s][p] = []

            # determine the value dictionary for the object
            v = {'value': o}
            if isinstance(o, rdflib.URIRef):
                v['type'] = 'uri'
            elif isinstance(o, rdflib.BNode):
                v['type'] = 'bnode'
            elif isinstance(o, rdflib.Literal):
                v['type'] = 'literal'
                if o.language:
                    v['lang'] = o.language
                if o.datatype:
                    v['datatype'] = o.datatype

            # add the triple
            g_json[s][p].append(v)

        return json.dumps(g_json, indent=4)
예제 #14
0
class ContextTestCase(unittest.TestCase):
    #store = 'Memory'
    store = 'default'
    slow = True
    tmppath = None

    def setUp(self):
        self.graph = ConjunctiveGraph(store=self.store)
        if self.store == "MySQL":
            from mysql import configString
            from rdflib.store.MySQL import MySQL
            path = configString
            MySQL().destroy(path)
        else:
            self.tmppath = mkdtemp()
        self.graph.open(self.tmppath, create=True)
        self.michel = URIRef(u'michel')
        self.tarek = URIRef(u'tarek')
        self.bob = URIRef(u'bob')
        self.likes = URIRef(u'likes')
        self.hates = URIRef(u'hates')
        self.pizza = URIRef(u'pizza')
        self.cheese = URIRef(u'cheese')

        self.c1 = URIRef(u'context-1')
        self.c2 = URIRef(u'context-2')

        # delete the graph for each test!
        self.graph.remove((None, None, None))

    def tearDown(self):
        self.graph.close()
        shutil.rmtree(self.tmppath)

    def get_context(self, identifier):
        assert isinstance(identifier, URIRef) or \
               isinstance(identifier, BNode), type(identifier)
        return Graph(store=self.graph.store,
                     identifier=identifier,
                     namespace_manager=self)

    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.add((tarek, likes, pizza))
        graph.add((tarek, likes, cheese))
        graph.add((michel, likes, pizza))
        graph.add((michel, likes, cheese))
        graph.add((bob, likes, cheese))
        graph.add((bob, hates, pizza))
        graph.add((bob, hates, michel))  # gasp!

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.remove((tarek, likes, pizza))
        graph.remove((tarek, likes, cheese))
        graph.remove((michel, likes, pizza))
        graph.remove((michel, likes, cheese))
        graph.remove((bob, likes, cheese))
        graph.remove((bob, hates, pizza))
        graph.remove((bob, hates, michel))  # gasp!

    def addStuffInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek)  # revenge!

        # add to default context
        self.graph.add(triple)
        # add to context 1
        graph = Graph(self.graph.store, c1)
        graph.add(triple)
        # add to context 2
        graph = Graph(self.graph.store, c2)
        graph.add(triple)

    def testConjunction(self):
        self.addStuffInMultipleContexts()
        triple = (self.pizza, self.likes, self.pizza)
        # add to context 1
        graph = Graph(self.graph.store, self.c1)
        graph.add(triple)
        self.assertEquals(len(self.graph), len(graph))

    def testAdd(self):
        self.addStuff()

    def testRemove(self):
        self.addStuff()
        self.removeStuff()

    def testLenInOneContext(self):
        c1 = self.c1
        # make sure context is empty

        self.graph.remove_context(self.get_context(c1))
        graph = Graph(self.graph.store, c1)
        oldLen = len(self.graph)

        for i in range(0, 10):
            graph.add((BNode(), self.hates, self.hates))
        self.assertEquals(len(graph), oldLen + 10)
        self.assertEquals(len(self.get_context(c1)), oldLen + 10)
        self.graph.remove_context(self.get_context(c1))
        self.assertEquals(len(self.graph), oldLen)
        self.assertEquals(len(graph), 0)

    def testLenInMultipleContexts(self):
        oldLen = len(self.graph)
        self.addStuffInMultipleContexts()

        # addStuffInMultipleContexts is adding the same triple to
        # three different contexts. So it's only + 1
        self.assertEquals(len(self.graph), oldLen + 1)

        graph = Graph(self.graph.store, self.c1)
        self.assertEquals(len(graph), oldLen + 1)

    def testRemoveInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek)  # revenge!

        self.addStuffInMultipleContexts()

        # triple should be still in store after removing it from c1 + c2
        self.assert_(triple in self.graph)
        graph = Graph(self.graph.store, c1)
        graph.remove(triple)
        self.assert_(triple in self.graph)
        graph = Graph(self.graph.store, c2)
        graph.remove(triple)
        self.assert_(triple in self.graph)
        self.graph.remove(triple)
        # now gone!
        self.assert_(triple not in self.graph)

        # add again and see if remove without context removes all triples!
        self.addStuffInMultipleContexts()
        self.graph.remove(triple)
        self.assert_(triple not in self.graph)

    def testContexts(self):
        triple = (self.pizza, self.hates, self.tarek)  # revenge!

        self.addStuffInMultipleContexts()

        def cid(c):
            return c.identifier

        self.assert_(self.c1 in map(cid, self.graph.contexts()))
        self.assert_(self.c2 in map(cid, self.graph.contexts()))

        contextList = map(cid, list(self.graph.contexts(triple)))
        self.assert_(self.c1 in contextList)
        self.assert_(self.c2 in contextList)

    def testRemoveContext(self):
        c1 = self.c1

        self.addStuffInMultipleContexts()
        self.assertEquals(len(Graph(self.graph.store, c1)), 1)
        self.assertEquals(len(self.get_context(c1)), 1)

        self.graph.remove_context(self.get_context(c1))
        self.assert_(self.c1 not in self.graph.contexts())

    def testRemoveAny(self):
        Any = None
        self.addStuffInMultipleContexts()
        self.graph.remove((Any, Any, Any))
        self.assertEquals(len(self.graph), 0)

    def testTriples(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        asserte = self.assertEquals
        triples = self.graph.triples
        graph = self.graph
        c1graph = Graph(self.graph.store, c1)
        c1triples = c1graph.triples
        Any = None

        self.addStuff()

        # unbound subjects with context
        asserte(len(list(c1triples((Any, likes, pizza)))), 2)
        asserte(len(list(c1triples((Any, hates, pizza)))), 1)
        asserte(len(list(c1triples((Any, likes, cheese)))), 3)
        asserte(len(list(c1triples((Any, hates, cheese)))), 0)

        # unbound subjects without context, same results!
        asserte(len(list(triples((Any, likes, pizza)))), 2)
        asserte(len(list(triples((Any, hates, pizza)))), 1)
        asserte(len(list(triples((Any, likes, cheese)))), 3)
        asserte(len(list(triples((Any, hates, cheese)))), 0)

        # unbound objects with context
        asserte(len(list(c1triples((michel, likes, Any)))), 2)
        asserte(len(list(c1triples((tarek, likes, Any)))), 2)
        asserte(len(list(c1triples((bob, hates, Any)))), 2)
        asserte(len(list(c1triples((bob, likes, Any)))), 1)

        # unbound objects without context, same results!
        asserte(len(list(triples((michel, likes, Any)))), 2)
        asserte(len(list(triples((tarek, likes, Any)))), 2)
        asserte(len(list(triples((bob, hates, Any)))), 2)
        asserte(len(list(triples((bob, likes, Any)))), 1)

        # unbound predicates with context
        asserte(len(list(c1triples((michel, Any, cheese)))), 1)
        asserte(len(list(c1triples((tarek, Any, cheese)))), 1)
        asserte(len(list(c1triples((bob, Any, pizza)))), 1)
        asserte(len(list(c1triples((bob, Any, michel)))), 1)

        # unbound predicates without context, same results!
        asserte(len(list(triples((michel, Any, cheese)))), 1)
        asserte(len(list(triples((tarek, Any, cheese)))), 1)
        asserte(len(list(triples((bob, Any, pizza)))), 1)
        asserte(len(list(triples((bob, Any, michel)))), 1)

        # unbound subject, objects with context
        asserte(len(list(c1triples((Any, hates, Any)))), 2)
        asserte(len(list(c1triples((Any, likes, Any)))), 5)

        # unbound subject, objects without context, same results!
        asserte(len(list(triples((Any, hates, Any)))), 2)
        asserte(len(list(triples((Any, likes, Any)))), 5)

        # unbound predicates, objects with context
        asserte(len(list(c1triples((michel, Any, Any)))), 2)
        asserte(len(list(c1triples((bob, Any, Any)))), 3)
        asserte(len(list(c1triples((tarek, Any, Any)))), 2)

        # unbound predicates, objects without context, same results!
        asserte(len(list(triples((michel, Any, Any)))), 2)
        asserte(len(list(triples((bob, Any, Any)))), 3)
        asserte(len(list(triples((tarek, Any, Any)))), 2)

        # unbound subjects, predicates with context
        asserte(len(list(c1triples((Any, Any, pizza)))), 3)
        asserte(len(list(c1triples((Any, Any, cheese)))), 3)
        asserte(len(list(c1triples((Any, Any, michel)))), 1)

        # unbound subjects, predicates without context, same results!
        asserte(len(list(triples((Any, Any, pizza)))), 3)
        asserte(len(list(triples((Any, Any, cheese)))), 3)
        asserte(len(list(triples((Any, Any, michel)))), 1)

        # all unbound with context
        asserte(len(list(c1triples((Any, Any, Any)))), 7)
        # all unbound without context, same result!
        asserte(len(list(triples((Any, Any, Any)))), 7)

        for c in [graph, self.get_context(c1)]:
            # unbound subjects
            asserte(set(c.subjects(likes, pizza)), set((michel, tarek)))
            asserte(set(c.subjects(hates, pizza)), set((bob, )))
            asserte(set(c.subjects(likes, cheese)), set([tarek, bob, michel]))
            asserte(set(c.subjects(hates, cheese)), set())

            # unbound objects
            asserte(set(c.objects(michel, likes)), set([cheese, pizza]))
            asserte(set(c.objects(tarek, likes)), set([cheese, pizza]))
            asserte(set(c.objects(bob, hates)), set([michel, pizza]))
            asserte(set(c.objects(bob, likes)), set([cheese]))

            # unbound predicates
            asserte(set(c.predicates(michel, cheese)), set([likes]))
            asserte(set(c.predicates(tarek, cheese)), set([likes]))
            asserte(set(c.predicates(bob, pizza)), set([hates]))
            asserte(set(c.predicates(bob, michel)), set([hates]))

            asserte(set(c.subject_objects(hates)),
                    set([(bob, pizza), (bob, michel)]))
            asserte(
                set(c.subject_objects(likes)),
                set([(tarek, cheese), (michel, cheese), (michel, pizza),
                     (bob, cheese), (tarek, pizza)]))

            asserte(set(c.predicate_objects(michel)),
                    set([(likes, cheese), (likes, pizza)]))
            asserte(set(c.predicate_objects(bob)),
                    set([(likes, cheese), (hates, pizza), (hates, michel)]))
            asserte(set(c.predicate_objects(tarek)),
                    set([(likes, cheese), (likes, pizza)]))

            asserte(set(c.subject_predicates(pizza)),
                    set([(bob, hates), (tarek, likes), (michel, likes)]))
            asserte(set(c.subject_predicates(cheese)),
                    set([(bob, likes), (tarek, likes), (michel, likes)]))
            asserte(set(c.subject_predicates(michel)), set([(bob, hates)]))

            asserte(
                set(c),
                set([(bob, hates, michel), (bob, likes, cheese),
                     (tarek, likes, pizza), (michel, likes, pizza),
                     (michel, likes, cheese), (bob, hates, pizza),
                     (tarek, likes, cheese)]))

        # remove stuff and make sure the graph is empty again
        self.removeStuff()
        asserte(len(list(c1triples((Any, Any, Any)))), 0)
        asserte(len(list(triples((Any, Any, Any)))), 0)
예제 #15
0
def testFormulaStore(store="default", configString=None):
    try: 
        g = ConjunctiveGraph(store=store)
    except ImportError: 
        raise SkipTest("Dependencies for store '%s' not available!"%store)
  



    if configString:
        g.destroy(configString)
        g.open(configString)
    else: 
        g.open(mkdtemp(), create=True)

    g.parse(data=testN3, format="n3")
    print g.store
    try:
        for s,p,o in g.triples((None,implies,None)):
            formulaA = s
            formulaB = o

        assert type(formulaA)==QuotedGraph and type(formulaB)==QuotedGraph
        a = URIRef('http://test/a')
        b = URIRef('http://test/b')
        c = URIRef('http://test/c')
        d = URIRef('http://test/d')
        v = Variable('y')

        universe = ConjunctiveGraph(g.store)

        #test formula as terms
        assert len(list(universe.triples((formulaA,implies,formulaB))))==1

        #test variable as term and variable roundtrip
        assert len(list(formulaB.triples((None,None,v))))==1
        for s,p,o in formulaB.triples((None,d,None)):
            if o != c:
                assert isinstance(o,Variable)
                assert o == v
        s = list(universe.subjects(RDF.type, RDFS.Class))[0]
        assert isinstance(s,BNode)
        assert len(list(universe.triples((None,implies,None)))) == 1
        assert len(list(universe.triples((None,RDF.type,None)))) ==1
        assert len(list(formulaA.triples((None,RDF.type,None))))==1
        assert len(list(formulaA.triples((None,None,None))))==2
        assert len(list(formulaB.triples((None,None,None))))==2
        assert len(list(universe.triples((None,None,None))))==3
        assert len(list(formulaB.triples((None,URIRef('http://test/d'),None))))==2
        assert len(list(universe.triples((None,URIRef('http://test/d'),None))))==1

        #context tests
        #test contexts with triple argument
        assert len(list(universe.contexts((a,d,c))))==1

        #Remove test cases
        universe.remove((None,implies,None))
        assert len(list(universe.triples((None,implies,None))))==0
        assert len(list(formulaA.triples((None,None,None))))==2
        assert len(list(formulaB.triples((None,None,None))))==2

        formulaA.remove((None,b,None))
        assert len(list(formulaA.triples((None,None,None))))==1
        formulaA.remove((None,RDF.type,None))
        assert len(list(formulaA.triples((None,None,None))))==0

        universe.remove((None,RDF.type,RDFS.Class))


        #remove_context tests
        universe.remove_context(formulaB)
        assert len(list(universe.triples((None,RDF.type,None))))==0
        assert len(universe)==1
        assert len(formulaB)==0

        universe.remove((None,None,None))
        assert len(universe)==0

        g.close()
        g.store.destroy(configString)
    except:
        g.close()
        g.store.destroy(configString)
        raise
예제 #16
0
 def test_02_contexts(self):
     g = ConjunctiveGraph(self.store)
     for c in g.contexts():
         assert isinstance(c, Graph)
         break
예제 #17
0
def testN3Store(store="default", configString=None):
    storetest = True
    del storetest
    g = ConjunctiveGraph(store=store)
    if configString:
        # g.destroy(configString)
        g.open(configString, create=True)
    g.parse(data=testN3, format="n3")
    # op = g.serialize(format="n3")
    # print(op)
    formulaA = BNode()
    formulaB = BNode()
    try:
        for s, p, o in g.triples((None, implies, None)):
            formulaA = s
            formulaB = o

        assert type(formulaA) == QuotedGraph \
                and type(formulaB) == QuotedGraph
        a = URIRef('http://test/a')
        b = URIRef('http://test/b')
        c = URIRef('http://test/c')
        d = URIRef('http://test/d')
        v = Variable('y')

        universe = ConjunctiveGraph(g.store)

        #test formula as terms
        assert len(list(universe.triples((formulaA, implies, formulaB)))) == 1

        #test variable as term and variable roundtrip
        assert len(list(formulaB.triples((None, None, v)))) == 1
        for s, p, o in formulaB.triples((None, d, None)):
            if o != c:
                assert isinstance(o, Variable)
                assert o == v
        s = list(universe.subjects(RDF.type, RDFS.Class))[0]
        assert isinstance(s, BNode)
        assert len(list(universe.triples((None, implies, None)))) == 1
        assert len(list(universe.triples((None, RDF.type, None)))) == 1
        assert len(list(formulaA.triples((None, RDF.type, None)))) == 1
        assert len(list(formulaA.triples((None, None, None)))) == 2
        assert len(list(formulaB.triples((None, None, None)))) == 2
        assert len(list(universe.triples((None, None, None)))) == 3
        assert len(
            list(formulaB.triples((None, URIRef('http://test/d'), None)))) == 2
        assert len(
            list(universe.triples((None, URIRef('http://test/d'), None)))) == 1

        #context tests
        #test contexts with triple argument
        assert len(list(universe.contexts((a, d, c)))) == 1

        #Remove test cases
        universe.remove((None, implies, None))
        assert len(list(universe.triples((None, implies, None)))) == 0
        assert len(list(formulaA.triples((None, None, None)))) == 2
        assert len(list(formulaB.triples((None, None, None)))) == 2

        formulaA.remove((None, b, None))
        assert len(list(formulaA.triples((None, None, None)))) == 1
        formulaA.remove((None, RDF.type, None))
        assert len(list(formulaA.triples((None, None, None)))) == 0

        universe.remove((None, RDF.type, RDFS.Class))

        #remove_context tests
        universe.remove_context(formulaB)
        assert len(list(universe.triples((None, RDF.type, None)))) == 0
        assert len(universe) == 1
        assert len(formulaB) == 0

        universe.remove((None, None, None))
        assert len(universe) == 0

        g.store.destroy(configString)
    except:
        g.store.destroy(configString)
        raise
예제 #18
0
class ContextTestCase(unittest.TestCase):
    #store = 'Memory'
    store = 'default'
    slow = True

    def setUp(self):
        self.graph = ConjunctiveGraph(store=self.store)
        if self.store == "MySQL":
            from mysql import configString
            from rdflib.store.MySQL import MySQL
            path=configString
            MySQL().destroy(path)
        else:
            path = a_tmp_dir = mkdtemp()
        self.graph.open(path, create=True)
        self.michel = URIRef(u'michel')
        self.tarek = URIRef(u'tarek')
        self.bob = URIRef(u'bob')
        self.likes = URIRef(u'likes')
        self.hates = URIRef(u'hates')
        self.pizza = URIRef(u'pizza')
        self.cheese = URIRef(u'cheese')

        self.c1 = URIRef(u'context-1')
        self.c2 = URIRef(u'context-2')

        # delete the graph for each test!
        self.graph.remove((None, None, None))

    def tearDown(self):
        self.graph.close()

    def get_context(self, identifier):
        assert isinstance(identifier, URIRef) or \
               isinstance(identifier, BNode), type(identifier)
        return Graph(store=self.graph.store, identifier=identifier,
                         namespace_manager=self)
    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.add((tarek, likes, pizza))
        graph.add((tarek, likes, cheese))
        graph.add((michel, likes, pizza))
        graph.add((michel, likes, cheese))
        graph.add((bob, likes, cheese))
        graph.add((bob, hates, pizza))
        graph.add((bob, hates, michel)) # gasp!

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.remove((tarek, likes, pizza))
        graph.remove((tarek, likes, cheese))
        graph.remove((michel, likes, pizza))
        graph.remove((michel, likes, cheese))
        graph.remove((bob, likes, cheese))
        graph.remove((bob, hates, pizza))
        graph.remove((bob, hates, michel)) # gasp!

    def addStuffInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek) # revenge!

        # add to default context
        self.graph.add(triple)
        # add to context 1
        graph = Graph(self.graph.store, c1)
        graph.add(triple)
        # add to context 2
        graph = Graph(self.graph.store, c2)
        graph.add(triple)

    def testConjunction(self):
        self.addStuffInMultipleContexts()
        triple = (self.pizza, self.likes, self.pizza)
        # add to context 1
        graph = Graph(self.graph.store, self.c1)
        graph.add(triple)
        self.assertEquals(len(self.graph), len(graph))

    def testAdd(self):
        self.addStuff()

    def testRemove(self):
        self.addStuff()
        self.removeStuff()

    def testLenInOneContext(self):
        c1 = self.c1
        # make sure context is empty

        self.graph.remove_context(self.get_context(c1))
        graph = Graph(self.graph.store, c1)
        oldLen = len(self.graph)

        for i in range(0, 10):
            graph.add((BNode(), self.hates, self.hates))
        self.assertEquals(len(graph), oldLen + 10)
        self.assertEquals(len(self.get_context(c1)), oldLen + 10)
        self.graph.remove_context(self.get_context(c1))
        self.assertEquals(len(self.graph), oldLen)
        self.assertEquals(len(graph), 0)

    def testLenInMultipleContexts(self):
        oldLen = len(self.graph)
        self.addStuffInMultipleContexts()

        # addStuffInMultipleContexts is adding the same triple to
        # three different contexts. So it's only + 1
        self.assertEquals(len(self.graph), oldLen + 1) 

        graph = Graph(self.graph.store, self.c1)
        self.assertEquals(len(graph), oldLen + 1)

    def testRemoveInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek) # revenge!

        self.addStuffInMultipleContexts()

        # triple should be still in store after removing it from c1 + c2
        self.assert_(triple in self.graph)
        graph = Graph(self.graph.store, c1)
        graph.remove(triple)
        self.assert_(triple in self.graph)
        graph = Graph(self.graph.store, c2)
        graph.remove(triple)
        self.assert_(triple in self.graph)
        self.graph.remove(triple)
        # now gone!
        self.assert_(triple not in self.graph)

        # add again and see if remove without context removes all triples!
        self.addStuffInMultipleContexts()
        self.graph.remove(triple)
        self.assert_(triple not in self.graph)

    def testContexts(self):
        triple = (self.pizza, self.hates, self.tarek) # revenge!

        self.addStuffInMultipleContexts()
        def cid(c):
            return c.identifier
        self.assert_(self.c1 in map(cid, self.graph.contexts()))
        self.assert_(self.c2 in map(cid, self.graph.contexts()))

        contextList = map(cid, list(self.graph.contexts(triple)))
        self.assert_(self.c1 in contextList)
        self.assert_(self.c2 in contextList)

    def testRemoveContext(self):
        c1 = self.c1

        self.addStuffInMultipleContexts()
        self.assertEquals(len(Graph(self.graph.store, c1)), 1)
        self.assertEquals(len(self.get_context(c1)), 1)

        self.graph.remove_context(self.get_context(c1))
        self.assert_(self.c1 not in self.graph.contexts())

    def testRemoveAny(self):
        Any = None
        self.addStuffInMultipleContexts()
        self.graph.remove((Any, Any, Any))
        self.assertEquals(len(self.graph), 0)

    def testTriples(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        asserte = self.assertEquals
        triples = self.graph.triples
        graph = self.graph
        c1graph = Graph(self.graph.store, c1)
        c1triples = c1graph.triples
        Any = None

        self.addStuff()

        # unbound subjects with context
        asserte(len(list(c1triples((Any, likes, pizza)))), 2)
        asserte(len(list(c1triples((Any, hates, pizza)))), 1)
        asserte(len(list(c1triples((Any, likes, cheese)))), 3)
        asserte(len(list(c1triples((Any, hates, cheese)))), 0)

        # unbound subjects without context, same results!
        asserte(len(list(triples((Any, likes, pizza)))), 2)
        asserte(len(list(triples((Any, hates, pizza)))), 1)
        asserte(len(list(triples((Any, likes, cheese)))), 3)
        asserte(len(list(triples((Any, hates, cheese)))), 0)

        # unbound objects with context
        asserte(len(list(c1triples((michel, likes, Any)))), 2)
        asserte(len(list(c1triples((tarek, likes, Any)))), 2)
        asserte(len(list(c1triples((bob, hates, Any)))), 2)
        asserte(len(list(c1triples((bob, likes, Any)))), 1)

        # unbound objects without context, same results!
        asserte(len(list(triples((michel, likes, Any)))), 2)
        asserte(len(list(triples((tarek, likes, Any)))), 2)
        asserte(len(list(triples((bob, hates, Any)))), 2)
        asserte(len(list(triples((bob, likes, Any)))), 1)

        # unbound predicates with context
        asserte(len(list(c1triples((michel, Any, cheese)))), 1)
        asserte(len(list(c1triples((tarek, Any, cheese)))), 1)
        asserte(len(list(c1triples((bob, Any, pizza)))), 1)
        asserte(len(list(c1triples((bob, Any, michel)))), 1)

        # unbound predicates without context, same results!
        asserte(len(list(triples((michel, Any, cheese)))), 1)
        asserte(len(list(triples((tarek, Any, cheese)))), 1)
        asserte(len(list(triples((bob, Any, pizza)))), 1)
        asserte(len(list(triples((bob, Any, michel)))), 1)

        # unbound subject, objects with context
        asserte(len(list(c1triples((Any, hates, Any)))), 2)
        asserte(len(list(c1triples((Any, likes, Any)))), 5)

        # unbound subject, objects without context, same results!
        asserte(len(list(triples((Any, hates, Any)))), 2)
        asserte(len(list(triples((Any, likes, Any)))), 5)

        # unbound predicates, objects with context
        asserte(len(list(c1triples((michel, Any, Any)))), 2)
        asserte(len(list(c1triples((bob, Any, Any)))), 3)
        asserte(len(list(c1triples((tarek, Any, Any)))), 2)

        # unbound predicates, objects without context, same results!
        asserte(len(list(triples((michel, Any, Any)))), 2)
        asserte(len(list(triples((bob, Any, Any)))), 3)
        asserte(len(list(triples((tarek, Any, Any)))), 2)

        # unbound subjects, predicates with context
        asserte(len(list(c1triples((Any, Any, pizza)))), 3)
        asserte(len(list(c1triples((Any, Any, cheese)))), 3)
        asserte(len(list(c1triples((Any, Any, michel)))), 1)

        # unbound subjects, predicates without context, same results!
        asserte(len(list(triples((Any, Any, pizza)))), 3)
        asserte(len(list(triples((Any, Any, cheese)))), 3)
        asserte(len(list(triples((Any, Any, michel)))), 1)

        # all unbound with context
        asserte(len(list(c1triples((Any, Any, Any)))), 7)
        # all unbound without context, same result!
        asserte(len(list(triples((Any, Any, Any)))), 7)

        for c in [graph, self.get_context(c1)]:
            # unbound subjects
            asserte(set(c.subjects(likes, pizza)), set((michel, tarek)))
            asserte(set(c.subjects(hates, pizza)), set((bob,)))
            asserte(set(c.subjects(likes, cheese)), set([tarek, bob, michel]))
            asserte(set(c.subjects(hates, cheese)), set())

            # unbound objects
            asserte(set(c.objects(michel, likes)), set([cheese, pizza]))
            asserte(set(c.objects(tarek, likes)), set([cheese, pizza]))
            asserte(set(c.objects(bob, hates)), set([michel, pizza]))
            asserte(set(c.objects(bob, likes)), set([cheese]))

            # unbound predicates
            asserte(set(c.predicates(michel, cheese)), set([likes]))
            asserte(set(c.predicates(tarek, cheese)), set([likes]))
            asserte(set(c.predicates(bob, pizza)), set([hates]))
            asserte(set(c.predicates(bob, michel)), set([hates]))

            asserte(set(c.subject_objects(hates)), set([(bob, pizza), (bob, michel)]))
            asserte(set(c.subject_objects(likes)), set([(tarek, cheese), (michel, cheese), (michel, pizza), (bob, cheese), (tarek, pizza)]))

            asserte(set(c.predicate_objects(michel)), set([(likes, cheese), (likes, pizza)]))
            asserte(set(c.predicate_objects(bob)), set([(likes, cheese), (hates, pizza), (hates, michel)]))
            asserte(set(c.predicate_objects(tarek)), set([(likes, cheese), (likes, pizza)]))

            asserte(set(c.subject_predicates(pizza)), set([(bob, hates), (tarek, likes), (michel, likes)]))
            asserte(set(c.subject_predicates(cheese)), set([(bob, likes), (tarek, likes), (michel, likes)]))
            asserte(set(c.subject_predicates(michel)), set([(bob, hates)]))

            asserte(set(c), set([(bob, hates, michel), (bob, likes, cheese), (tarek, likes, pizza), (michel, likes, pizza), (michel, likes, cheese), (bob, hates, pizza), (tarek, likes, cheese)]))

        # remove stuff and make sure the graph is empty again
        self.removeStuff()
        asserte(len(list(c1triples((Any, Any, Any)))), 0)
        asserte(len(list(triples((Any, Any, Any)))), 0)
예제 #19
0
파일: test_4store.py 프로젝트: TomT0m/py4s
 def test_20_remove(self):
     assert store.query("ASK WHERE { ?s ?p ?o }")
     g = ConjunctiveGraph(store)
     for ctx in g.contexts():
         store.remove((None,None,None), context=ctx)
     assert not store.query("ASK WHERE { ?s ?p ?o }")
예제 #20
0
    store = IOMemory()

    g = ConjunctiveGraph(store=store)
    g.bind("love", ns)

    gmary = Graph(store=store, identifier=cmary)

    gmary.add((mary, ns['hasName'], Literal("Mary")))
    gmary.add((mary, ns['loves'], john))

    gjohn = Graph(store=store, identifier=cjohn)
    gjohn.add((john, ns['hasName'], Literal("John")))

    #enumerate contexts
    for c in g.contexts():
        print("-- %s " % c)

    #separate graphs
    print(gjohn.serialize(format='n3'))
    print("===================")
    print(gmary.serialize(format='n3'))
    print("===================")

    #full graph
    print(g.serialize(format='xml'))

    # query the conjunction of all graphs

    print 'Mary loves:'
    for x in g[mary:ns.loves / ns.hasName]:
예제 #21
0
    def test_rdflib_mysql_test(self):
        """
        test taken from rdflib/test/test_mysql.py
        """
        implies = URIRef("http://www.w3.org/2000/10/swap/log#implies")
        testN3="""
        @prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
        @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
        @prefix : <http://test/> .
        {:a :b :c;a :foo} => {:a :d :c,?y}.
        _:foo a rdfs:Class.
        :a :d :c."""


        #Thorough test suite for formula-aware store
        g = self.rdflib_graph
        g.parse(data=testN3, format="n3")
        #print g.store
        for s,p,o in g.triples((None,implies,None)):
            formulaA = s
            formulaB = o

        self.assertTrue(type(formulaA)==QuotedGraph and type(formulaB)==QuotedGraph)
        a = URIRef('http://test/a')
        b = URIRef('http://test/b')
        c = URIRef('http://test/c')
        d = URIRef('http://test/d')
        v = Variable('y')

        universe = ConjunctiveGraph(g.store)

        #test formula as terms
        self.assertTrue(len(list(universe.triples((formulaA,implies,formulaB))))==1)

        #test variable as term and variable roundtrip
        self.assertTrue(len(list(formulaB.triples((None,None,v))))==1)
        for s,p,o in formulaB.triples((None,d,None)):
            if o != c:
                self.assertTrue(isinstance(o,Variable))
                self.assertTrue(o == v)
        s = list(universe.subjects(RDF.type, RDFS.Class))[0]
        self.assertTrue(isinstance(s,BNode))
        self.assertTrue( len(list(universe.triples((None,implies,None)))) == 1)
        self.assertTrue( len(list(universe.triples((None,RDF.type,None)))) ==1)
        self.assertTrue( len(list(formulaA.triples((None,RDF.type,None))))==1)
        self.assertTrue( len(list(formulaA.triples((None,None,None))))==2)
        self.assertTrue( len(list(formulaB.triples((None,None,None))))==2)
        self.assertTrue( len(list(universe.triples((None,None,None))))==3)
        self.assertTrue( len(list(formulaB.triples((None,URIRef('http://test/d'),None))))==2)
        self.assertTrue( len(list(universe.triples((None,URIRef('http://test/d'),None))))==1)

        #context tests
        #test contexts with triple argument
        self.assertTrue( len(list(universe.contexts((a,d,c))))==1)

        #Remove test cases
        universe.remove((None,implies,None))
        self.assertTrue( len(list(universe.triples((None,implies,None))))==0)
        self.assertTrue( len(list(formulaA.triples((None,None,None))))==2)
        self.assertTrue( len(list(formulaB.triples((None,None,None))))==2)

        formulaA.remove((None,b,None))
        self.assertTrue( len(list(formulaA.triples((None,None,None))))==1)
        formulaA.remove((None,RDF.type,None))
        self.assertTrue( len(list(formulaA.triples((None,None,None))))==0)

        universe.remove((None,RDF.type,RDFS.Class))


        #remove_context tests
        universe.remove_context(formulaB)
        self.assertTrue( len(list(universe.triples((None,RDF.type,None))))==0)
        self.assertTrue( len(universe)==1)
        self.assertTrue( len(list(formulaB.triples((None,None,None))))==0)

        universe.remove((None,None,None))
        self.assertTrue( len(universe)==0)
예제 #22
0
def testN3Store(store="default", configString=None):
    storetest = True
    g = ConjunctiveGraph(store=store)
    if configString is not None:
        g.destroy(configString)
        g.open(configString, create=True)
    g.parse(data=testN3, format="n3")
    # op = g.serialize(format="n3")
    # print(op)
    formulaA = BNode()
    formulaB = BNode()
    try:
        for s,p,o in g.triples((None,implies,None)):
            formulaA = s
            formulaB = o
        
        assert type(formulaA)==QuotedGraph and type(formulaB)==QuotedGraph
        a = URIRef('http://test/a')
        b = URIRef('http://test/b')
        c = URIRef('http://test/c')
        d = URIRef('http://test/d')
        v = Variable('y')
        
        universe = ConjunctiveGraph(g.store)
        
        #test formula as terms
        assert len(list(universe.triples((formulaA,implies,formulaB))))==1
        
        #test variable as term and variable roundtrip
        assert len(list(formulaB.triples((None,None,v))))==1
        for s,p,o in formulaB.triples((None,d,None)):
            if o != c:
                assert isinstance(o,Variable)
                assert o == v
        s = list(universe.subjects(RDF.type, RDFS.Class))[0]
        assert isinstance(s,BNode)
        assert len(list(universe.triples((None,implies,None)))) == 1
        assert len(list(universe.triples((None,RDF.type,None)))) ==1
        assert len(list(formulaA.triples((None,RDF.type,None))))==1
        assert len(list(formulaA.triples((None,None,None))))==2
        assert len(list(formulaB.triples((None,None,None))))==2
        assert len(list(universe.triples((None,None,None))))==3
        assert len(list(formulaB.triples((None,URIRef('http://test/d'),None))))==2
        assert len(list(universe.triples((None,URIRef('http://test/d'),None))))==1
        
        #context tests
        #test contexts with triple argument
        assert len(list(universe.contexts((a,d,c))))==1
        
        #Remove test cases
        universe.remove((None,implies,None))
        assert len(list(universe.triples((None,implies,None))))==0
        assert len(list(formulaA.triples((None,None,None))))==2
        assert len(list(formulaB.triples((None,None,None))))==2
        
        formulaA.remove((None,b,None))
        assert len(list(formulaA.triples((None,None,None))))==1
        formulaA.remove((None,RDF.type,None))
        assert len(list(formulaA.triples((None,None,None))))==0
        
        universe.remove((None,RDF.type,RDFS.Class))
        
        #remove_context tests
        universe.remove_context(formulaB)
        assert len(list(universe.triples((None,RDF.type,None))))==0
        assert len(universe)==1
        assert len(formulaB)==0
        
        universe.remove((None,None,None))
        assert len(universe)==0
        
        g.store.destroy(configString)
    except:
        g.store.destroy(configString)
        raise
예제 #23
0
john = URIRef("http://love.com/lovers/john#")

cmary = URIRef("http://love.com/lovers/mary#")
cjohn = URIRef("http://love.com/lovers/john#")

store = IOMemory()

g = ConjunctiveGraph(store=store)
g.bind("love", ns)

gmary = Graph(store=store, identifier=cmary)

gmary.add((mary, ns["hasName"], Literal("Mary")))
gmary.add((mary, ns["loves"], john))

gjohn = Graph(store=store, identifier=cjohn)
gjohn.add((john, ns["hasName"], Literal("John")))

# enumerate contexts
for c in g.contexts():
    print("-- %s " % c)

# separate graphs
print(gjohn.serialize(format="n3"))
print("===================")
print(gmary.serialize(format="n3"))
print("===================")

# full graph
print(g.serialize(format="n3"))
예제 #24
0
class ContextTest(test.TestCase):
    """
    Testing different contexts.

    Heavily based on https://github.com/RDFLib/rdflib-postgresql/blob/master/test/context_case.py
    """
    store_name = "Django"
    storetest = True
    path = ""
    create = True

    michel = URIRef(u'michel')
    tarek = URIRef(u'tarek')
    bob = URIRef(u'bob')
    likes = URIRef(u'likes')
    hates = URIRef(u'hates')
    pizza = URIRef(u'pizza')
    cheese = URIRef(u'cheese')
    c1 = URIRef(u'context-1')
    c2 = URIRef(u'context-2')

    def setUp(self):
        self.graph = ConjunctiveGraph(store=self.store_name)
        self.graph.destroy(self.path)
        self.graph.open(self.path, create=self.create)

    def tearDown(self):
        self.graph.destroy(self.path)
        self.graph.close()

    def get_context(self, identifier):
        assert isinstance(identifier, URIRef) or isinstance(identifier, BNode), type(identifier)
        return Graph(store=self.graph.store, identifier=identifier, namespace_manager=self)

    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.add((tarek, likes, pizza))
        graph.add((tarek, likes, cheese))
        graph.add((michel, likes, pizza))
        graph.add((michel, likes, cheese))
        graph.add((bob, likes, cheese))
        graph.add((bob, hates, pizza))
        graph.add((bob, hates, michel))

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.remove((tarek, likes, pizza))
        graph.remove((tarek, likes, cheese))
        graph.remove((michel, likes, pizza))
        graph.remove((michel, likes, cheese))
        graph.remove((bob, likes, cheese))
        graph.remove((bob, hates, pizza))
        graph.remove((bob, hates, michel))

    def addStuffInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek)

        # add to default context
        self.graph.add(triple)
        # add to context 1
        graph = Graph(self.graph.store, c1)
        graph.add(triple)
        # add to context 2
        graph = Graph(self.graph.store, c2)
        graph.add(triple)

    def testConjunction(self):
        self.addStuffInMultipleContexts()
        triple = (self.pizza, self.likes, self.pizza)
        # add to context 1
        graph = Graph(self.graph.store, self.c1)
        graph.add(triple)

        self.assertEquals(len(graph), 2)
        self.assertEquals(len(self.graph), 2)

    def testAdd(self):
        self.addStuff()

    def testRemove(self):
        self.addStuff()
        self.removeStuff()

    def testLenInOneContext(self):
        c1 = self.c1
        # make sure context is empty

        self.graph.remove_context(self.get_context(c1))
        graph = Graph(self.graph.store, c1)
        oldLen = len(self.graph)

        for _ in range(0, 10):
            graph.add((BNode(), self.hates, self.hates))
        self.assertEquals(len(graph), oldLen + 10)
        self.assertEquals(len(self.get_context(c1)), oldLen + 10)
        self.graph.remove_context(self.get_context(c1))
        self.assertEquals(len(self.graph), oldLen)
        self.assertEquals(len(graph), 0)

    def testLenInMultipleContexts(self):
        oldLen = len(self.graph)
        self.addStuffInMultipleContexts()

        # addStuffInMultipleContexts is adding the same triple to
        # three different contexts. So it's only + 1
        self.assertEquals(len(self.graph), oldLen + 1)

        graph = Graph(self.graph.store, self.c1)
        self.assertEquals(len(graph), oldLen + 1)

    def testRemoveInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek)

        self.addStuffInMultipleContexts()

        # triple should be still in store after removing it from c1 + c2
        self.assertIn(triple, self.graph)
        graph = Graph(self.graph.store, c1)
        graph.remove(triple)
        self.assertIn(triple, self.graph)
        graph = Graph(self.graph.store, c2)
        graph.remove(triple)
        self.assertIn(triple, self.graph)
        self.graph.remove(triple)
        # now gone!
        self.assertNotIn(triple, self.graph)

        # add again and see if remove without context removes all triples!
        self.addStuffInMultipleContexts()
        self.graph.remove(triple)
        self.assertNotIn(triple, self.graph)

    def testContexts(self):
        triple = (self.pizza, self.hates, self.tarek)

        self.addStuffInMultipleContexts()

        def cid(c):
            if not isinstance(c, basestring):
                return c.identifier
            return c

        self.assertIn(self.c1, [cid(c) for c in self.graph.contexts()])
        self.assertIn(self.c2, [cid(c) for c in self.graph.contexts()])

        contextList = [cid(c) for c in self.graph.contexts(triple)]
        self.assertIn(self.c1, contextList)
        self.assertIn(self.c2, contextList)

    def testRemoveContext(self):
        c1 = self.c1

        self.addStuffInMultipleContexts()
        self.assertEquals(len(Graph(self.graph.store, c1)), 1)
        self.assertEquals(len(self.get_context(c1)), 1)

        self.graph.remove_context(self.get_context(c1))
        self.assert_(self.c1 not in self.graph.contexts())

    def testRemoveAny(self):
        Any = None
        self.addStuffInMultipleContexts()
        self.graph.remove((Any, Any, Any))
        self.assertEquals(len(self.graph), 0)

    def testTriples(self):
        triples = self.graph.triples
        graph = self.graph
        c1graph = Graph(self.graph.store, self.c1)
        c1triples = c1graph.triples
        Any = None

        self.addStuff()

        # unbound subjects with context
        self.assertEquals(len(list(c1triples((Any, self.likes, self.pizza)))), 2)
        self.assertEquals(len(list(c1triples((Any, self.hates, self.pizza)))), 1)
        self.assertEquals(len(list(c1triples((Any, self.likes, self.cheese)))), 3)
        self.assertEquals(len(list(c1triples((Any, self.hates, self.cheese)))), 0)

        # unbound subjects without context, same results!
        self.assertEquals(len(list(triples((Any, self.likes, self.pizza)))), 2)
        self.assertEquals(len(list(triples((Any, self.hates, self.pizza)))), 1)
        self.assertEquals(len(list(triples((Any, self.likes, self.cheese)))), 3)
        self.assertEquals(len(list(triples((Any, self.hates, self.cheese)))), 0)

        # unbound objects with context
        self.assertEquals(len(list(c1triples((self.michel, self.likes, Any)))), 2)
        self.assertEquals(len(list(c1triples((self.tarek, self.likes, Any)))), 2)
        self.assertEquals(len(list(c1triples((self.bob, self.hates, Any)))), 2)
        self.assertEquals(len(list(c1triples((self.bob, self.likes, Any)))), 1)

        # unbound objects without context, same results!
        self.assertEquals(len(list(triples((self.michel, self.likes, Any)))), 2)
        self.assertEquals(len(list(triples((self.tarek, self.likes, Any)))), 2)
        self.assertEquals(len(list(triples((self.bob, self.hates, Any)))), 2)
        self.assertEquals(len(list(triples((self.bob, self.likes, Any)))), 1)

        # unbound predicates with context
        self.assertEquals(len(list(c1triples((self.michel, Any, self.cheese)))), 1)
        self.assertEquals(len(list(c1triples((self.tarek, Any, self.cheese)))), 1)
        self.assertEquals(len(list(c1triples((self.bob, Any, self.pizza)))), 1)
        self.assertEquals(len(list(c1triples((self.bob, Any, self.michel)))), 1)

        # unbound predicates without context, same results!
        self.assertEquals(len(list(triples((self.michel, Any, self.cheese)))), 1)
        self.assertEquals(len(list(triples((self.tarek, Any, self.cheese)))), 1)
        self.assertEquals(len(list(triples((self.bob, Any, self.pizza)))), 1)
        self.assertEquals(len(list(triples((self.bob, Any, self.michel)))), 1)

        # unbound subject, objects with context
        self.assertEquals(len(list(c1triples((Any, self.hates, Any)))), 2)
        self.assertEquals(len(list(c1triples((Any, self.likes, Any)))), 5)

        # unbound subject, objects without context, same results!
        self.assertEquals(len(list(triples((Any, self.hates, Any)))), 2)
        self.assertEquals(len(list(triples((Any, self.likes, Any)))), 5)

        # unbound predicates, objects with context
        self.assertEquals(len(list(c1triples((self.michel, Any, Any)))), 2)
        self.assertEquals(len(list(c1triples((self.bob, Any, Any)))), 3)
        self.assertEquals(len(list(c1triples((self.tarek, Any, Any)))), 2)

        # unbound predicates, objects without context, same results!
        self.assertEquals(len(list(triples((self.michel, Any, Any)))), 2)
        self.assertEquals(len(list(triples((self.bob, Any, Any)))), 3)
        self.assertEquals(len(list(triples((self.tarek, Any, Any)))), 2)

        # unbound subjects, predicates with context
        self.assertEquals(len(list(c1triples((Any, Any, self.pizza)))), 3)
        self.assertEquals(len(list(c1triples((Any, Any, self.cheese)))), 3)
        self.assertEquals(len(list(c1triples((Any, Any, self.michel)))), 1)

        # unbound subjects, predicates without context, same results!
        self.assertEquals(len(list(triples((Any, Any, self.pizza)))), 3)
        self.assertEquals(len(list(triples((Any, Any, self.cheese)))), 3)
        self.assertEquals(len(list(triples((Any, Any, self.michel)))), 1)

        # all unbound with context
        self.assertEquals(len(list(c1triples((Any, Any, Any)))), 7)
        # all unbound without context, same result!
        self.assertEquals(len(list(triples((Any, Any, Any)))), 7)

        for c in [graph, self.get_context(self.c1)]:
            # unbound subjects
            self.assertEquals(set(c.subjects(self.likes, self.pizza)), {self.michel, self.tarek})
            self.assertEquals(set(c.subjects(self.hates, self.pizza)), {self.bob})
            self.assertEquals(set(c.subjects(self.likes, self.cheese)), {self.tarek, self.bob, self.michel})
            self.assertEquals(set(c.subjects(self.hates, self.cheese)), set())

            # unbound objects
            self.assertEquals(set(c.objects(self.michel, self.likes)), {self.cheese, self.pizza})
            self.assertEquals(set(c.objects(self.tarek, self.likes)), {self.cheese, self.pizza})
            self.assertEquals(set(c.objects(self.bob, self.hates)), {self.michel, self.pizza})
            self.assertEquals(set(c.objects(self.bob, self.likes)), {self.cheese})

            # unbound predicates
            self.assertEquals(set(c.predicates(self.michel, self.cheese)), {self.likes})
            self.assertEquals(set(c.predicates(self.tarek, self.cheese)), {self.likes})
            self.assertEquals(set(c.predicates(self.bob, self.pizza)), {self.hates})
            self.assertEquals(set(c.predicates(self.bob, self.michel)), {self.hates})

            self.assertEquals(set(c.subject_objects(self.hates)), {(self.bob, self.pizza), (self.bob, self.michel)})
            self.assertEquals(set(c.subject_objects(self.likes)),
                    {(self.tarek, self.cheese), (self.michel, self.cheese), (self.michel, self.pizza), (self.bob, self.cheese), (self.tarek, self.pizza)})

            self.assertEquals(set(c.predicate_objects(self.michel)), {(self.likes, self.cheese), (self.likes, self.pizza)})
            self.assertEquals(set(c.predicate_objects(self.bob)), {(self.likes, self.cheese), (self.hates, self.pizza), (self.hates, self.michel)})
            self.assertEquals(set(c.predicate_objects(self.tarek)), {(self.likes, self.cheese), (self.likes, self.pizza)})

            self.assertEquals(set(c.subject_predicates(self.pizza)), {(self.bob, self.hates), (self.tarek, self.likes), (self.michel, self.likes)})
            self.assertEquals(set(c.subject_predicates(self.cheese)), {(self.bob, self.likes), (self.tarek, self.likes), (self.michel, self.likes)})
            self.assertEquals(set(c.subject_predicates(self.michel)), {(self.bob, self.hates)})

            self.assertEquals(set(c), {(self.bob, self.hates, self.michel), (self.bob, self.likes, self.cheese), (self.tarek, self.likes, self.pizza),
                (self.michel, self.likes, self.pizza), (self.michel, self.likes, self.cheese), (self.bob, self.hates, self.pizza),
                (self.tarek, self.likes, self.cheese)})

        # remove stuff and make sure the graph is empty again
        self.removeStuff()
        self.assertEquals(len(list(c1triples((Any, Any, Any)))), 0)
        self.assertEquals(len(list(triples((Any, Any, Any)))), 0)
예제 #25
0
def DoTheTestMemory():
    ns = Namespace("http://love.com#")

    # AssertionError: ConjunctiveGraph must be backed by a context aware store.
    mary = URIRef("http://love.com/lovers/mary")
    john = URIRef("http://love.com/lovers/john")

    cmary = URIRef("http://love.com/lovers/context_mary")
    cjohn = URIRef("http://love.com/lovers/context_john")

    # my_store = Memory()
    store_input = IOMemory()

    gconjunctive = ConjunctiveGraph(store=store_input)
    gconjunctive.bind("love", ns)

    # add a graph for Mary's facts to the Conjunctive Graph
    gmary = Graph(store=store_input, identifier=cmary)
    # Mary's graph only contains the URI of the person she love, not his cute name
    gmary.add((mary, ns["hasName"], Literal("Mary")))
    gmary.add((mary, ns["loves"], john))

    # add a graph for John's facts to the Conjunctive Graph
    gjohn = Graph(store=store_input, identifier=cjohn)
    # John's graph contains his cute name
    gjohn.add((john, ns["hasCuteName"], Literal("Johnny Boy")))

    # enumerate contexts
    print("Input contexts")
    for c in gconjunctive.contexts():
        print("-- %s " % c)

    # separate graphs
    if False:
        print("===================")
        print("GJOHN")
        print(gjohn.serialize(format="n3").decode("utf-8"))
        print("===================")
        print("GMARY")
        print(gmary.serialize(format="n3").decode("utf-8"))
        print("===================")

    # full graph
    print("===================")
    print("GCONJUNCTIVE NATIVE")
    print(gconjunctive.serialize(format="n3").decode("utf-8"))

    # query the conjunction of all graphs
    xx = None
    for x in gconjunctive[mary:ns.loves / ns.hasCuteName]:
        xx = x
    print("Q: Who does Mary love?")
    print("A: Mary loves {}".format(xx))

    # Ensuite, on sauve un seul sous-graphe, puis on le recharge et le resultat doit etre le meme.
    gjohn.serialize(destination='gjohn_copy.xml', format='xml')
    gmary.serialize(destination='gmary_copy.xml', format='xml')

    gjohn_copy = Graph()
    gjohn_copy.parse('gjohn_copy.xml', format='xml')
    gmary_copy = Graph()
    gmary_copy.parse('gmary_copy.xml', format='xml')

    if True:
        print("===================")
        print("GJOHN")
        print(gjohn_copy.serialize(format="n3").decode("utf-8"))
        print("===================")
        print("GMARY")
        print(gmary_copy.serialize(format="n3").decode("utf-8"))
        print("===================")

    print("===================")
    print("GCONJUNCTIVE WITH QUADS")
    print(list(gconjunctive.quads(None)))
    print("===================")

    gconjunctive.serialize(destination='gconjunctive_copy.xml', format='xml')

    gconjunctive_copy = ConjunctiveGraph()
    gconjunctive_copy.parse('gconjunctive_copy.xml', format='xml')

    print("===================")
    print("GCONJUNCTIVE AS CONJUNCTIVE")
    print(gconjunctive_copy.serialize(format="n3").decode("utf-8"))
    print("Output contexts")
    for c in gconjunctive_copy.contexts():
        print("-- %s " % c)
    print("===================")

    gconjunctive_graph_copy = Graph()
    gconjunctive_graph_copy.parse('gconjunctive_copy.xml', format='xml')

    print("===================")
    print("GCONJUNCTIVE AS GRAPH")
    print(gconjunctive_graph_copy.serialize(format="n3").decode("utf-8"))
    #print("Output contexts")
    #for c in gconjunctive_graph_copy.contexts():
    #    print("-- %s " % c)
    print("===================")
예제 #26
0
class ContextTest(TestCase):
    """
    Testing different contexts.

    Heavily based on https://github.com/RDFLib/rdflib-postgresql/blob/master/test/context_case.py
    """  # noqa: E501
    store_name = "Django"
    storetest = True
    path = ""
    create = True

    michel = URIRef(u'michel')
    tarek = URIRef(u'tarek')
    bob = URIRef(u'bob')
    likes = URIRef(u'likes')
    hates = URIRef(u'hates')
    pizza = URIRef(u'pizza')
    cheese = URIRef(u'cheese')
    c1 = URIRef(u'context-1')
    c2 = URIRef(u'context-2')

    def setUp(self):
        self.graph = ConjunctiveGraph(store=self.store_name)
        self.graph.destroy(self.path)
        self.graph.open(self.path, create=self.create)

    def tearDown(self):
        self.graph.destroy(self.path)
        self.graph.close()

    def get_context(self, identifier):
        assert isinstance(identifier, URIRef) or isinstance(identifier, BNode), type(identifier)  # noqa: E501
        return Graph(store=self.graph.store, identifier=identifier, namespace_manager=self)  # noqa: E501

    def addStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.add((tarek, likes, pizza))
        graph.add((tarek, likes, cheese))
        graph.add((michel, likes, pizza))
        graph.add((michel, likes, cheese))
        graph.add((bob, likes, cheese))
        graph.add((bob, hates, pizza))
        graph.add((bob, hates, michel))

    def removeStuff(self):
        tarek = self.tarek
        michel = self.michel
        bob = self.bob
        likes = self.likes
        hates = self.hates
        pizza = self.pizza
        cheese = self.cheese
        c1 = self.c1
        graph = Graph(self.graph.store, c1)

        graph.remove((tarek, likes, pizza))
        graph.remove((tarek, likes, cheese))
        graph.remove((michel, likes, pizza))
        graph.remove((michel, likes, cheese))
        graph.remove((bob, likes, cheese))
        graph.remove((bob, hates, pizza))
        graph.remove((bob, hates, michel))

    def addStuffInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek)

        # add to default context
        self.graph.add(triple)
        # add to context 1
        graph = Graph(self.graph.store, c1)
        graph.add(triple)
        # add to context 2
        graph = Graph(self.graph.store, c2)
        graph.add(triple)

    def testConjunction(self):
        self.addStuffInMultipleContexts()
        triple = (self.pizza, self.likes, self.pizza)
        # add to context 1
        graph = Graph(self.graph.store, self.c1)
        graph.add(triple)

        self.assertEquals(len(graph), 2)
        self.assertEquals(len(self.graph), 2)

    def testAdd(self):
        self.addStuff()

    def testRemove(self):
        self.addStuff()
        self.removeStuff()

    def testLenInOneContext(self):
        c1 = self.c1
        # make sure context is empty

        self.graph.remove_context(self.get_context(c1))
        graph = Graph(self.graph.store, c1)
        oldLen = len(self.graph)

        for _ in range(0, 10):
            graph.add((BNode(), self.hates, self.hates))
        self.assertEquals(len(graph), oldLen + 10)
        self.assertEquals(len(self.get_context(c1)), oldLen + 10)
        self.graph.remove_context(self.get_context(c1))
        self.assertEquals(len(self.graph), oldLen)
        self.assertEquals(len(graph), 0)

    def testLenInMultipleContexts(self):
        oldLen = len(self.graph)
        self.addStuffInMultipleContexts()

        # addStuffInMultipleContexts is adding the same triple to
        # three different contexts. So it's only + 1
        self.assertEquals(len(self.graph), oldLen + 1)

        graph = Graph(self.graph.store, self.c1)
        self.assertEquals(len(graph), oldLen + 1)

    def testRemoveInMultipleContexts(self):
        c1 = self.c1
        c2 = self.c2
        triple = (self.pizza, self.hates, self.tarek)

        self.addStuffInMultipleContexts()

        # triple should be still in store after removing it from c1 + c2
        self.assertIn(triple, self.graph)
        graph = Graph(self.graph.store, c1)
        graph.remove(triple)
        self.assertIn(triple, self.graph)
        graph = Graph(self.graph.store, c2)
        graph.remove(triple)
        self.assertIn(triple, self.graph)
        self.graph.remove(triple)
        # now gone!
        self.assertNotIn(triple, self.graph)

        # add again and see if remove without context removes all triples!
        self.addStuffInMultipleContexts()
        self.graph.remove(triple)
        self.assertNotIn(triple, self.graph)

    def testContexts(self):
        triple = (self.pizza, self.hates, self.tarek)

        self.addStuffInMultipleContexts()

        def cid(c):
            if not isinstance(c, str):
                return c.identifier
            return c

        self.assertIn(self.c1, [cid(c) for c in self.graph.contexts()])
        self.assertIn(self.c2, [cid(c) for c in self.graph.contexts()])

        contextList = [cid(c) for c in self.graph.contexts(triple)]
        self.assertIn(self.c1, contextList)
        self.assertIn(self.c2, contextList)

    def testRemoveContext(self):
        c1 = self.c1

        self.addStuffInMultipleContexts()
        self.assertEquals(len(Graph(self.graph.store, c1)), 1)
        self.assertEquals(len(self.get_context(c1)), 1)

        self.graph.remove_context(self.get_context(c1))
        self.assert_(self.c1 not in self.graph.contexts())

    def testRemoveAny(self):
        Any = None
        self.addStuffInMultipleContexts()
        self.graph.remove((Any, Any, Any))
        self.assertEquals(len(self.graph), 0)

    def testTriples(self):
        triples = self.graph.triples
        graph = self.graph
        c1graph = Graph(self.graph.store, self.c1)
        c1triples = c1graph.triples
        Any = None

        self.addStuff()

        # unbound subjects with context
        self.assertEquals(
            len(
                list(
                    c1triples((Any, self.likes, self.pizza))
                )
            ), 2
        )
        self.assertEquals(
            len(
                list(
                    c1triples((Any, self.hates, self.pizza))
                )
            ), 1
        )
        self.assertEquals(
            len(
                list(
                    c1triples((Any, self.likes, self.cheese))
                )
            ), 3
        )
        self.assertEquals(
            len(
                list(
                    c1triples((Any, self.hates, self.cheese))
                )
            ), 0
        )

        # unbound subjects without context, same results!
        self.assertEquals(len(list(triples((Any, self.likes, self.pizza)))), 2)
        self.assertEquals(len(list(triples((Any, self.hates, self.pizza)))), 1)
        self.assertEquals(len(list(triples((Any, self.likes, self.cheese)))), 3)
        self.assertEquals(len(list(triples((Any, self.hates, self.cheese)))), 0)

        # unbound objects with context
        self.assertEquals(len(list(c1triples((self.michel, self.likes, Any)))), 2)
        self.assertEquals(len(list(c1triples((self.tarek, self.likes, Any)))), 2)
        self.assertEquals(len(list(c1triples((self.bob, self.hates, Any)))), 2)
        self.assertEquals(len(list(c1triples((self.bob, self.likes, Any)))), 1)

        # unbound objects without context, same results!
        self.assertEquals(len(list(triples((self.michel, self.likes, Any)))), 2)
        self.assertEquals(len(list(triples((self.tarek, self.likes, Any)))), 2)
        self.assertEquals(len(list(triples((self.bob, self.hates, Any)))), 2)
        self.assertEquals(len(list(triples((self.bob, self.likes, Any)))), 1)

        # unbound predicates with context
        self.assertEquals(len(list(c1triples((self.michel, Any, self.cheese)))), 1)
        self.assertEquals(len(list(c1triples((self.tarek, Any, self.cheese)))), 1)
        self.assertEquals(len(list(c1triples((self.bob, Any, self.pizza)))), 1)
        self.assertEquals(len(list(c1triples((self.bob, Any, self.michel)))), 1)

        # unbound predicates without context, same results!
        self.assertEquals(len(list(triples((self.michel, Any, self.cheese)))), 1)
        self.assertEquals(len(list(triples((self.tarek, Any, self.cheese)))), 1)
        self.assertEquals(len(list(triples((self.bob, Any, self.pizza)))), 1)
        self.assertEquals(len(list(triples((self.bob, Any, self.michel)))), 1)

        # unbound subject, objects with context
        self.assertEquals(len(list(c1triples((Any, self.hates, Any)))), 2)
        self.assertEquals(len(list(c1triples((Any, self.likes, Any)))), 5)

        # unbound subject, objects without context, same results!
        self.assertEquals(len(list(triples((Any, self.hates, Any)))), 2)
        self.assertEquals(len(list(triples((Any, self.likes, Any)))), 5)

        # unbound predicates, objects with context
        self.assertEquals(len(list(c1triples((self.michel, Any, Any)))), 2)
        self.assertEquals(len(list(c1triples((self.bob, Any, Any)))), 3)
        self.assertEquals(len(list(c1triples((self.tarek, Any, Any)))), 2)

        # unbound predicates, objects without context, same results!
        self.assertEquals(len(list(triples((self.michel, Any, Any)))), 2)
        self.assertEquals(len(list(triples((self.bob, Any, Any)))), 3)
        self.assertEquals(len(list(triples((self.tarek, Any, Any)))), 2)

        # unbound subjects, predicates with context
        self.assertEquals(len(list(c1triples((Any, Any, self.pizza)))), 3)
        self.assertEquals(len(list(c1triples((Any, Any, self.cheese)))), 3)
        self.assertEquals(len(list(c1triples((Any, Any, self.michel)))), 1)

        # unbound subjects, predicates without context, same results!
        self.assertEquals(len(list(triples((Any, Any, self.pizza)))), 3)
        self.assertEquals(len(list(triples((Any, Any, self.cheese)))), 3)
        self.assertEquals(len(list(triples((Any, Any, self.michel)))), 1)

        # all unbound with context
        self.assertEquals(len(list(c1triples((Any, Any, Any)))), 7)
        # all unbound without context, same result!
        self.assertEquals(len(list(triples((Any, Any, Any)))), 7)

        for c in [graph, self.get_context(self.c1)]:
            # unbound subjects
            self.assertEquals(set(c.subjects(self.likes, self.pizza)), {self.michel, self.tarek})
            self.assertEquals(set(c.subjects(self.hates, self.pizza)), {self.bob})
            self.assertEquals(set(c.subjects(self.likes, self.cheese)), {self.tarek, self.bob, self.michel})
            self.assertEquals(set(c.subjects(self.hates, self.cheese)), set())

            # unbound objects
            self.assertEquals(set(c.objects(self.michel, self.likes)), {self.cheese, self.pizza})
            self.assertEquals(set(c.objects(self.tarek, self.likes)), {self.cheese, self.pizza})
            self.assertEquals(set(c.objects(self.bob, self.hates)), {self.michel, self.pizza})
            self.assertEquals(set(c.objects(self.bob, self.likes)), {self.cheese})

            # unbound predicates
            self.assertEquals(
                set(
                    c.predicates(self.michel, self.cheese)
                ),
                {self.likes}
            )
            self.assertEquals(
                set(
                    c.predicates(self.tarek, self.cheese)
                ),
                {self.likes}
            )
            self.assertEquals(set(c.predicates(self.bob, self.pizza)), {self.hates})
            self.assertEquals(set(c.predicates(self.bob, self.michel)), {self.hates})

            self.assertEquals(set(c.subject_objects(self.hates)), {(self.bob, self.pizza), (self.bob, self.michel)})
            self.assertEquals(set(c.subject_objects(self.likes)),
                    {(self.tarek, self.cheese), (self.michel, self.cheese), (self.michel, self.pizza), (self.bob, self.cheese), (self.tarek, self.pizza)})

            self.assertEquals(set(c.predicate_objects(self.michel)), {(self.likes, self.cheese), (self.likes, self.pizza)})
            self.assertEquals(set(c.predicate_objects(self.bob)), {(self.likes, self.cheese), (self.hates, self.pizza), (self.hates, self.michel)})
            self.assertEquals(set(c.predicate_objects(self.tarek)), {(self.likes, self.cheese), (self.likes, self.pizza)})

            self.assertEquals(set(c.subject_predicates(self.pizza)), {(self.bob, self.hates), (self.tarek, self.likes), (self.michel, self.likes)})
            self.assertEquals(set(c.subject_predicates(self.cheese)), {(self.bob, self.likes), (self.tarek, self.likes), (self.michel, self.likes)})
            self.assertEquals(set(c.subject_predicates(self.michel)), {(self.bob, self.hates)})

            self.assertEquals(set(c), {(self.bob, self.hates, self.michel), (self.bob, self.likes, self.cheese), (self.tarek, self.likes, self.pizza),
                (self.michel, self.likes, self.pizza), (self.michel, self.likes, self.cheese), (self.bob, self.hates, self.pizza),
                (self.tarek, self.likes, self.cheese)})

        # remove stuff and make sure the graph is empty again
        self.removeStuff()
        self.assertEquals(len(list(c1triples((Any, Any, Any)))), 0)
        self.assertEquals(len(list(triples((Any, Any, Any)))), 0)
예제 #27
0
 def test_02_contexts(self):
     g = ConjunctiveGraph(self.store)
     for c in g.contexts():
         assert isinstance(c, Graph)
         break