def test_exclude_xhtml(self): ns = "http://www.w3.org/1999/xhtml/vocab#" kg = ConjunctiveGraph() kg.add(( BNode(), URIRef("http://www.w3.org/1999/xhtml/vocab#role"), URIRef("http://www.w3.org/1999/xhtml/vocab#button"), )) print(kg.serialize(format="turtle")) q_xhtml = ('SELECT * WHERE { ?s ?p ?o . FILTER (strstarts(str(?p), "' + ns + '"))}') print(q_xhtml) res = kg.query(q_xhtml) self.assertEquals(len(res), 1) q_del = ( 'DELETE {?s ?p ?o} WHERE { ?s ?p ?o . FILTER (strstarts(str(?p), "' + ns + '"))}') kg.update(q_del) print(kg.serialize(format="turtle")) res = kg.query(q_xhtml) self.assertEquals(len(res), 0)
def post(g, URLendpoint, graphURI): # eseguo la post del grafo g nel database specificato output = { 'risposta': [] } endpoint = ConjunctiveGraph ('SPARQLUpdateStore') endpoint.open(URLendpoint) enddata = """INSERT DATA { GRAPH <"""+graphURI+"""> { %s } }""" % g.serialize(format="nt") endpoint.update(enddata) output['risposta'].append(g.serialize(format="turtle"))
def apply_inference_sparql( inference_directory: Path, graph: ConjunctiveGraph, ) -> bool: """Apply custom SPARQL inference rules.""" if inference_directory.is_dir(): query_files = list(sorted( # noqa: C413 inference_directory.glob('**/*.sparql'), )) else: query_files = [] if not query_files: logger.info( 'No SPARQL inference files found at %s directory.', inference_directory, ) return False logger.warning( 'SPARQL inference queries are an outdated feature. Files: %s', query_files, ) for query_file in query_files: logger.info( 'Inference: %s', query_file.relative_to(inference_directory), ) query_text = query_file.read_text() logger.debug(' Query text: %s', textwrap.indent( query_text, prefix=' ', )) graph.update(query_text) return True
class TestSparql11(unittest.TestCase): def setUp(self): self.longMessage = True self.graph = ConjunctiveGraph('SPARQLUpdateStore') root = "http://localhost:3030/ukpp/" self.graph.open((root + "sparql", root + "update")) # clean out the store for c in self.graph.contexts(): c.remove((None, None, None)) assert len(c) == 0 def tearDown(self): self.graph.close() def testSimpleGraph(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g.add((bob, likes, pizza)) g.add((bob, likes, cheese)) g2 = self.graph.get_context(othergraphuri) g2.add((michel, likes, pizza)) self.assertEquals(3, len(g), 'graph contains 3 triples') self.assertEquals(1, len(g2), 'other graph contains 1 triple') r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = g.triples((None, likes, pizza)) self.assertEquals(2, len(list(r)), "two people like pizza") # Test initBindings r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.add((tarek, likes, pizza)) g.remove((tarek, likes, pizza)) r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only bob likes pizza") def testConjunctiveDefault(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g2 = self.graph.get_context(othergraphuri) g2.add((bob, likes, pizza)) g.add((tarek, hates, cheese)) self.assertEquals(2, len(g), 'graph contains 2 triples') self.assertEquals(3, len(self.graph), 'default union graph contains three triples') r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.remove((bob, likes, pizza)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only tarek likes pizza") def testUpdate(self): self.graph.update("INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }") g = self.graph.get_context(graphuri) self.assertEquals(1, len(g), 'graph contains 1 triples') def testUpdateWithInitNs(self): self.graph.update( "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }", initNs={'ns': URIRef('urn:')} ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) def testUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WherE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), } ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) def testMultipleUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WHERE { };" "INSERT { GRAPH <urn:graph> { ?d ?b ?c . } } WHERE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), 'd': URIRef('urn:bob'), } ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza), (bob,likes,pizza)]), 'michel and bob like pizza' ) def testNamedGraphUpdate(self): g = self.graph.get_context(graphuri) r1 = "INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }" g.update(r1) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) r2 = "DELETE { <urn:michel> <urn:likes> <urn:pizza> } " + \ "INSERT { <urn:bob> <urn:likes> <urn:pizza> } WHERE {}" g.update(r2) self.assertEquals( set(g.triples((None, None, None))), set([(bob, likes, pizza)]), 'only bob likes pizza' ) says = URIRef("urn:says") # Strings with unbalanced curly braces tricky_strs = ["With an unbalanced curly brace %s " % brace for brace in ["{", "}"]] for tricky_str in tricky_strs: r3 = """INSERT { ?b <urn:says> "%s" } WHERE { ?b <urn:likes> <urn:pizza>} """ % tricky_str g.update(r3) values = set() for v in g.objects(bob, says): values.add(str(v)) self.assertEquals(values, set(tricky_strs)) # Complicated Strings r4strings = [] r4strings.append(ur'''"1: adfk { ' \\\" \" { "''') r4strings.append(ur'''"2: adfk } <foo> #éï \\"''') r4strings.append(ur"""'3: adfk { " \\\' \' { '""") r4strings.append(ur"""'4: adfk } <foo> #éï \\'""") r4strings.append(ur'''"""5: adfk { ' \\\" \" { """''') r4strings.append(ur'''"""6: adfk } <foo> #éï \\"""''') r4strings.append(u'"""7: ad adsfj \n { \n sadfj"""') r4strings.append(ur"""'''8: adfk { " \\\' \' { '''""") r4strings.append(ur"""'''9: adfk } <foo> #éï \\'''""") r4strings.append(u"'''10: ad adsfj \n { \n sadfj'''") r4 = "\n".join([ u'INSERT DATA { <urn:michel> <urn:says> %s } ;' % s for s in r4strings ]) g.update(r4) values = set() for v in g.objects(michel, says): values.add(unicode(v)) self.assertEquals(values, set([re.sub(ur"\\(.)", ur"\1", re.sub(ur"^'''|'''$|^'|'$|" + ur'^"""|"""$|^"|"$', ur"", s)) for s in r4strings]))
class TestSparql11(unittest.TestCase): def setUp(self): self.longMessage = True self.graph = ConjunctiveGraph('SPARQLUpdateStore') root = HOST + DB self.graph.open((root + "sparql", root + "update")) # clean out the store for c in self.graph.contexts(): c.remove((None, None, None)) assert len(c) == 0 def tearDown(self): self.graph.close() def testSimpleGraph(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g.add((bob, likes, pizza)) g.add((bob, likes, cheese)) g2 = self.graph.get_context(othergraphuri) g2.add((michel, likes, pizza)) self.assertEqual(3, len(g), 'graph contains 3 triples') self.assertEqual(1, len(g2), 'other graph contains 1 triple') r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEqual(2, len(list(r)), "two people like pizza") r = g.triples((None, likes, pizza)) self.assertEqual(2, len(list(r)), "two people like pizza") # Test initBindings r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEqual(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, pizza)) self.assertEqual(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, cheese)) self.assertEqual(0, len(list(r)), "tarek doesn't like cheese") g2.add((tarek, likes, pizza)) g.remove((tarek, likes, pizza)) r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEqual(1, len(list(r)), "only bob likes pizza") def testConjunctiveDefault(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g2 = self.graph.get_context(othergraphuri) g2.add((bob, likes, pizza)) g.add((tarek, hates, cheese)) self.assertEqual(2, len(g), 'graph contains 2 triples') # the following are actually bad tests as they depend on your endpoint, # as pointed out in the sparqlstore.py code: # # For ConjunctiveGraphs, reading is done from the "default graph" Exactly # what this means depends on your endpoint, because SPARQL does not offer a # simple way to query the union of all graphs as it would be expected for a # ConjuntiveGraph. ## # Fuseki/TDB has a flag for specifying that the default graph # is the union of all graphs (tdb:unionDefaultGraph in the Fuseki config). self.assertEqual( 3, len(self.graph), 'default union graph should contain three triples but contains:\n' '%s' % list(self.graph)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEqual(2, len(list(r)), "two people like pizza") r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEqual(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, pizza)) self.assertEqual(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, cheese)) self.assertEqual(0, len(list(r)), "tarek doesn't like cheese") g2.remove((bob, likes, pizza)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEqual(1, len(list(r)), "only tarek likes pizza") def testUpdate(self): self.graph.update( "INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }" ) g = self.graph.get_context(graphuri) self.assertEqual(1, len(g), 'graph contains 1 triples') def testUpdateWithInitNs(self): self.graph.update( "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }", initNs={'ns': URIRef('urn:')}) g = self.graph.get_context(graphuri) self.assertEqual(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') def testUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WherE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), }) g = self.graph.get_context(graphuri) self.assertEqual(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') def testUpdateWithBlankNode(self): self.graph.update( "INSERT DATA { GRAPH <urn:graph> { _:blankA <urn:type> <urn:Blank> } }" ) g = self.graph.get_context(graphuri) for t in g.triples((None, None, None)): self.assertTrue(isinstance(t[0], BNode)) self.assertEqual(t[1].n3(), "<urn:type>") self.assertEqual(t[2].n3(), "<urn:Blank>") def testUpdateWithBlankNodeSerializeAndParse(self): self.graph.update( "INSERT DATA { GRAPH <urn:graph> { _:blankA <urn:type> <urn:Blank> } }" ) g = self.graph.get_context(graphuri) string = g.serialize(format='ntriples').decode('utf-8') raised = False try: Graph().parse(data=string, format="ntriples") except Exception as e: raised = True self.assertFalse(raised, 'Exception raised when parsing: ' + string) def testMultipleUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WHERE { };" "INSERT { GRAPH <urn:graph> { ?d ?b ?c . } } WHERE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), 'd': URIRef('urn:bob'), }) g = self.graph.get_context(graphuri) self.assertEqual(set(g.triples((None, None, None))), set([(michel, likes, pizza), (bob, likes, pizza)]), 'michel and bob like pizza') def testNamedGraphUpdate(self): g = self.graph.get_context(graphuri) r1 = "INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }" g.update(r1) self.assertEqual(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') r2 = "DELETE { <urn:michel> <urn:likes> <urn:pizza> } " + \ "INSERT { <urn:bob> <urn:likes> <urn:pizza> } WHERE {}" g.update(r2) self.assertEqual(set(g.triples((None, None, None))), set([(bob, likes, pizza)]), 'only bob likes pizza') says = URIRef("urn:says") # Strings with unbalanced curly braces tricky_strs = [ "With an unbalanced curly brace %s " % brace for brace in ["{", "}"] ] for tricky_str in tricky_strs: r3 = """INSERT { ?b <urn:says> "%s" } WHERE { ?b <urn:likes> <urn:pizza>} """ % tricky_str g.update(r3) values = set() for v in g.objects(bob, says): values.add(str(v)) self.assertEqual(values, set(tricky_strs)) # Complicated Strings r4strings = [] r4strings.append(r'''"1: adfk { ' \\\" \" { "''') r4strings.append(r'''"2: adfk } <foo> #éï \\"''') r4strings.append(r"""'3: adfk { " \\\' \' { '""") r4strings.append(r"""'4: adfk } <foo> #éï \\'""") r4strings.append(r'''"""5: adfk { ' \\\" \" { """''') r4strings.append(r'''"""6: adfk } <foo> #éï \\"""''') r4strings.append('"""7: ad adsfj \n { \n sadfj"""') r4strings.append(r"""'''8: adfk { " \\\' \' { '''""") r4strings.append(r"""'''9: adfk } <foo> #éï \\'''""") r4strings.append("'''10: ad adsfj \n { \n sadfj'''") r4 = "\n".join([ u'INSERT DATA { <urn:michel> <urn:says> %s } ;' % s for s in r4strings ]) g.update(r4) values = set() for v in g.objects(michel, says): values.add(text_type(v)) self.assertEqual( values, set([ re.sub( r"\\(.)", r"\1", re.sub(r"^'''|'''$|^'|'$|" + r'^"""|"""$|^"|"$', r"", s)) for s in r4strings ])) # IRI Containing ' or # # The fragment identifier must not be misinterpreted as a comment # (commenting out the end of the block). # The ' must not be interpreted as the start of a string, causing the } # in the literal to be identified as the end of the block. r5 = """INSERT DATA { <urn:michel> <urn:hates> <urn:foo'bar?baz;a=1&b=2#fragment>, "'}" }""" g.update(r5) values = set() for v in g.objects(michel, hates): values.add(text_type(v)) self.assertEqual(values, set([u"urn:foo'bar?baz;a=1&b=2#fragment", u"'}"])) # Comments r6 = u""" INSERT DATA { <urn:bob> <urn:hates> <urn:bob> . # No closing brace: } <urn:bob> <urn:hates> <urn:michel>. } #Final { } comment""" g.update(r6) values = set() for v in g.objects(bob, hates): values.add(v) self.assertEqual(values, set([bob, michel])) def testNamedGraphUpdateWithInitBindings(self): g = self.graph.get_context(graphuri) r = "INSERT { ?a ?b ?c } WHERE {}" g.update(r, initBindings={'a': michel, 'b': likes, 'c': pizza}) self.assertEqual(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') def testEmptyNamedGraph(self): empty_graph_iri = "urn:empty-graph-1" self.graph.update("CREATE GRAPH <%s>" % empty_graph_iri) named_graphs = [ text_type(r[0]) for r in self.graph.query("SELECT ?name WHERE { GRAPH ?name {} }") ] # Some SPARQL endpoint backends (like TDB) are not able to find empty named graphs # (at least with this query) if empty_graph_iri in named_graphs: self.assertTrue( empty_graph_iri in [text_type(g.identifier) for g in self.graph.contexts()]) def testEmptyLiteral(self): # test for https://github.com/RDFLib/rdflib/issues/457 # also see test_issue457.py which is sparql store independent! g = self.graph.get_context(graphuri) g.add((URIRef('http://example.com/s'), URIRef('http://example.com/p'), Literal(''))) o = tuple(g)[0][2] self.assertEqual(o, Literal(''), repr(o))
class BerkeleyDBTestCase(unittest.TestCase): def setUp(self): if not has_bsddb: self.skipTest("skipping as berkleydb is missing") self.store_name = "BerkeleyDB" self.path = mktemp() self.g = ConjunctiveGraph(store=self.store_name) self.rt = self.g.open(self.path, create=True) assert self.rt == VALID_STORE, "The underlying store is corrupt" assert ( len(self.g) == 0 ), "There must be zero triples in the graph just after store (file) creation" data = """ PREFIX : <https://example.org/> :a :b :c . :d :e :f . :d :g :h . """ self.g.parse(data=data, format="ttl") def tearDown(self): self.g.close() def test_write(self): assert ( len(self.g) == 3 ), "There must be three triples in the graph after the first data chunk parse" data2 = """ PREFIX : <https://example.org/> :d :i :j . """ self.g.parse(data=data2, format="ttl") assert ( len(self.g) == 4 ), "There must be four triples in the graph after the second data chunk parse" data3 = """ PREFIX : <https://example.org/> :d :i :j . """ self.g.parse(data=data3, format="ttl") assert ( len(self.g) == 4 ), "There must still be four triples in the graph after the thrd data chunk parse" def test_read(self): sx = None for s in self.g.subjects( predicate=URIRef("https://example.org/e"), object=URIRef("https://example.org/f"), ): sx = s assert sx == URIRef("https://example.org/d") def test_sparql_query(self): q = """ PREFIX : <https://example.org/> SELECT (COUNT(*) AS ?c) WHERE { :d ?p ?o . }""" c = 0 for row in self.g.query(q): c = int(row.c) assert c == 2, "SPARQL COUNT must return 2" def test_sparql_insert(self): q = """ PREFIX : <https://example.org/> INSERT DATA { :x :y :z . }""" self.g.update(q) assert len(self.g) == 4, "After extra triple insert, length must be 4" def test_multigraph(self): q = """ PREFIX : <https://example.org/> INSERT DATA { GRAPH :m { :x :y :z . } GRAPH :n { :x :y :z . } }""" self.g.update(q) q = """ SELECT (COUNT(?g) AS ?c) WHERE { SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } } } """ c = 0 for row in self.g.query(q): c = int(row.c) assert c == 3, "SPARQL COUNT must return 3 (default, :m & :n)" def test_open_shut(self): assert len(self.g) == 3, "Initially we must have 3 triples from setUp" self.g.close() self.g = None # reopen the graph self.g = ConjunctiveGraph("BerkeleyDB") self.g.open(self.path, create=False) assert ( len(self.g) == 3 ), "After close and reopen, we should still have the 3 originally added triples"
class TestSparql11(unittest.TestCase): def setUp(self): self.longMessage = True self.graph = ConjunctiveGraph('SPARQLUpdateStore') root = HOST + DB self.graph.open((root + "sparql", root + "update")) # clean out the store for c in self.graph.contexts(): c.remove((None, None, None)) assert len(c) == 0 def tearDown(self): self.graph.close() def testSimpleGraph(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g.add((bob, likes, pizza)) g.add((bob, likes, cheese)) g2 = self.graph.get_context(othergraphuri) g2.add((michel, likes, pizza)) self.assertEquals(3, len(g), 'graph contains 3 triples') self.assertEquals(1, len(g2), 'other graph contains 1 triple') r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = g.triples((None, likes, pizza)) self.assertEquals(2, len(list(r)), "two people like pizza") # Test initBindings r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.add((tarek, likes, pizza)) g.remove((tarek, likes, pizza)) r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only bob likes pizza") def testConjunctiveDefault(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g2 = self.graph.get_context(othergraphuri) g2.add((bob, likes, pizza)) g.add((tarek, hates, cheese)) self.assertEquals(2, len(g), 'graph contains 2 triples') # the following are actually bad tests as they depend on your endpoint, # as pointed out in the sparqlstore.py code: # ## For ConjunctiveGraphs, reading is done from the "default graph" Exactly ## what this means depends on your endpoint, because SPARQL does not offer a ## simple way to query the union of all graphs as it would be expected for a ## ConjuntiveGraph. ## ## Fuseki/TDB has a flag for specifying that the default graph ## is the union of all graphs (tdb:unionDefaultGraph in the Fuseki config). self.assertEquals(3, len(self.graph), 'default union graph should contain three triples but contains:\n' '%s' % list(self.graph)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.remove((bob, likes, pizza)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only tarek likes pizza") def testUpdate(self): self.graph.update("INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }") g = self.graph.get_context(graphuri) self.assertEquals(1, len(g), 'graph contains 1 triples') def testUpdateWithInitNs(self): self.graph.update( "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }", initNs={'ns': URIRef('urn:')} ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) def testUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WherE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), } ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) def testMultipleUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WHERE { };" "INSERT { GRAPH <urn:graph> { ?d ?b ?c . } } WHERE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), 'd': URIRef('urn:bob'), } ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza), (bob,likes,pizza)]), 'michel and bob like pizza' ) def testNamedGraphUpdate(self): g = self.graph.get_context(graphuri) r1 = "INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }" g.update(r1) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) r2 = "DELETE { <urn:michel> <urn:likes> <urn:pizza> } " + \ "INSERT { <urn:bob> <urn:likes> <urn:pizza> } WHERE {}" g.update(r2) self.assertEquals( set(g.triples((None, None, None))), set([(bob, likes, pizza)]), 'only bob likes pizza' ) says = URIRef("urn:says") # Strings with unbalanced curly braces tricky_strs = ["With an unbalanced curly brace %s " % brace for brace in ["{", "}"]] for tricky_str in tricky_strs: r3 = """INSERT { ?b <urn:says> "%s" } WHERE { ?b <urn:likes> <urn:pizza>} """ % tricky_str g.update(r3) values = set() for v in g.objects(bob, says): values.add(str(v)) self.assertEquals(values, set(tricky_strs)) # Complicated Strings r4strings = [] r4strings.append(ur'''"1: adfk { ' \\\" \" { "''') r4strings.append(ur'''"2: adfk } <foo> #éï \\"''') r4strings.append(ur"""'3: adfk { " \\\' \' { '""") r4strings.append(ur"""'4: adfk } <foo> #éï \\'""") r4strings.append(ur'''"""5: adfk { ' \\\" \" { """''') r4strings.append(ur'''"""6: adfk } <foo> #éï \\"""''') r4strings.append(u'"""7: ad adsfj \n { \n sadfj"""') r4strings.append(ur"""'''8: adfk { " \\\' \' { '''""") r4strings.append(ur"""'''9: adfk } <foo> #éï \\'''""") r4strings.append(u"'''10: ad adsfj \n { \n sadfj'''") r4 = "\n".join([ u'INSERT DATA { <urn:michel> <urn:says> %s } ;' % s for s in r4strings ]) g.update(r4) values = set() for v in g.objects(michel, says): values.add(unicode(v)) self.assertEquals(values, set([re.sub(ur"\\(.)", ur"\1", re.sub(ur"^'''|'''$|^'|'$|" + ur'^"""|"""$|^"|"$', ur"", s)) for s in r4strings]))
rdf.add((body, RDF.predicate, SCHEMA.comment)) rdf.add((body, RDFS.label, Literal(form.getvalue('user_ann')))) rdf.add((body, RDF.subject, URIRef(subject))) rdf.add((body, RDF.object, Literal(form.getvalue('user_ann'), datatype=XSD.string))) rdf.add((target, RDF.type, OA.SpecificResource)) rdf.add((target, OA.hasSelector, selector)) rdf.add((target, OA.hasSource, URIRef(linkver))) rdf.add((selector, RDF.type, OA.FragmentSelector)) rdf.add((selector, RDF.value, Literal(value))) rdf.add((selector, OA.end, Literal(end, datatype=XSD.nonNegativeInteger))) rdf.add((selector, OA.start, Literal(start, datatype=XSD.nonNegativeInteger))) rdf.add((URIRef(nick), RDF.type, FOAF.Person)) rdf.add((URIRef(nick), SCHEMA.email, Literal(form.getvalue('user_mail')))) rdf.add((URIRef(nick), FOAF.name, Literal(user))) giovannaurl = "http://giovanna.cs.unibo.it:8181/data" giov = ConjunctiveGraph('SPARQLUpdateStore') giov.open((giovannaurl + "/query", giovannaurl + "/update")) update = "INSERT DATA { %s }" % rdf.serialize(format="nt") giov.update(update) ris['risposta'].append(rdf.serialize(format="turtle")) ris['risposta'].append("Annotazioni inserite correttamente") print 'Content-Type: application/json\n\n' print json.dumps(ris)
class MemoryStore: """A class that combines and syncronieses n-quad files and an in-memory quad store. This class contains information about all graphs, their corresponding URIs and pathes in the file system. For every Graph (context of Quad-Store) exists a FileReference object (n-quad) that enables versioning (with git) and persistence. """ def __init__(self): """Initialize a new MemoryStore instance.""" logger = logging.getLogger('quit.core.MemoryStore') logger.debug('Create an instance of MemoryStore') self.store = ConjunctiveGraph(identifier='default') return def getgraphuris(self): """Method to get all available named graphs. Returns: A list containing all graph uris found in store. """ graphs = [] for graph in self.store.contexts(): if isinstance(graph, BNode) or str(graph.identifier) == 'default': pass else: graphs.append(graph.identifier) return graphs def getgraphcontent(self, graphuri): """Get the serialized content of a named graph. Args: graphuri: The URI of a named graph. Returns: content: A list of strings where each string is a quad. """ data = [] context = self.store.get_context(URIRef(graphuri)) triplestring = context.serialize(format='nt').decode('UTF-8') # Since we have triples here, we transform them to quads by adding the graphuri # TODO This might cause problems if ' .\n' will be part of a literal. # Maybe a regex would be a better solution triplestring = triplestring.replace(' .\n', ' <' + graphuri + '> .\n') data = triplestring.splitlines() data.remove('') return data def getstoreobject(self): """Get the conjunctive graph object. Returns: graph: A list of strings where each string is a quad. """ def graphexists(self, graphuri): """Ask if a named graph FileReference object for a named graph URI. Args: graphuri: A string containing the URI of a named graph Returns: True or False """ if self.store.get_context(URIRef(graphuri)) is None: return False else: return True def addfile(self, filename, serialization): """Add a file to the store. Args: filename: A String for the path to the file. serialization: A String containg the RDF format Raises: ValueError if the given file can't be parsed as nquads. """ try: self.store.parse(source=filename, format=serialization) except Exception as e: logger.debug(e) logger.debug("Could not import file: {}. " + "Make sure the file exists and contains data in {}". format(filename, serialization)) def addquads(self, quads): """Add quads to the MemoryStore. Args: quads: Rdflib.quads that should be added to the MemoryStore. """ self.store.addN(quads) self.store.commit() def query(self, querystring): """Execute a SPARQL select query. Args: querystring: A string containing a SPARQL ask or select query. Returns: The SPARQL result set """ return self.store.query(querystring) def update(self, querystring, versioning=True): """Execute a SPARQL update query and update the store. This method executes a SPARQL update query and updates and commits all affected files. Args: querystring: A string containing a SPARQL upate query. """ # methods of rdflib ConjunciveGraph if versioning: actions = evalUpdate(self.store, querystring) self.store.update(querystring) return actions else: self.store.update(querystring) return return def removequads(self, quads): """Remove quads from the MemoryStore. Args: quads: Rdflib.quads that should be removed to the MemoryStore. """ self.store.remove((quads)) self.store.commit() return def exit(self): """Execute actions on API shutdown.""" return
class TestSparql11(unittest.TestCase): def setUp(self): self.longMessage = True self.graph = ConjunctiveGraph('SPARQLUpdateStore') root = HOST + DB self.graph.open((root + "sparql", root + "update")) # clean out the store for c in self.graph.contexts(): c.remove((None, None, None)) assert len(c) == 0 def tearDown(self): self.graph.close() def testSimpleGraph(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g.add((bob, likes, pizza)) g.add((bob, likes, cheese)) g2 = self.graph.get_context(othergraphuri) g2.add((michel, likes, pizza)) self.assertEqual(3, len(g), 'graph contains 3 triples') self.assertEqual(1, len(g2), 'other graph contains 1 triple') r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEqual(2, len(list(r)), "two people like pizza") r = g.triples((None, likes, pizza)) self.assertEqual(2, len(list(r)), "two people like pizza") # Test initBindings r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEqual(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, pizza)) self.assertEqual(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, cheese)) self.assertEqual(0, len(list(r)), "tarek doesn't like cheese") g2.add((tarek, likes, pizza)) g.remove((tarek, likes, pizza)) r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEqual(1, len(list(r)), "only bob likes pizza") def testConjunctiveDefault(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g2 = self.graph.get_context(othergraphuri) g2.add((bob, likes, pizza)) g.add((tarek, hates, cheese)) self.assertEqual(2, len(g), 'graph contains 2 triples') # the following are actually bad tests as they depend on your endpoint, # as pointed out in the sparqlstore.py code: # ## For ConjunctiveGraphs, reading is done from the "default graph" Exactly ## what this means depends on your endpoint, because SPARQL does not offer a ## simple way to query the union of all graphs as it would be expected for a ## ConjuntiveGraph. ## ## Fuseki/TDB has a flag for specifying that the default graph ## is the union of all graphs (tdb:unionDefaultGraph in the Fuseki config). self.assertEqual(3, len(self.graph), 'default union graph should contain three triples but contains:\n' '%s' % list(self.graph)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEqual(2, len(list(r)), "two people like pizza") r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEqual(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, pizza)) self.assertEqual(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, cheese)) self.assertEqual(0, len(list(r)), "tarek doesn't like cheese") g2.remove((bob, likes, pizza)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEqual(1, len(list(r)), "only tarek likes pizza") def testUpdate(self): self.graph.update("INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }") g = self.graph.get_context(graphuri) self.assertEqual(1, len(g), 'graph contains 1 triples') def testUpdateWithInitNs(self): self.graph.update( "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }", initNs={'ns': URIRef('urn:')} ) g = self.graph.get_context(graphuri) self.assertEqual( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) def testUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WherE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), } ) g = self.graph.get_context(graphuri) self.assertEqual( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) def testMultipleUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WHERE { };" "INSERT { GRAPH <urn:graph> { ?d ?b ?c . } } WHERE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), 'd': URIRef('urn:bob'), } ) g = self.graph.get_context(graphuri) self.assertEqual( set(g.triples((None,None,None))), set([(michel,likes,pizza), (bob,likes,pizza)]), 'michel and bob like pizza' ) def testNamedGraphUpdate(self): g = self.graph.get_context(graphuri) r1 = "INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }" g.update(r1) self.assertEqual( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) r2 = "DELETE { <urn:michel> <urn:likes> <urn:pizza> } " + \ "INSERT { <urn:bob> <urn:likes> <urn:pizza> } WHERE {}" g.update(r2) self.assertEqual( set(g.triples((None, None, None))), set([(bob, likes, pizza)]), 'only bob likes pizza' ) says = URIRef("urn:says") # Strings with unbalanced curly braces tricky_strs = ["With an unbalanced curly brace %s " % brace for brace in ["{", "}"]] for tricky_str in tricky_strs: r3 = """INSERT { ?b <urn:says> "%s" } WHERE { ?b <urn:likes> <urn:pizza>} """ % tricky_str g.update(r3) values = set() for v in g.objects(bob, says): values.add(str(v)) self.assertEqual(values, set(tricky_strs)) # Complicated Strings r4strings = [] r4strings.append(r'''"1: adfk { ' \\\" \" { "''') r4strings.append(r'''"2: adfk } <foo> #éï \\"''') r4strings.append(r"""'3: adfk { " \\\' \' { '""") r4strings.append(r"""'4: adfk } <foo> #éï \\'""") r4strings.append(r'''"""5: adfk { ' \\\" \" { """''') r4strings.append(r'''"""6: adfk } <foo> #éï \\"""''') r4strings.append('"""7: ad adsfj \n { \n sadfj"""') r4strings.append(r"""'''8: adfk { " \\\' \' { '''""") r4strings.append(r"""'''9: adfk } <foo> #éï \\'''""") r4strings.append("'''10: ad adsfj \n { \n sadfj'''") r4 = "\n".join([ u'INSERT DATA { <urn:michel> <urn:says> %s } ;' % s for s in r4strings ]) g.update(r4) values = set() for v in g.objects(michel, says): values.add(text_type(v)) self.assertEqual(values, set([re.sub(r"\\(.)", r"\1", re.sub(r"^'''|'''$|^'|'$|" + r'^"""|"""$|^"|"$', r"", s)) for s in r4strings])) # IRI Containing ' or # # The fragment identifier must not be misinterpreted as a comment # (commenting out the end of the block). # The ' must not be interpreted as the start of a string, causing the } # in the literal to be identified as the end of the block. r5 = """INSERT DATA { <urn:michel> <urn:hates> <urn:foo'bar?baz;a=1&b=2#fragment>, "'}" }""" g.update(r5) values = set() for v in g.objects(michel, hates): values.add(text_type(v)) self.assertEqual(values, set([u"urn:foo'bar?baz;a=1&b=2#fragment", u"'}"])) # Comments r6 = u""" INSERT DATA { <urn:bob> <urn:hates> <urn:bob> . # No closing brace: } <urn:bob> <urn:hates> <urn:michel>. } #Final { } comment""" g.update(r6) values = set() for v in g.objects(bob, hates): values.add(v) self.assertEqual(values, set([bob, michel])) def testNamedGraphUpdateWithInitBindings(self): g = self.graph.get_context(graphuri) r = "INSERT { ?a ?b ?c } WHERE {}" g.update(r, initBindings={ 'a': michel, 'b': likes, 'c': pizza }) self.assertEqual( set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza' ) def testEmptyNamedGraph(self): empty_graph_iri = "urn:empty-graph-1" self.graph.update("CREATE GRAPH <%s>" % empty_graph_iri) named_graphs = [text_type(r[0]) for r in self.graph.query( "SELECT ?name WHERE { GRAPH ?name {} }")] # Some SPARQL endpoint backends (like TDB) are not able to find empty named graphs # (at least with this query) if empty_graph_iri in named_graphs: self.assertTrue(empty_graph_iri in [text_type(g.identifier) for g in self.graph.contexts()]) def testEmptyLiteral(self): # test for https://github.com/RDFLib/rdflib/issues/457 # also see test_issue457.py which is sparql store independent! g = self.graph.get_context(graphuri) g.add(( URIRef('http://example.com/s'), URIRef('http://example.com/p'), Literal(''))) o = tuple(g)[0][2] self.assertEqual(o, Literal(''), repr(o))
class TestSparql11(unittest.TestCase): def setUp(self): self.longMessage = True self.graph = ConjunctiveGraph('SPARQLUpdateStore') root = "http://localhost:3030/ukpp/" self.graph.open((root + "sparql", root + "update")) # clean out the store for c in self.graph.contexts(): c.remove((None, None, None)) assert len(c) == 0 def tearDown(self): self.graph.close() def testSimpleGraph(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g.add((bob, likes, pizza)) g.add((bob, likes, cheese)) g2 = self.graph.get_context(othergraphuri) g2.add((michel, likes, pizza)) self.assertEquals(3, len(g), 'graph contains 3 triples') self.assertEquals(1, len(g2), 'other graph contains 1 triple') r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = g.triples((None, likes, pizza)) self.assertEquals(2, len(list(r)), "two people like pizza") # Test initBindings r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.add((tarek, likes, pizza)) g.remove((tarek, likes, pizza)) r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only bob likes pizza") def testConjunctiveDefault(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g2 = self.graph.get_context(othergraphuri) g2.add((bob, likes, pizza)) g.add((tarek, hates, cheese)) self.assertEquals(2, len(g), 'graph contains 2 triples') self.assertEquals(3, len(self.graph), 'default union graph contains three triples') r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.remove((bob, likes, pizza)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only tarek likes pizza") def testUpdate(self): self.graph.update( "INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }" ) g = self.graph.get_context(graphuri) self.assertEquals(1, len(g), 'graph contains 1 triples') def testUpdateWithInitNs(self): self.graph.update( "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }", initNs={'ns': URIRef('urn:')}) g = self.graph.get_context(graphuri) self.assertEquals(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') def testUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WherE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), }) g = self.graph.get_context(graphuri) self.assertEquals(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') def testMultipleUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WHERE { };" "INSERT { GRAPH <urn:graph> { ?d ?b ?c . } } WHERE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), 'd': URIRef('urn:bob'), }) g = self.graph.get_context(graphuri) self.assertEquals(set(g.triples((None, None, None))), set([(michel, likes, pizza), (bob, likes, pizza)]), 'michel and bob like pizza') def testNamedGraphUpdate(self): g = self.graph.get_context(graphuri) r1 = "INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }" g.update(r1) self.assertEquals(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') r2 = "DELETE { <urn:michel> <urn:likes> <urn:pizza> } " + \ "INSERT { <urn:bob> <urn:likes> <urn:pizza> } WHERE {}" g.update(r2) self.assertEquals(set(g.triples((None, None, None))), set([(bob, likes, pizza)]), 'only bob likes pizza') says = URIRef("urn:says") # Strings with unbalanced curly braces tricky_strs = [ "With an unbalanced curly brace %s " % brace for brace in ["{", "}"] ] for tricky_str in tricky_strs: r3 = """INSERT { ?b <urn:says> "%s" } WHERE { ?b <urn:likes> <urn:pizza>} """ % tricky_str g.update(r3) values = set() for v in g.objects(bob, says): values.add(str(v)) self.assertEquals(values, set(tricky_strs)) # Complicated Strings r4strings = [] r4strings.append(ur'''"1: adfk { ' \\\" \" { "''') r4strings.append(ur'''"2: adfk } <foo> #éï \\"''') r4strings.append(ur"""'3: adfk { " \\\' \' { '""") r4strings.append(ur"""'4: adfk } <foo> #éï \\'""") r4strings.append(ur'''"""5: adfk { ' \\\" \" { """''') r4strings.append(ur'''"""6: adfk } <foo> #éï \\"""''') r4strings.append(u'"""7: ad adsfj \n { \n sadfj"""') r4strings.append(ur"""'''8: adfk { " \\\' \' { '''""") r4strings.append(ur"""'''9: adfk } <foo> #éï \\'''""") r4strings.append(u"'''10: ad adsfj \n { \n sadfj'''") r4 = "\n".join([ u'INSERT DATA { <urn:michel> <urn:says> %s } ;' % s for s in r4strings ]) g.update(r4) values = set() for v in g.objects(michel, says): values.add(unicode(v)) self.assertEquals( values, set([ re.sub( ur"\\(.)", ur"\1", re.sub(ur"^'''|'''$|^'|'$|" + ur'^"""|"""$|^"|"$', ur"", s)) for s in r4strings ]))
class TestSparql11(unittest.TestCase): def setUp(self): self.longMessage = True self.graph = ConjunctiveGraph('SPARQLUpdateStore') root = HOST + DB self.graph.open((root + "sparql", root + "update")) # clean out the store for c in self.graph.contexts(): c.remove((None, None, None)) assert len(c) == 0 def tearDown(self): self.graph.close() def testSimpleGraph(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g.add((bob, likes, pizza)) g.add((bob, likes, cheese)) g2 = self.graph.get_context(othergraphuri) g2.add((michel, likes, pizza)) self.assertEquals(3, len(g), 'graph contains 3 triples') self.assertEquals(1, len(g2), 'other graph contains 1 triple') r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = g.triples((None, likes, pizza)) self.assertEquals(2, len(list(r)), "two people like pizza") # Test initBindings r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.add((tarek, likes, pizza)) g.remove((tarek, likes, pizza)) r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only bob likes pizza") def testConjunctiveDefault(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g2 = self.graph.get_context(othergraphuri) g2.add((bob, likes, pizza)) g.add((tarek, hates, cheese)) self.assertEquals(2, len(g), 'graph contains 2 triples') # the following are actually bad tests as they depend on your endpoint, # as pointed out in the sparqlstore.py code: # ## For ConjunctiveGraphs, reading is done from the "default graph" Exactly ## what this means depends on your endpoint, because SPARQL does not offer a ## simple way to query the union of all graphs as it would be expected for a ## ConjuntiveGraph. ## ## Fuseki/TDB has a flag for specifying that the default graph ## is the union of all graphs (tdb:unionDefaultGraph in the Fuseki config). self.assertEquals( 3, len(self.graph), 'default union graph should contain three triples but contains:\n' '%s' % list(self.graph)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.remove((bob, likes, pizza)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only tarek likes pizza") def testUpdate(self): self.graph.update( "INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }" ) g = self.graph.get_context(graphuri) self.assertEquals(1, len(g), 'graph contains 1 triples') def testUpdateWithInitNs(self): self.graph.update( "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }", initNs={'ns': URIRef('urn:')}) g = self.graph.get_context(graphuri) self.assertEquals(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') def testUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WherE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), }) g = self.graph.get_context(graphuri) self.assertEquals(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') def testMultipleUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WHERE { };" "INSERT { GRAPH <urn:graph> { ?d ?b ?c . } } WHERE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), 'd': URIRef('urn:bob'), }) g = self.graph.get_context(graphuri) self.assertEquals(set(g.triples((None, None, None))), set([(michel, likes, pizza), (bob, likes, pizza)]), 'michel and bob like pizza') def testNamedGraphUpdate(self): g = self.graph.get_context(graphuri) r1 = "INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }" g.update(r1) self.assertEquals(set(g.triples((None, None, None))), set([(michel, likes, pizza)]), 'only michel likes pizza') r2 = "DELETE { <urn:michel> <urn:likes> <urn:pizza> } " + \ "INSERT { <urn:bob> <urn:likes> <urn:pizza> } WHERE {}" g.update(r2) self.assertEquals(set(g.triples((None, None, None))), set([(bob, likes, pizza)]), 'only bob likes pizza') says = URIRef("urn:says") # Strings with unbalanced curly braces tricky_strs = [ "With an unbalanced curly brace %s " % brace for brace in ["{", "}"] ] for tricky_str in tricky_strs: r3 = """INSERT { ?b <urn:says> "%s" } WHERE { ?b <urn:likes> <urn:pizza>} """ % tricky_str g.update(r3) values = set() for v in g.objects(bob, says): values.add(str(v)) self.assertEquals(values, set(tricky_strs)) # Complicated Strings r4strings = [] r4strings.append(ur'''"1: adfk { ' \\\" \" { "''') r4strings.append(ur'''"2: adfk } <foo> #éï \\"''') r4strings.append(ur"""'3: adfk { " \\\' \' { '""") r4strings.append(ur"""'4: adfk } <foo> #éï \\'""") r4strings.append(ur'''"""5: adfk { ' \\\" \" { """''') r4strings.append(ur'''"""6: adfk } <foo> #éï \\"""''') r4strings.append(u'"""7: ad adsfj \n { \n sadfj"""') r4strings.append(ur"""'''8: adfk { " \\\' \' { '''""") r4strings.append(ur"""'''9: adfk } <foo> #éï \\'''""") r4strings.append(u"'''10: ad adsfj \n { \n sadfj'''") r4 = "\n".join([ u'INSERT DATA { <urn:michel> <urn:says> %s } ;' % s for s in r4strings ]) g.update(r4) values = set() for v in g.objects(michel, says): values.add(unicode(v)) self.assertEquals( values, set([ re.sub( ur"\\(.)", ur"\1", re.sub(ur"^'''|'''$|^'|'$|" + ur'^"""|"""$|^"|"$', ur"", s)) for s in r4strings ]))
class TestSparql11(unittest.TestCase): def setUp(self): self.longMessage = True self.graph = ConjunctiveGraph('SPARQLUpdateStore') root = "http://localhost:3030/ukpp/" self.graph.open((root + "sparql", root + "update")) # clean out the store for c in self.graph.contexts(): c.remove((None, None, None)) assert len(c) == 0 def tearDown(self): self.graph.close() def testSimpleGraph(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g.add((bob, likes, pizza)) g.add((bob, likes, cheese)) g2 = self.graph.get_context(othergraphuri) g2.add((michel, likes, pizza)) self.assertEquals(3, len(g), 'graph contains 3 triples') self.assertEquals(1, len(g2), 'other graph contains 1 triple') r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = g.triples((None, likes, pizza)) self.assertEquals(2, len(list(r)), "two people like pizza") # Test initBindings r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = g.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.add((tarek, likes, pizza)) g.remove((tarek, likes, pizza)) r = g.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only bob likes pizza") def testConjunctiveDefault(self): g = self.graph.get_context(graphuri) g.add((tarek, likes, pizza)) g2 = self.graph.get_context(othergraphuri) g2.add((bob, likes, pizza)) g.add((tarek, hates, cheese)) self.assertEquals(2, len(g), 'graph contains 2 triples') self.assertEquals(3, len(self.graph), 'default union graph contains three triples') r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(2, len(list(r)), "two people like pizza") r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }", initBindings={'s': tarek}) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, pizza)) self.assertEquals(1, len(list(r)), "i was asking only about tarek") r = self.graph.triples((tarek, likes, cheese)) self.assertEquals(0, len(list(r)), "tarek doesn't like cheese") g2.remove((bob, likes, pizza)) r = self.graph.query("SELECT * WHERE { ?s <urn:likes> <urn:pizza> . }") self.assertEquals(1, len(list(r)), "only tarek likes pizza") def testUpdate(self): self.graph.update("INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> . } }") g = self.graph.get_context(graphuri) self.assertEquals(1, len(g), 'graph contains 1 triples') def testUpdateWithInitNs(self): self.graph.update( "INSERT DATA { GRAPH ns:graph { ns:michel ns:likes ns:pizza . } }", initNs={'ns': URIRef('urn:')} ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) def testUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WherE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), } ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza)]), 'only michel likes pizza' ) def testMultipleUpdateWithInitBindings(self): self.graph.update( "INSERT { GRAPH <urn:graph> { ?a ?b ?c . } } WHERE { };" "INSERT { GRAPH <urn:graph> { ?d ?b ?c . } } WHERE { }", initBindings={ 'a': URIRef('urn:michel'), 'b': URIRef('urn:likes'), 'c': URIRef('urn:pizza'), 'd': URIRef('urn:bob'), } ) g = self.graph.get_context(graphuri) self.assertEquals( set(g.triples((None,None,None))), set([(michel,likes,pizza), (bob,likes,pizza)]), 'michel and bob like pizza' )