diff options
author | Gunnar Aastrand Grimnes <gromgull@gmail.com> | 2018-10-30 14:21:41 +0100 |
---|---|---|
committer | Gunnar Aastrand Grimnes <gromgull@gmail.com> | 2018-10-30 15:38:42 +0100 |
commit | 785e37932e71a02ab8c31257694060f550ff72a6 (patch) | |
tree | 43bc2158ce60168cebe15a0f88ea2aeddb30520d | |
parent | fac8b840627013e1b9bbe76bd75c8e9d5d7b4cdf (diff) | |
download | rdflib-785e37932e71a02ab8c31257694060f550ff72a6.tar.gz |
a slightly opinionated autopep8 run
opinions is mainly: no to long lines, but not at any cost.
notation3.py crashses autopep :D
Also rdflib/__init__.py gets completely broken
163 files changed, 1366 insertions, 1139 deletions
@@ -1,4 +1,4 @@ [pep8] ignore = W806 max-line-length = 85 -exclude = pyRdfa,host,extras,transform,rdfs,pyMicrodata +exclude = host,extras,transform,rdfs diff --git a/examples/conjunctive_graphs.py b/examples/conjunctive_graphs.py index a5e5a71f..81cbab9e 100644 --- a/examples/conjunctive_graphs.py +++ b/examples/conjunctive_graphs.py @@ -14,21 +14,20 @@ from rdflib import Namespace, Literal, URIRef from rdflib.graph import Graph, ConjunctiveGraph from rdflib.plugins.memory import IOMemory -if __name__=='__main__': - +if __name__ == '__main__': ns = Namespace("http://love.com#") mary = URIRef("http://love.com/lovers/mary#") john = URIRef("http://love.com/lovers/john#") - cmary=URIRef("http://love.com/lovers/mary#") - cjohn=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) + g.bind("love", ns) gmary = Graph(store=store, identifier=cmary) @@ -38,21 +37,21 @@ if __name__=='__main__': gjohn = Graph(store=store, identifier=cjohn) gjohn.add((john, ns['hasName'], Literal("John"))) - #enumerate contexts + # enumerate contexts for c in g.contexts(): print("-- %s " % c) - #separate graphs + # separate graphs print(gjohn.serialize(format='n3')) print("===================") print(gmary.serialize(format='n3')) print("===================") - #full graph + # full graph print(g.serialize(format='n3')) # query the conjunction of all graphs print('Mary loves:') - for x in g[mary : ns.loves/ns.hasName]: + for x in g[mary: ns.loves / ns.hasName]: print(x) diff --git a/examples/custom_datatype.py b/examples/custom_datatype.py index 34bde44c..f2d4fb28 100644 --- a/examples/custom_datatype.py +++ b/examples/custom_datatype.py @@ -14,31 +14,31 @@ mappings between literal datatypes and python objects from rdflib import Graph, Literal, Namespace, XSD from rdflib.term import bind -if __name__=='__main__': +if __name__ == '__main__': # complex numbers are not registered by default # no custom constructor/serializer needed since # complex('(2+3j)') works fine bind(XSD.complexNumber, complex) - ns=Namespace("urn:my:namespace:") + ns = Namespace("urn:my:namespace:") - c=complex(2,3) + c = complex(2, 3) - l=Literal(c) + l = Literal(c) - g=Graph() + g = Graph() g.add((ns.mysubject, ns.myprop, l)) - n3=g.serialize(format='n3') + n3 = g.serialize(format='n3') # round-trip through n3 - g2=Graph() + g2 = Graph() g2.parse(data=n3, format='n3') - l2=list(g2)[0][2] + l2 = list(g2)[0][2] print(l2) - print(l2.value == c) # back to a python complex object + print(l2.value == c) # back to a python complex object diff --git a/examples/custom_eval.py b/examples/custom_eval.py index bad8ff1c..69cd173a 100644 --- a/examples/custom_eval.py +++ b/examples/custom_eval.py @@ -49,7 +49,8 @@ def customEval(ctx, part): raise NotImplementedError() -if __name__=='__main__': + +if __name__ == '__main__': # add function directly, normally we would use setuptools and entry_points rdflib.plugins.sparql.CUSTOM_EVALS['exampleEval'] = customEval diff --git a/examples/film.py b/examples/film.py index 0672840a..6bbda04a 100644 --- a/examples/film.py +++ b/examples/film.py @@ -23,7 +23,11 @@ Usage: film.py http://www.imdb.com/title/tt0105236/ Review the movie "Reservoir Dogs" """ -import datetime, os, sys, re, time +import datetime +import os +import sys +import re +import time try: import imdb @@ -36,7 +40,7 @@ from six.moves import input storefn = os.path.expanduser('~/movies.n3') #storefn = '/home/simon/codes/film.dev/movies.n3' -storeuri = 'file://'+storefn +storeuri = 'file://' + storefn title = 'Movies viewed by %s' r_who = re.compile('^(.*?) <([a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+)>$') @@ -44,6 +48,7 @@ r_who = re.compile('^(.*?) <([a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_- IMDB = Namespace('http://www.csd.abdn.ac.uk/~ggrimnes/dev/imdb/IMDB#') REV = Namespace('http://purl.org/stuff/rev#') + class Store: def __init__(self): self.graph = ConjunctiveGraph() @@ -61,12 +66,14 @@ class Store: if who is not None: name, email = (r_who.match(who).group(1), r_who.match(who).group(2)) self.graph.add((URIRef(storeuri), DC['title'], Literal(title % name))) - self.graph.add((URIRef(storeuri+'#author'), RDF.type, FOAF['Person'])) - self.graph.add((URIRef(storeuri+'#author'), FOAF['name'], Literal(name))) - self.graph.add((URIRef(storeuri+'#author'), FOAF['mbox'], Literal(email))) + self.graph.add((URIRef(storeuri + '#author'), RDF.type, FOAF['Person'])) + self.graph.add((URIRef(storeuri + '#author'), + FOAF['name'], Literal(name))) + self.graph.add((URIRef(storeuri + '#author'), + FOAF['mbox'], Literal(email))) self.save() else: - return self.graph.objects(URIRef(storeuri+'#author'), FOAF['name']) + return self.graph.objects(URIRef(storeuri + '#author'), FOAF['name']) def new_movie(self, movie): movieuri = URIRef('http://www.imdb.com/title/tt%s/' % movie.movieID) @@ -76,14 +83,14 @@ class Store: self.save() def new_review(self, movie, date, rating, comment=None): - review = BNode() # @@ humanize the identifier (something like #rev-$date) + review = BNode() # @@ humanize the identifier (something like #rev-$date) movieuri = URIRef('http://www.imdb.com/title/tt%s/' % movie.movieID) self.graph.add((movieuri, REV['hasReview'], URIRef('%s#%s' % (storeuri, review)))) self.graph.add((review, RDF.type, REV['Review'])) self.graph.add((review, DC['date'], Literal(date))) self.graph.add((review, REV['maxRating'], Literal(5))) self.graph.add((review, REV['minRating'], Literal(0))) - self.graph.add((review, REV['reviewer'], URIRef(storeuri+'#author'))) + self.graph.add((review, REV['reviewer'], URIRef(storeuri + '#author'))) self.graph.add((review, REV['rating'], Literal(rating))) if comment is not None: self.graph.add((review, REV['text'], Literal(comment))) @@ -92,9 +99,11 @@ class Store: def movie_is_in(self, uri): return (URIRef(uri), RDF.type, IMDB['Movie']) in self.graph + def help(): print(__doc__.split('--')[1]) + def main(argv=None): if not argv: argv = sys.argv @@ -136,6 +145,7 @@ def main(argv=None): else: help() + if __name__ == '__main__': if not imdb: raise Exception('This example requires the IMDB library! Install with "pip install imdbpy"') diff --git a/examples/foafpaths.py b/examples/foafpaths.py index 9209500b..4650d228 100644 --- a/examples/foafpaths.py +++ b/examples/foafpaths.py @@ -31,7 +31,7 @@ This example shows how to get the name of friends with a single query. from rdflib import URIRef, Graph from rdflib.namespace import FOAF -if __name__=='__main__': +if __name__ == '__main__': g = Graph() g.load("foaf.rdf") diff --git a/examples/graph_digest_benchmark.py b/examples/graph_digest_benchmark.py index 2e64e1bf..678425d1 100644 --- a/examples/graph_digest_benchmark.py +++ b/examples/graph_digest_benchmark.py @@ -12,7 +12,8 @@ from rdflib import Namespace, Graph from rdflib.compare import to_isomorphic from six.moves.urllib.request import urlopen from six.moves import queue -import sys, csv +import sys +import csv from io import StringIO from collections import defaultdict @@ -49,7 +50,7 @@ stat_cols = [ 'to_hash_runtime', 'canonicalize_triples_runtime', 'error', - ] +] def files_benchmark(ontologies, output_file, threads): @@ -160,6 +161,7 @@ def bioportal_benchmark(apikey, output_file, threads): w.flush() written_tasks += 1 + if __name__ == '__main__': if len(sys.argv) > 4: files_benchmark(sys.argv[1:-2], sys.argv[-2], sys.argv[-1]) diff --git a/examples/prepared_query.py b/examples/prepared_query.py index 2906783f..eb5f2b8c 100644 --- a/examples/prepared_query.py +++ b/examples/prepared_query.py @@ -14,11 +14,11 @@ import rdflib from rdflib.plugins.sparql import prepareQuery from rdflib.namespace import FOAF -if __name__=='__main__': +if __name__ == '__main__': q = prepareQuery( 'SELECT ?s WHERE { ?person foaf:knows ?s .}', - initNs = { "foaf": FOAF }) + initNs={"foaf": FOAF}) g = rdflib.Graph() g.load("foaf.rdf") diff --git a/examples/rdfa_example.py b/examples/rdfa_example.py index 000644ec..e49bebbc 100644 --- a/examples/rdfa_example.py +++ b/examples/rdfa_example.py @@ -19,4 +19,4 @@ if __name__ == '__main__': schema:name ?title ] FILTER (LANG(?title) = 'en') } """): - print("%s by %s"%(row.title, row.author)) + print("%s by %s" % (row.title, row.author)) diff --git a/examples/resource.py b/examples/resource.py index d254e751..d676ae5f 100644 --- a/examples/resource.py +++ b/examples/resource.py @@ -12,19 +12,18 @@ subject. from rdflib import Graph, RDF, RDFS, Literal from rdflib.namespace import FOAF -if __name__=='__main__': +if __name__ == '__main__': g = Graph() bob = g.resource('urn:bob') - bob.set(RDF.type, FOAF.Person) # .set replaces all other values + bob.set(RDF.type, FOAF.Person) # .set replaces all other values bob.set(FOAF.name, Literal("Bob")) - bill = g.resource('urn:bill') - bill.add(RDF.type, FOAF.Person) # add adds to existing values + bill.add(RDF.type, FOAF.Person) # add adds to existing values bill.add(RDF.type, FOAF.Agent) bill.set(RDFS.label, Literal("Bill")) @@ -42,8 +41,8 @@ if __name__=='__main__': # or even quicker with paths: print("Bill knows: ") - for friend in bill[FOAF.knows/FOAF.name]: + for friend in bill[FOAF.knows / FOAF.name]: print(friend) # setting single properties is also possible: - bill[RDFS.label]=Literal("William") + bill[RDFS.label] = Literal("William") diff --git a/examples/simple_example.py b/examples/simple_example.py index 5ed4be62..ef5ec73a 100644 --- a/examples/simple_example.py +++ b/examples/simple_example.py @@ -2,7 +2,7 @@ from rdflib import Graph, Literal, BNode, RDF from rdflib.namespace import FOAF, DC -if __name__=='__main__': +if __name__ == '__main__': store = Graph() diff --git a/examples/sleepycat_example.py b/examples/sleepycat_example.py index 417897fa..b112717e 100644 --- a/examples/sleepycat_example.py +++ b/examples/sleepycat_example.py @@ -47,7 +47,7 @@ if __name__ == '__main__': graph = ConjunctiveGraph('Sleepycat') - graph.open(path, create = False) + graph.open(path, create=False) print('Triples still in graph: ', len(graph)) @@ -56,5 +56,5 @@ if __name__ == '__main__': # Clean up the temp folder to remove the Sleepycat database files... import os for f in os.listdir(path): - os.unlink(path+'/'+f) + os.unlink(path + '/' + f) os.rmdir(path) diff --git a/examples/slice.py b/examples/slice.py index e3d21b40..525edb95 100644 --- a/examples/slice.py +++ b/examples/slice.py @@ -14,16 +14,16 @@ See :meth:`rdflib.graph.Graph.__getitem__` for details from rdflib import Graph, RDF from rdflib.namespace import FOAF -if __name__=='__main__': +if __name__ == '__main__': graph = Graph() graph.load("foaf.rdf") - for person in graph[: RDF.type : FOAF.Person]: + for person in graph[: RDF.type: FOAF.Person]: - friends = list(graph[person:FOAF.knows * '+'/FOAF.name]) + friends = list(graph[person:FOAF.knows * '+' / FOAF.name]) if friends: - print("%s's circle of friends:"%graph.value(person, FOAF.name)) + print("%s's circle of friends:" % graph.value(person, FOAF.name)) for name in friends: print(name) diff --git a/examples/smushing.py b/examples/smushing.py index fbd5dd25..3b174f83 100644 --- a/examples/smushing.py +++ b/examples/smushing.py @@ -27,21 +27,20 @@ from rdflib.namespace import FOAF STABLE = Namespace("http://example.com/person/mbox_sha1sum/") -if __name__=='__main__': +if __name__ == '__main__': g = Graph() g.parse("smushingdemo.n3", format="n3") - newURI = {} # old subject : stable uri - for s,p,o in g.triples((None, FOAF['mbox_sha1sum'], None)): + newURI = {} # old subject : stable uri + for s, p, o in g.triples((None, FOAF['mbox_sha1sum'], None)): newURI[s] = STABLE[o] - out = Graph() out.bind('foaf', FOAF) - for s,p,o in g: + for s, p, o in g: s = newURI.get(s, s) - o = newURI.get(o, o) # might be linked to another person - out.add((s,p,o)) + o = newURI.get(o, o) # might be linked to another person + out.add((s, p, o)) print(out.serialize(format="n3").decode('utf-8')) diff --git a/examples/sparql_query_example.py b/examples/sparql_query_example.py index 1698c706..b1ffff5f 100644 --- a/examples/sparql_query_example.py +++ b/examples/sparql_query_example.py @@ -16,7 +16,7 @@ For variable names that are not valid python identifiers, dict access import rdflib -if __name__=='__main__': +if __name__ == '__main__': g = rdflib.Graph() g.load("foaf.rdf") diff --git a/examples/sparql_update_example.py b/examples/sparql_update_example.py index 99156135..a604eebd 100644 --- a/examples/sparql_update_example.py +++ b/examples/sparql_update_example.py @@ -7,7 +7,7 @@ SPARQL Update statements can be applied with :meth:`rdflib.graph.Graph.update` import rdflib -if __name__=='__main__': +if __name__ == '__main__': g = rdflib.Graph() g.load("foaf.rdf") diff --git a/examples/sparqlstore_example.py b/examples/sparqlstore_example.py index 529ee233..afef011d 100644 --- a/examples/sparqlstore_example.py +++ b/examples/sparqlstore_example.py @@ -14,7 +14,6 @@ if __name__ == '__main__': graph.open("http://dbpedia.org/sparql") - pop = graph.value( URIRef("http://dbpedia.org/resource/Berlin"), dbo.populationTotal) diff --git a/examples/swap_primer.py b/examples/swap_primer.py index e44c34f2..dacb92e4 100644 --- a/examples/swap_primer.py +++ b/examples/swap_primer.py @@ -12,7 +12,7 @@ http://www.w3.org/2000/10/swap/Primer from rdflib import ConjunctiveGraph, Namespace, Literal from rdflib.namespace import OWL, DC -if __name__=='__main__': +if __name__ == '__main__': # Firstly, it doesn't have to be so complex. # Here we create a "Graph" of our work. @@ -25,7 +25,6 @@ if __name__=='__main__': # or: primer.add((myNS['pat'], myNS['age'], Literal(24))) - # Now, with just that, lets see how the system # recorded *way* too many details about what # you just asserted as fact. @@ -34,7 +33,6 @@ if __name__=='__main__': from pprint import pprint pprint(list(primer)) - # just think .whatever((s, p, o)) # here we report on what we know @@ -50,16 +48,12 @@ if __name__=='__main__': # who is what age? pprint(list(primer.subject_objects(myNS.age))) - - # Okay, so lets now work with a bigger # dataset from the example, and start # with a fresh new graph. - primer = ConjunctiveGraph() - # Lets start with a verbatim string straight from the primer text: mySource = """ @@ -101,7 +95,7 @@ if __name__=='__main__': - """ # --- End of primer code + """ # --- End of primer code # To make this go easier to spit back out... # technically, we already created a namespace @@ -119,7 +113,6 @@ if __name__=='__main__': primer.parse(data=mySource, format='n3') - # Now you can query, either directly straight into a list: [(x, y, z) for x, y, z in primer] diff --git a/examples/transitive.py b/examples/transitive.py index dad3a07b..5251ea79 100644 --- a/examples/transitive.py +++ b/examples/transitive.py @@ -45,7 +45,7 @@ transtive closures of user-defined functions. """ -if __name__=='__main__': +if __name__ == '__main__': from rdflib import ConjunctiveGraph, URIRef person = URIRef('ex:person') diff --git a/rdflib/collection.py b/rdflib/collection.py index 8338a24c..c99aa4c7 100644 --- a/rdflib/collection.py +++ b/rdflib/collection.py @@ -232,7 +232,6 @@ class Collection(object): self.graph.add((end, RDF.first, item)) - self.graph.add((end, RDF.rest, RDF.nil)) def clear(self): @@ -249,6 +248,7 @@ def test(): import doctest doctest.testmod() + if __name__ == "__main__": test() diff --git a/rdflib/compare.py b/rdflib/compare.py index 97de047b..d28b3336 100644 --- a/rdflib/compare.py +++ b/rdflib/compare.py @@ -195,9 +195,9 @@ class Color: self._hash_color = None def __str__(self): - nodes, color = self.key() + nodes, color = self.key() return "Color %s (%s nodes)" % (color, nodes) - + def key(self): return (len(self.nodes), self.hash_color()) @@ -264,11 +264,9 @@ class _TripleCanonicalizer(object): self._hash_cache = {} self.hashfunc = _hashfunc - def _discrete(self, coloring): return len([c for c in coloring if not c.discrete()]) == 0 - def _initial_color(self): """Finds an initial color for the graph. @@ -494,6 +492,7 @@ def to_isomorphic(graph): result += graph return result + def isomorphic(graph1, graph2): """Compare graph for equality. @@ -530,7 +529,6 @@ def isomorphic(graph1, graph2): return gd1 == gd2 - def to_canonical_graph(g1, stats=None): """Creates a canonical, read-only graph. @@ -553,7 +551,6 @@ def graph_diff(g1, g2): return (in_both, in_first, in_second) - _MOCK_BNODE = BNode() diff --git a/rdflib/compat.py b/rdflib/compat.py index c82f426f..2c5e4cf4 100644 --- a/rdflib/compat.py +++ b/rdflib/compat.py @@ -15,25 +15,26 @@ import six # clean ElementTree import try: - from lxml import etree + from lxml import etree except ImportError: - try: - # Python 2.5 - import xml.etree.cElementTree as etree - except ImportError: try: - # Python 2.5 - import xml.etree.ElementTree as etree + # Python 2.5 + import xml.etree.cElementTree as etree except ImportError: - try: - # normal cElementTree install - import cElementTree as etree - except ImportError: try: - # normal ElementTree install - import elementtree.ElementTree as etree + # Python 2.5 + import xml.etree.ElementTree as etree except ImportError: - raise Exception("Failed to import ElementTree from any known place") + try: + # normal cElementTree install + import cElementTree as etree + except ImportError: + try: + # normal ElementTree install + import elementtree.ElementTree as etree + except ImportError: + raise Exception( + "Failed to import ElementTree from any known place") try: etree_register_namespace = etree.register_namespace @@ -44,11 +45,13 @@ except AttributeError: def etree_register_namespace(prefix, uri): etreenative._namespace_map[uri] = prefix + def cast_bytes(s, enc='utf-8'): if isinstance(s, six.text_type): return s.encode(enc) return s + if six.PY3: # Python 3: # --------- @@ -57,7 +60,7 @@ if six.PY3: return codecs.getreader('ascii')(stream) def bopen(*args, **kwargs): - return open(*args, mode = 'rb', **kwargs) + return open(*args, mode='rb', **kwargs) long_type = int @@ -84,9 +87,11 @@ else: r_unicodeEscape = re.compile(r'(\\u[0-9A-Fa-f]{4}|\\U[0-9A-Fa-f]{8})') + def _unicodeExpand(s): return r_unicodeEscape.sub(lambda m: six.unichr(int(m.group(0)[2:], 16)), s) + narrow_build = False try: six.unichr(0x10FFFF) @@ -108,7 +113,6 @@ if narrow_build: def decodeStringEscape(s): - """ s is byte-string - replace \ escapes in string """ @@ -126,7 +130,8 @@ def decodeStringEscape(s): s = s.replace('\\\\', '\\') return s - #return _unicodeExpand(s) # hmm - string escape doesn't do unicode escaping + # return _unicodeExpand(s) # hmm - string escape doesn't do unicode escaping + def decodeUnicodeEscape(s): """ @@ -146,6 +151,6 @@ def decodeUnicodeEscape(s): s = s.replace("\\'", "'") s = s.replace('\\\\', '\\') - s = _unicodeExpand(s) # hmm - string escape doesn't do unicode escaping + s = _unicodeExpand(s) # hmm - string escape doesn't do unicode escaping return s diff --git a/rdflib/events.py b/rdflib/events.py index 3deebbb2..2c563c10 100644 --- a/rdflib/events.py +++ b/rdflib/events.py @@ -92,5 +92,6 @@ def test(): import doctest doctest.testmod() + if __name__ == '__main__': test() diff --git a/rdflib/exceptions.py b/rdflib/exceptions.py index bbfdb594..85195a53 100644 --- a/rdflib/exceptions.py +++ b/rdflib/exceptions.py @@ -9,6 +9,7 @@ __all__ = ['Error', 'TypeCheckError', 'SubjectTypeError', class Error(Exception): """Base class for rdflib exceptions.""" + def __init__(self, msg=None): Exception.__init__(self, msg) self.msg = msg @@ -25,6 +26,7 @@ class TypeCheckError(Error): class SubjectTypeError(TypeCheckError): """Subject of an assertion must be an instance of URIRef.""" + def __init__(self, node): TypeCheckError.__init__(self, node) self.msg = "Subject must be instance of URIRef or BNode: %s(%s)" \ @@ -33,6 +35,7 @@ class SubjectTypeError(TypeCheckError): class PredicateTypeError(TypeCheckError): """Predicate of an assertion must be an instance of URIRef.""" + def __init__(self, node): TypeCheckError.__init__(self, node) self.msg = "Predicate must be a URIRef instance: %s(%s)" \ @@ -42,6 +45,7 @@ class PredicateTypeError(TypeCheckError): class ObjectTypeError(TypeCheckError): """Object of an assertion must be an instance of URIRef, Literal, or BNode.""" + def __init__(self, node): TypeCheckError.__init__(self, node) self.msg = "\ @@ -51,6 +55,7 @@ Object must be instance of URIRef, Literal, or BNode: %s(%s)" % \ class ContextTypeError(TypeCheckError): """Context of an assertion must be an instance of URIRef.""" + def __init__(self, node): TypeCheckError.__init__(self, node) self.msg = "Context must be instance of URIRef or BNode: %s(%s)" \ @@ -59,6 +64,7 @@ class ContextTypeError(TypeCheckError): class ParserError(Error): """RDF Parser error.""" + def __init__(self, msg): Error.__init__(self, msg) self.msg = msg @@ -69,6 +75,7 @@ class ParserError(Error): class UniquenessError(Error): """A uniqueness assumption was made in the context, and that is not true""" + def __init__(self, values): Error.__init__(self, "\ Uniqueness assumption is not fulfilled. Multiple values are: %s" % values) diff --git a/rdflib/extras/describer.py b/rdflib/extras/describer.py index 105da668..68e85240 100644 --- a/rdflib/extras/describer.py +++ b/rdflib/extras/describer.py @@ -128,7 +128,6 @@ class Describer(object): self._subjects = [] self.about(about or None) - def about(self, subject, **kws): """ Sets the current subject. Will convert the given object into an @@ -151,7 +150,6 @@ class Describer(object): else: self._subjects.append(subject) - def value(self, p, v, **kws): """ Set a literal value for the given property. Will cast the value to an @@ -170,7 +168,6 @@ class Describer(object): v = cast_value(v, **kws) self.graph.add((self._current(), p, v)) - def rel(self, p, o=None, **kws): """Set an object for the given property. Will convert the given object into an ``URIRef`` if it's not an ``Identifier``. If none is given, a @@ -204,7 +201,6 @@ class Describer(object): self.graph.add((self._current(), p, o)) return self._subject_stack(o) - def rev(self, p, s=None, **kws): """ Same as ``rel``, but uses current subject as *object* of the relation. diff --git a/rdflib/extras/external_graph_libs.py b/rdflib/extras/external_graph_libs.py index 2bb62a18..8617b370 100644 --- a/rdflib/extras/external_graph_libs.py +++ b/rdflib/extras/external_graph_libs.py @@ -19,7 +19,9 @@ see ../../test/test_extras_external_graph_libs.py for conditional tests import logging logger = logging.getLogger(__name__) -_identity = lambda x: x + +def _identity(x): return x + def _rdflib_to_networkx_graph( graph, @@ -65,6 +67,7 @@ def _rdflib_to_networkx_graph( d = edge_attrs(s, p, o) data['triples'].extend(d['triples']) + def rdflib_to_networkx_multidigraph( graph, edge_attrs=lambda s, p, o: {'key': p}, @@ -117,6 +120,7 @@ def rdflib_to_networkx_multidigraph( _rdflib_to_networkx_graph(graph, mdg, False, edge_attrs, **kwds) return mdg + def rdflib_to_networkx_digraph( graph, calc_weights=True, @@ -238,13 +242,13 @@ def rdflib_to_networkx_graph( def rdflib_to_graphtool( - graph, - v_prop_names=[str('term')], - e_prop_names=[str('term')], - transform_s=lambda s, p, o: {str('term'): s}, - transform_p=lambda s, p, o: {str('term'): p}, - transform_o=lambda s, p, o: {str('term'): o}, - ): + graph, + v_prop_names=[str('term')], + e_prop_names=[str('term')], + transform_s=lambda s, p, o: {str('term'): s}, + transform_p=lambda s, p, o: {str('term'): p}, + transform_o=lambda s, p, o: {str('term'): o}, +): """Converts the given graph into a graph_tool.Graph(). The subjects and objects are the later vertices of the Graph. diff --git a/rdflib/extras/infixowl.py b/rdflib/extras/infixowl.py index 8f0a439d..f3ce40d3 100644 --- a/rdflib/extras/infixowl.py +++ b/rdflib/extras/infixowl.py @@ -214,6 +214,7 @@ class Infix: def __call__(self, value1, value2): return self.function(value1, value2) + OWL_NS = Namespace("http://www.w3.org/2002/07/owl#") nsBinds = { @@ -515,6 +516,7 @@ class AnnotatableTerms(Individual): """ Terms in an OWL ontology with rdfs:label and rdfs:comment """ + def __init__(self, identifier, graph=None, @@ -633,6 +635,7 @@ class AnnotatableTerms(Individual): class Ontology(AnnotatableTerms): """ The owl ontology metadata""" + def __init__(self, identifier=None, imports=None, comment=None, graph=None): super(Ontology, self).__init__(identifier, graph) @@ -707,6 +710,7 @@ class ClassNamespaceFactory(Namespace): else: return self.term(name) + CLASS_RELATIONS = set( OWL_NS.resourceProperties ).difference([OWL_NS.onProperty, @@ -877,8 +881,8 @@ def CastClass(c, graph=None): else: for s, p, o in graph.triples_choices((classOrIdentifier(c), [OWL_NS.intersectionOf, - OWL_NS.unionOf, - OWL_NS.oneOf], + OWL_NS.unionOf, + OWL_NS.oneOf], None)): if p == OWL_NS.oneOf: return EnumeratedClass(classOrIdentifier(c), graph=graph) @@ -919,6 +923,7 @@ class Class(AnnotatableTerms): description." """ + def _serialize(self, graph): for cl in self.subClassOf: CastClass(cl, self.graph).serialize(graph) @@ -1102,7 +1107,7 @@ class Class(AnnotatableTerms): return for sc in other: self.graph.add((self.identifier, - OWL_NS.equivalentClass, classOrIdentifier(sc))) + OWL_NS.equivalentClass, classOrIdentifier(sc))) @TermDeletionHelper(OWL_NS.equivalentClass) def _del_equivalentClass(self): @@ -1259,8 +1264,8 @@ class Class(AnnotatableTerms): else: scJoin = ', ' necStatements = [ - isinstance(s, Class) and isinstance(self.identifier, BNode) and - repr(CastClass(s, self.graph)) or + isinstance(s, Class) and isinstance(self.identifier, BNode) + and repr(CastClass(s, self.graph)) or # repr(BooleanClass(classOrIdentifier(s), # operator=None, # graph=self.graph)) or @@ -1273,8 +1278,8 @@ class Class(AnnotatableTerms): exprs[-1] = "\n " + exprs[-1] if ec: nec_SuffStatements = [ - isinstance(s, str) and s or - manchesterSyntax(classOrIdentifier(s), self.graph) for s in ec] + isinstance(s, str) and s + or manchesterSyntax(classOrIdentifier(s), self.graph) for s in ec] if nec_SuffStatements: klassKind = "A Defined Class %s" % label exprs.append("EquivalentTo: %s" % ', '.join(nec_SuffStatements)) @@ -1294,9 +1299,9 @@ class Class(AnnotatableTerms): else: klassDescr = full and (descr and "\n %s" % descr[0] or '') or '' + ' . '.join(exprs) - return (isinstance(self.identifier, BNode) - and "Some Class " - or "Class: %s " % self.qname) + klassDescr + return (isinstance(self.identifier, BNode) and + "Some Class " or + "Class: %s " % self.qname) + klassDescr class OWLRDFListProxy(object): @@ -1438,6 +1443,7 @@ class EnumeratedClass(OWLRDFListProxy, Class): graph.add((s, p, o)) self._serialize(graph) + BooleanPredicates = [OWL_NS.intersectionOf, OWL_NS.unionOf] @@ -1461,6 +1467,7 @@ class BooleanClassExtentHelper: ... print(c) #doctest: +SKIP ( ex:Fire OR ex:Water ) """ + def __init__(self, operator): self.operator = operator @@ -1501,8 +1508,8 @@ class BooleanClass(OWLRDFListProxy, Class): props = [] for s, p, o in graph.triples_choices((identifier, [OWL_NS.intersectionOf, - OWL_NS.unionOf], - None)): + OWL_NS.unionOf], + None)): props.append(p) operator = p assert len(props) == 1, repr(props) @@ -1629,7 +1636,7 @@ class Restriction(Class): OWL_NS.onProperty, propertyOrIdentifier(onProperty)) not in graph: graph.add((self.identifier, OWL_NS.onProperty, - propertyOrIdentifier(onProperty))) + propertyOrIdentifier(onProperty))) self.onProperty = onProperty restrTypes = [ (allValuesFrom, OWL_NS.allValuesFrom), @@ -1659,7 +1666,6 @@ class Restriction(Class): self.graph.add((self.identifier, RDF.type, OWL_NS.Restriction)) self.graph.remove((self.identifier, RDF.type, OWL_NS.Class)) - def serialize(self, graph): """ >>> g1 = Graph() @@ -1880,6 +1886,7 @@ class Restriction(Class): ### Infix Operators ### + some = Infix(lambda prop, _class: Restriction(prop, graph=_class.graph, someValuesFrom=_class)) only = Infix(lambda prop, _class: Restriction(prop, graph=_class.graph, @@ -1989,8 +1996,8 @@ class Property(AnnotatableTerms): rt = [] if OWL_NS.ObjectProperty in self.type: rt.append('ObjectProperty( %s annotation(%s)' - % (self.qname, first(self.comment) - and first(self.comment) or '')) + % (self.qname, first(self.comment) and + first(self.comment) or '')) if first(self.inverseOf): twoLinkInverse = first(first(self.inverseOf).inverseOf) if twoLinkInverse \ @@ -2000,9 +2007,9 @@ class Property(AnnotatableTerms): inverseRepr = repr(first(self.inverseOf)) rt.append(" inverseOf( %s )%s" % ( inverseRepr, - OWL_NS.SymmetricProperty in self.type - and ' Symmetric' - or '')) + OWL_NS.SymmetricProperty in self.type and + ' Symmetric' or + '')) for s, p, roleType in self.graph.triples_choices( (self.identifier, RDF.type, @@ -2012,9 +2019,9 @@ class Property(AnnotatableTerms): rt.append(str(roleType.split(OWL_NS)[-1])) else: rt.append('DatatypeProperty( %s %s' - % (self.qname, first(self.comment) - and first(self.comment) - or '')) + % (self.qname, first(self.comment) and + first(self.comment) or + '')) for s, p, roleType in self.graph.triples(( self.identifier, RDF.type, OWL_NS.FunctionalProperty)): rt.append(' Functional') @@ -2028,7 +2035,7 @@ class Property(AnnotatableTerms): elif first(g.triples_choices(( normalizedName, [OWL_NS.unionOf, - OWL_NS.intersectionOf], None))): + OWL_NS.intersectionOf], None))): return repr(term) else: return str(term.qname) @@ -2149,5 +2156,6 @@ def test(): import doctest doctest.testmod() + if __name__ == '__main__': test() diff --git a/rdflib/graph.py b/rdflib/graph.py index 36362913..b7092bb9 100644 --- a/rdflib/graph.py +++ b/rdflib/graph.py @@ -395,9 +395,9 @@ class Graph(Node): """Add a sequence of triple with context""" self.__store.addN((s, p, o, c) for s, p, o, c in quads - if isinstance(c, Graph) - and c.identifier is self.identifier - and _assertnode(s,p,o) + if isinstance(c, Graph) and + c.identifier is self.identifier and + _assertnode(s, p, o) ) def remove(self, triple): @@ -422,7 +422,6 @@ class Graph(Node): for (s, p, o), cg in self.__store.triples((s, p, o), context=self): yield (s, p, o) - def __getitem__(self, item): """ A graph can be "sliced" as a shortcut for the triples method @@ -466,9 +465,9 @@ class Graph(Node): if isinstance(item, slice): - s,p,o=item.start,item.stop,item.step + s, p, o = item.start, item.stop, item.step if s is None and p is None and o is None: - return self.triples((s,p,o)) + return self.triples((s, p, o)) elif s is None and p is None: return self.subject_predicates(o) elif s is None and o is None: @@ -476,16 +475,16 @@ class Graph(Node): elif p is None and o is None: return self.predicate_objects(s) elif s is None: - return self.subjects(p,o) + return self.subjects(p, o) elif p is None: - return self.predicates(s,o) + return self.predicates(s, o) elif o is None: - return self.objects(s,p) + return self.objects(s, p) else: # all given - return (s,p,o) in self + return (s, p, o) in self - elif isinstance(item, (Path,Node)): + elif isinstance(item, (Path, Node)): return self.predicate_objects(item) @@ -530,15 +529,15 @@ class Graph(Node): def __lt__(self, other): return (other is None) \ - or (isinstance(other, Graph) - and self.identifier < other.identifier) + or (isinstance(other, Graph) and + self.identifier < other.identifier) def __le__(self, other): return self < other or self == other def __gt__(self, other): - return (isinstance(other, Graph) - and self.identifier > other.identifier) \ + return (isinstance(other, Graph) and + self.identifier > other.identifier) \ or (other is not None) def __ge__(self, other): @@ -708,7 +707,6 @@ class Graph(Node): return default return self.value(subject, RDFS.label, default=default, any=True) - def preferredLabel(self, subject, lang=None, default=None, labelProperties=(SKOS.prefLabel, RDFS.label)): """ @@ -758,11 +756,11 @@ class Graph(Node): # setup the language filtering if lang is not None: if lang == '': # we only want not language-tagged literals - langfilter = lambda l: l.language is None + def langfilter(l): return l.language is None else: - langfilter = lambda l: l.language == lang + def langfilter(l): return l.language == lang else: # we don't care about language tags - langfilter = lambda l: True + def langfilter(l): return True for labelProp in labelProperties: labels = list(filter(langfilter, self.objects(subject, labelProp))) @@ -1062,9 +1060,9 @@ class Graph(Node): try: return self.store.query( query_object, initNs, initBindings, - self.default_union - and '__UNION__' - or self.identifier, + self.default_union and + '__UNION__' or + self.identifier, **kwargs) except NotImplementedError: pass # store has no own implementation @@ -1078,8 +1076,8 @@ class Graph(Node): query_object, initBindings, initNs, **kwargs)) def update(self, update_object, processor='sparql', - initNs=None, initBindings=None, - use_store_provided=True, **kwargs): + initNs=None, initBindings=None, + use_store_provided=True, **kwargs): """Update this graph with the given update query.""" initBindings = initBindings or {} initNs = initNs or dict(self.namespaces()) @@ -1088,9 +1086,9 @@ class Graph(Node): try: return self.store.update( update_object, initNs, initBindings, - self.default_union - and '__UNION__' - or self.identifier, + self.default_union and + '__UNION__' or + self.identifier, **kwargs) except NotImplementedError: pass # store has no own implementation @@ -1100,7 +1098,6 @@ class Graph(Node): return processor.update(update_object, initBindings, initNs, **kwargs) - def n3(self): """return an n3 identifier for the Graph""" return "[%s]" % self.identifier.n3() @@ -1191,8 +1188,6 @@ class Graph(Node): return Collection(self, identifier) - - def resource(self, identifier): """Create a new ``Resource`` instance. @@ -1272,6 +1267,7 @@ class Graph(Node): return retval + class ConjunctiveGraph(Graph): """ @@ -1294,7 +1290,7 @@ class ConjunctiveGraph(Graph): assert self.store.context_aware, ("ConjunctiveGraph must be backed by" " a context aware store.") self.context_aware = True - self.default_union = True # Conjunctive! + self.default_union = True # Conjunctive! self.default_context = Graph(store=self.store, identifier=identifier or BNode()) @@ -1316,46 +1312,43 @@ class ConjunctiveGraph(Graph): elif len(triple_or_quad) == 4: (s, p, o, c) = triple_or_quad c = self._graph(c) - return s,p,o,c - + return s, p, o, c def __contains__(self, triple_or_quad): """Support for 'triple/quad in graph' syntax""" - s,p,o,c = self._spoc(triple_or_quad) - for t in self.triples((s,p,o), context=c): + s, p, o, c = self._spoc(triple_or_quad) + for t in self.triples((s, p, o), context=c): return True return False - def add(self, triple_or_quad): - """ Add a triple or quad to the store. if a triple is given it is added to the default context """ - s,p,o,c = self._spoc(triple_or_quad, default=True) + s, p, o, c = self._spoc(triple_or_quad, default=True) - _assertnode(s,p,o) + _assertnode(s, p, o) self.store.add((s, p, o), context=c, quoted=False) def _graph(self, c): - if c is None: return None + if c is None: + return None if not isinstance(c, Graph): return self.get_context(c) else: return c - def addN(self, quads): """Add a sequence of triples with context""" self.store.addN( (s, p, o, self._graph(c)) for s, p, o, c in quads if _assertnode(s, p, o) - ) + ) def remove(self, triple_or_quad): """ @@ -1366,7 +1359,7 @@ class ConjunctiveGraph(Graph): a quad is removed from the given context only """ - s,p,o,c = self._spoc(triple_or_quad) + s, p, o, c = self._spoc(triple_or_quad) self.store.remove((s, p, o), context=c) @@ -1379,11 +1372,11 @@ class ConjunctiveGraph(Graph): keyword parameter. The kw param takes precedence. """ - s,p,o,c = self._spoc(triple_or_quad) + s, p, o, c = self._spoc(triple_or_quad) context = self._graph(context or c) if self.default_union: - if context==self.default_context: + if context == self.default_context: context = None else: if context is None: @@ -1402,7 +1395,7 @@ class ConjunctiveGraph(Graph): def quads(self, triple_or_quad=None): """Iterate over all the quads in the entire conjunctive graph""" - s,p,o,c = self._spoc(triple_or_quad) + s, p, o, c = self._spoc(triple_or_quad) for (s, p, o), cg in self.store.triples((s, p, o), context=c): for ctx in cg: @@ -1413,7 +1406,7 @@ class ConjunctiveGraph(Graph): s, p, o = triple if context is None: if not self.default_union: - context=self.default_context + context = self.default_context else: context = self._graph(context) @@ -1481,7 +1474,7 @@ class ConjunctiveGraph(Graph): g_id = URIRef(g_id) context = Graph(store=self.store, identifier=g_id) - context.remove((None, None, None)) # hmm ? + context.remove((None, None, None)) # hmm ? context.parse(source, publicID=publicID, format=format, **args) return context @@ -1489,9 +1482,9 @@ class ConjunctiveGraph(Graph): return (ConjunctiveGraph, (self.store, self.identifier)) - DATASET_DEFAULT_GRAPH_ID = URIRef('urn:x-rdflib:default') + class Dataset(ConjunctiveGraph): __doc__ = """ RDF 1.1 Dataset. Small extension to the Conjunctive Graph: @@ -1604,7 +1597,6 @@ class Dataset(ConjunctiveGraph): self.default_union = default_union - def __str__(self): pattern = ("[a rdflib:Dataset;rdflib:storage " "[a rdflib:Store;rdfs:label '%s']]") @@ -1655,11 +1647,12 @@ class Dataset(ConjunctiveGraph): def quads(self, quad): for s, p, o, c in super(Dataset, self).quads(quad): - if c.identifier==self.default_context: + if c.identifier == self.default_context: yield (s, p, o, None) else: yield (s, p, o, c.identifier) + class QuotedGraph(Graph): """ Quoted Graphs are intended to implement Notation 3 formulae. They are @@ -1667,6 +1660,7 @@ class QuotedGraph(Graph): in order to maintain consistent formulae identification for scenarios such as implication and other such processing. """ + def __init__(self, store, identifier): super(QuotedGraph, self).__init__(store, identifier) @@ -1687,10 +1681,10 @@ class QuotedGraph(Graph): self.store.addN( (s, p, o, c) for s, p, o, c in quads - if isinstance(c, QuotedGraph) - and c.identifier is self.identifier - and _assertnode(s, p, o) - ) + if isinstance(c, QuotedGraph) and + c.identifier is self.identifier and + _assertnode(s, p, o) + ) def n3(self): """Return an n3 identifier for the Graph""" @@ -1711,7 +1705,7 @@ class QuotedGraph(Graph): # wrt to other Terms. # this must be done here, as the QuotedGraph cannot be # circularily imported in term.py -rdflib.term._ORDERING[QuotedGraph]=11 +rdflib.term._ORDERING[QuotedGraph] = 11 class Seq(object): @@ -1926,6 +1920,7 @@ class ReadOnlyGraphAggregate(ConjunctiveGraph): def __reduce__(self): raise UnSupportedAggregateOperation() + def _assertnode(*terms): for t in terms: assert isinstance(t, Node), \ @@ -1937,5 +1932,6 @@ def test(): import doctest doctest.testmod() + if __name__ == '__main__': test() diff --git a/rdflib/namespace.py b/rdflib/namespace.py index 7ab00990..5cdbfb80 100644 --- a/rdflib/namespace.py +++ b/rdflib/namespace.py @@ -198,6 +198,7 @@ class _RDFNamespace(ClosedNamespace): """ Closed namespace for RDF terms """ + def __init__(self): super(_RDFNamespace, self).__init__( URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), @@ -284,6 +285,7 @@ class NamespaceManager(object): >>> """ + def __init__(self, graph): self.graph = graph self.__cache = {} @@ -357,7 +359,6 @@ class NamespaceManager(object): return self.__cache[uri] def bind(self, prefix, namespace, override=True, replace=False): - """bind a given namespace to the prefix if override, rebind, even if the given namespace is already diff --git a/rdflib/parser.py b/rdflib/parser.py index 5864820a..9dc60f65 100644 --- a/rdflib/parser.py +++ b/rdflib/parser.py @@ -117,7 +117,7 @@ class URLInputSource(InputSource): self.content_type = self.content_type.split(";", 1)[0] self.setByteStream(file) # TODO: self.setEncoding(encoding) - self.response_info = file.info() # a mimetools.Message instance + self.response_info = file.info() # a mimetools.Message instance def __repr__(self): return self.url @@ -191,7 +191,7 @@ def create_input_source(source=None, publicID=None, input_source = URLInputSource(absolute_location, format) auto_close = True # publicID = publicID or absolute_location # Further to fix - # for issue 130 + # for issue 130 if file is not None: input_source = FileInputSource(file) diff --git a/rdflib/paths.py b/rdflib/paths.py index ea6a8b38..69147fbe 100644 --- a/rdflib/paths.py +++ b/rdflib/paths.py @@ -308,7 +308,6 @@ class AlternativePath(Path): return '|'.join(a.n3() for a in self.args) - class MulPath(Path): def __init__(self, path, mod): self.path = path @@ -413,7 +412,6 @@ class MulPath(Path): return '%s%s' % (self.path.n3(), self.mod) - class NegatedPath(Path): def __init__(self, arg): if isinstance(arg, (URIRef, InvPath)): @@ -471,6 +469,7 @@ def path_sequence(self, other): def evalPath(graph, t): return ((s, o) for s, p, o in graph.triples(t)) + def mul_path(p, mul): """ cardinality path @@ -492,7 +491,6 @@ def neg_path(p): return NegatedPath(p) - if __name__ == '__main__': import doctest diff --git a/rdflib/plugin.py b/rdflib/plugin.py index 3ad1cafd..33d6ae7a 100644 --- a/rdflib/plugin.py +++ b/rdflib/plugin.py @@ -129,6 +129,7 @@ def plugins(name=None, kind=None): kind is None or kind == p.kind): yield p + register( 'default', Store, 'rdflib.plugins.memory', 'IOMemory') @@ -254,7 +255,6 @@ register( 'rdflib.plugins.parsers.trig', 'TrigParser') - register( 'sparql', Result, 'rdflib.plugins.sparql.processor', 'SPARQLResult') diff --git a/rdflib/plugins/memory.py b/rdflib/plugins/memory.py index f1cb5870..7345311a 100644 --- a/rdflib/plugins/memory.py +++ b/rdflib/plugins/memory.py @@ -2,6 +2,8 @@ from __future__ import absolute_import from __future__ import division from __future__ import print_function +import random + from rdflib.term import BNode from rdflib.store import Store, NO_STORE, VALID_STORE from six import iteritems @@ -21,6 +23,7 @@ class Memory(Store): Authors: Michel Pelletier, Daniel Krech, Stefan Niederhauser """ + def __init__(self, configuration=None, identifier=None): super(Memory, self).__init__(configuration) self.identifier = identifier @@ -147,7 +150,7 @@ class Memory(Store): yield (s, p, o), self.__contexts() def __len__(self, context=None): - #@@ optimize + # @@ optimize i = 0 for triple in self.triples((None, None, None)): i += 1 @@ -357,7 +360,7 @@ class IOMemory(Store): if self.__tripleHasContext(enctriple, cid)) def contexts(self, triple=None): - if triple is None or triple is (None,None,None): + if triple is None or triple is (None, None, None): return (context for context in self.__all_contexts) enctriple = self.__encodeTriple(triple) @@ -383,13 +386,11 @@ class IOMemory(Store): if not self.graph_aware: Store.remove_graph(self, graph) else: - self.remove((None,None,None), graph) + self.remove((None, None, None), graph) try: self.__all_contexts.remove(graph) except KeyError: - pass # we didn't know this graph, no problem - - + pass # we didn't know this graph, no problem # internal utility methods below @@ -500,10 +501,8 @@ class IOMemory(Store): yield -import random - - def randid(randint=random.randint, choice=random.choice, signs=(-1, 1)): return choice(signs) * randint(1, 2000000000) + del random diff --git a/rdflib/plugins/parsers/ntriples.py b/rdflib/plugins/parsers/ntriples.py index 4f56a890..0a47ecb9 100644 --- a/rdflib/plugins/parsers/ntriples.py +++ b/rdflib/plugins/parsers/ntriples.py @@ -60,6 +60,7 @@ class Sink(object): self.length += 1 print(s, p, o) + quot = {'t': u'\t', 'n': u'\n', 'r': u'\r', '"': u'"', '\\': u'\\'} r_safe = re.compile(r'([\x20\x21\x23-\x5B\x5D-\x7E]+)') @@ -71,7 +72,7 @@ def unquote(s): """Unquote an N-Triples string.""" if not validate: - if isinstance(s, text_type): # nquads + if isinstance(s, text_type): # nquads s = decodeUnicodeEscape(s) else: s = s.decode('unicode-escape') @@ -106,6 +107,7 @@ def unquote(s): raise ParseError("Illegal literal character: %r" % s[0]) return u''.join(result) + r_hibyte = re.compile(r'([\x80-\xFF])') diff --git a/rdflib/plugins/parsers/rdfxml.py b/rdflib/plugins/parsers/rdfxml.py index 6e6d2df2..dd8659a1 100644 --- a/rdflib/plugins/parsers/rdfxml.py +++ b/rdflib/plugins/parsers/rdfxml.py @@ -173,7 +173,7 @@ class RDFXMLHandler(handler.ContentHandler): pass def add_reified(self, sid, spo): - s,p,o = spo + s, p, o = spo self.store.add((sid, RDF.type, RDF.Statement)) self.store.add((sid, RDF.subject, s)) self.store.add((sid, RDF.predicate, p)) @@ -477,7 +477,7 @@ class RDFXMLHandler(handler.ContentHandler): (self.parent.subject, current.predicate, current.object)) if current.id is not None: self.add_reified(current.id, (self.parent.subject, - current.predicate, current.object)) + current.predicate, current.object)) current.subject = None def list_node_element_end(self, name, qname): diff --git a/rdflib/plugins/parsers/trig.py b/rdflib/plugins/parsers/trig.py index b0410a1d..f4c3ff1b 100644 --- a/rdflib/plugins/parsers/trig.py +++ b/rdflib/plugins/parsers/trig.py @@ -34,7 +34,6 @@ class TrigSinkParser(SinkParser): if j >= 0: return self.checkDot(argstr, j) - return j def labelOrSubject(self, argstr, i, res): @@ -48,13 +47,13 @@ class TrigSinkParser(SinkParser): return j if argstr[i] == '[': - j = self.skipSpace(argstr, i+1) + j = self.skipSpace(argstr, i + 1) if j < 0: self.BadSyntax(argstr, i, - "Expected ] got EOF") + "Expected ] got EOF") if argstr[j] == ']': res.append(self.blankNode()) - return j+1 + return j + 1 return -1 def graph(self, argstr, i): @@ -68,8 +67,9 @@ class TrigSinkParser(SinkParser): """ #import pdb; pdb.set_trace() - j = self.sparqlTok('GRAPH', argstr, i) # optional GRAPH keyword - if j >= 0: i = j + j = self.sparqlTok('GRAPH', argstr, i) # optional GRAPH keyword + if j >= 0: + i = j r = [] j = self.labelOrSubject(argstr, i, r) @@ -77,15 +77,14 @@ class TrigSinkParser(SinkParser): graph = r[0] i = j else: - graph = self._store.graph.identifier # hack - + graph = self._store.graph.identifier # hack j = self.skipSpace(argstr, i) if j < 0: self.BadSyntax(argstr, i, "EOF found when expected graph") - if argstr[j:j + 1] == "=": # optional = for legacy support + if argstr[j:j + 1] == "=": # optional = for legacy support i = self.skipSpace(argstr, j + 1) if i < 0: @@ -93,11 +92,10 @@ class TrigSinkParser(SinkParser): else: i = j - if argstr[i:i+1] != "{": - return -1 # the node wasn't part of a graph + if argstr[i:i + 1] != "{": + return -1 # the node wasn't part of a graph - - j = i+1 + j = i + 1 oldParentContext = self._parentContext self._parentContext = self._context @@ -123,12 +121,10 @@ class TrigSinkParser(SinkParser): self._context = self._parentContext self._reason2 = reason2 self._parentContext = oldParentContext - #res.append(subj.close()) # No use until closed + # res.append(subj.close()) # No use until closed return j - - class TrigParser(Parser): """ An RDFLib parser for TriG @@ -151,7 +147,7 @@ class TrigParser(Parser): conj_graph = ConjunctiveGraph(store=graph.store, identifier=graph.identifier) conj_graph.default_context = graph # TODO: CG __init__ should have a # default_context arg - # TODO: update N3Processor so that it can use conj_graph as the sink + # TODO: update N3Processor so that it can use conj_graph as the sink conj_graph.namespace_manager = graph.namespace_manager sink = RDFSink(conj_graph) diff --git a/rdflib/plugins/serializers/nt.py b/rdflib/plugins/serializers/nt.py index 77ea5e8c..ea2e2f32 100644 --- a/rdflib/plugins/serializers/nt.py +++ b/rdflib/plugins/serializers/nt.py @@ -20,7 +20,7 @@ class NTSerializer(Serializer): def __init__(self, store): Serializer.__init__(self, store) - self.encoding = 'ascii' # n-triples are ascii encoded + self.encoding = 'ascii' # n-triples are ascii encoded def serialize(self, stream, base=None, encoding=None, **args): if base is not None: @@ -41,7 +41,7 @@ class NT11Serializer(NTSerializer): """ def __init__(self, store): - Serializer.__init__(self, store) # default to utf-8 + Serializer.__init__(self, store) # default to utf-8 def _nt_row(triple): @@ -79,8 +79,8 @@ def _quote_encode(l): .replace('"', '\\"')\ .replace('\r', '\\r') -def _nt_unicode_error_resolver(err): +def _nt_unicode_error_resolver(err): """ Do unicode char replaces as defined in https://www.w3.org/TR/2004/REC-rdf-testcases-20040210/#ntrip_strings """ @@ -91,6 +91,7 @@ def _nt_unicode_error_resolver(err): return fmt % c string = err.object[err.start:err.end] - return ( "".join( _replace_single(c) for c in string ), err.end ) + return ("".join(_replace_single(c) for c in string), err.end) + codecs.register_error('_rdflib_nt_escape', _nt_unicode_error_resolver) diff --git a/rdflib/plugins/serializers/rdfxml.py b/rdflib/plugins/serializers/rdfxml.py index 71602438..d5ca78b9 100644 --- a/rdflib/plugins/serializers/rdfxml.py +++ b/rdflib/plugins/serializers/rdfxml.py @@ -139,6 +139,7 @@ class XMLSerializer(Serializer): write("%s<%s rdf:resource=%s/>\n" % (indent, qname, quoteattr(self.relativize(object)))) + XMLLANG = "http://www.w3.org/XML/1998/namespacelang" XMLBASE = "http://www.w3.org/XML/1998/namespacebase" OWL_NS = Namespace('http://www.w3.org/2002/07/owl#') @@ -273,8 +274,8 @@ class PrettyXMLSerializer(Serializer): if object.language: writer.attribute(XMLLANG, object.language) - if (object.datatype == RDF.XMLLiteral and - isinstance(object.value, xml.dom.minidom.Document)): + if (object.datatype == RDF.XMLLiteral + and isinstance(object.value, xml.dom.minidom.Document)): writer.attribute(RDF.parseType, "Literal") writer.text(u"") writer.stream.write(object) diff --git a/rdflib/plugins/serializers/trig.py b/rdflib/plugins/serializers/trig.py index 6ccd8e10..6c05ad75 100644 --- a/rdflib/plugins/serializers/trig.py +++ b/rdflib/plugins/serializers/trig.py @@ -60,14 +60,15 @@ class TrigSerializer(TurtleSerializer): firstTime = True for store, (ordered_subjects, subjects, ref) in self._contexts.items(): - if not ordered_subjects: continue + if not ordered_subjects: + continue self._references = ref self._serialized = {} self.store = store self._subjects = subjects - if self.default_context and store.identifier==self.default_context: + if self.default_context and store.identifier == self.default_context: self.write(self.indent() + '\n{') else: if isinstance(store.identifier, BNode): diff --git a/rdflib/plugins/serializers/trix.py b/rdflib/plugins/serializers/trix.py index 84b9f820..fceec6bd 100644 --- a/rdflib/plugins/serializers/trix.py +++ b/rdflib/plugins/serializers/trix.py @@ -10,7 +10,7 @@ from six import text_type, b __all__ = ['TriXSerializer'] -## TODO: MOve this somewhere central +# TODO: Move this somewhere central TRIXNS = Namespace("http://www.w3.org/2004/03/trix/trix-1/") XMLNS = Namespace("http://www.w3.org/XML/1998/namespace") diff --git a/rdflib/plugins/serializers/turtle.py b/rdflib/plugins/serializers/turtle.py index 156f8a6c..8ab9538e 100644 --- a/rdflib/plugins/serializers/turtle.py +++ b/rdflib/plugins/serializers/turtle.py @@ -14,7 +14,8 @@ from six import b, text_type __all__ = ['RecursiveSerializer', 'TurtleSerializer'] -def _object_comparator(a,b): + +def _object_comparator(a, b): """ for nice clean output we sort the objects of triples, some of them are literals, @@ -24,8 +25,10 @@ def _object_comparator(a,b): """ try: - if a>b: return 1 - if a<b: return -1 + if a > b: + return 1 + if a < b: + return -1 return 0 except TypeError: @@ -48,8 +51,8 @@ class RecursiveSerializer(Serializer): self.reset() def addNamespace(self, prefix, uri): - if prefix in self.namespaces and self.namespaces[prefix]!=uri: - raise Exception("Trying to override namespace prefix %s => %s, but it's already bound to %s"%(prefix, uri, self.namespaces[prefix])) + if prefix in self.namespaces and self.namespaces[prefix] != uri: + raise Exception("Trying to override namespace prefix %s => %s, but it's already bound to %s" % (prefix, uri, self.namespaces[prefix])) self.namespaces[prefix] = uri def checkSubject(self, subject): @@ -57,8 +60,8 @@ class RecursiveSerializer(Serializer): if ((self.isDone(subject)) or (subject not in self._subjects) or ((subject in self._topLevels) and (self.depth > 1)) - or (isinstance(subject, URIRef) - and (self.depth >= self.maxDepth))): + or (isinstance(subject, URIRef) and + (self.depth >= self.maxDepth))): return False return True @@ -95,7 +98,7 @@ class RecursiveSerializer(Serializer): def preprocessTriple(self, spo): s, p, o = spo - self._references[o]+=1 + self._references[o] += 1 self._subjects[s] = True def reset(self): @@ -243,8 +246,8 @@ class TurtleSerializer(RecursiveSerializer): if isinstance(node, Literal) and node.datatype: self.getQName(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT) p = triple[1] - if isinstance(p, BNode): # hmm - when is P ever a bnode? - self._references[p]+=1 + if isinstance(p, BNode): # hmm - when is P ever a bnode? + self._references[p] += 1 def getQName(self, uri, gen_prefix=True): if not isinstance(uri, URIRef): @@ -268,7 +271,8 @@ class TurtleSerializer(RecursiveSerializer): prefix, namespace, local = parts # QName cannot end with . - if local.endswith("."): return None + if local.endswith("."): + return None prefix = self.addNamespace(prefix, namespace) diff --git a/rdflib/plugins/sleepycat.py b/rdflib/plugins/sleepycat.py index c265e190..745e270a 100644 --- a/rdflib/plugins/sleepycat.py +++ b/rdflib/plugins/sleepycat.py @@ -1,3 +1,7 @@ +import logging +from threading import Thread +from os.path import exists, abspath +from os import mkdir from rdflib.store import Store, VALID_STORE, NO_STORE from rdflib.term import URIRef from six import b @@ -17,10 +21,7 @@ except ImportError: has_bsddb = True except ImportError: has_bsddb = False -from os import mkdir -from os.path import exists, abspath -from threading import Thread if has_bsddb: # These are passed to bsddb when creating DBs @@ -34,7 +35,6 @@ if has_bsddb: # passed to db.DB.Open() DBOPENFLAGS = db.DB_THREAD -import logging logger = logging.getLogger(__name__) __all__ = ['Sleepycat'] @@ -65,7 +65,7 @@ class Sleepycat(Store): if not exists(homeDir): if create is True: mkdir(homeDir) - # TODO: implement create method and refactor this to it + # TODO: implement create method and refactor this to it self.create(homeDir) else: return NO_STORE @@ -314,7 +314,7 @@ class Sleepycat(Store): o = _to_string(object, txn=txn) c = _to_string(context, txn=txn) value = self.__indicies[0].get(bb("%s^%s^%s^%s^" % - (c, s, p, o)), txn=txn) + (c, s, p, o)), txn=txn) if value is not None: self.__remove((bb(s), bb(p), bb(o)), bb(c), txn=txn) self.__needs_sync = True diff --git a/rdflib/plugins/sparql/__init__.py b/rdflib/plugins/sparql/__init__.py index 250fb501..bc1227f2 100644 --- a/rdflib/plugins/sparql/__init__.py +++ b/rdflib/plugins/sparql/__init__.py @@ -30,8 +30,6 @@ NotImplementedError if they cannot handle a certain part PLUGIN_ENTRY_POINT = 'rdf.plugins.sparqleval' - - from . import parser from . import operators from . import parserutils diff --git a/rdflib/plugins/sparql/aggregates.py b/rdflib/plugins/sparql/aggregates.py index 3e657c99..b63b6edb 100644 --- a/rdflib/plugins/sparql/aggregates.py +++ b/rdflib/plugins/sparql/aggregates.py @@ -13,6 +13,7 @@ from decimal import Decimal Aggregation functions """ + class Accumulator(object): """abstract base class for different aggregation functions """ @@ -73,8 +74,8 @@ class Counter(Accumulator): def type_safe_numbers(*args): if ( - any(isinstance(arg, float) for arg in args) - and any(isinstance(arg, Decimal) for arg in args) + any(isinstance(arg, float) for arg in args) and + any(isinstance(arg, Decimal) for arg in args) ): return map(float, args) return args @@ -106,6 +107,7 @@ class Sum(Accumulator): def get_value(self): return Literal(self.value, datatype=self.datatype) + class Average(Accumulator): def __init__(self, aggregation): @@ -193,7 +195,7 @@ class Sample(Accumulator): def update(self, row, aggregator): try: # set the value now - aggregator.bindings[self.var] = _eval(self.expr, row) + aggregator.bindings[self.var] = _eval(self.expr, row) # and skip this accumulator for future rows del aggregator.accumulators[self.var] except NotBoundError: @@ -203,6 +205,7 @@ class Sample(Accumulator): # set None if no value was set return None + class GroupConcat(Accumulator): def __init__(self, aggregation): diff --git a/rdflib/plugins/sparql/algebra.py b/rdflib/plugins/sparql/algebra.py index 56a5cfad..5fa445c7 100644 --- a/rdflib/plugins/sparql/algebra.py +++ b/rdflib/plugins/sparql/algebra.py @@ -67,9 +67,11 @@ def Filter(expr, p): def Extend(p, expr, var): return CompValue('Extend', p=p, expr=expr, var=var) + def Values(res): return CompValue('values', res=res) + def Project(p, PV): return CompValue('Project', p=p, PV=PV) @@ -79,11 +81,11 @@ def Group(p, expr=None): def _knownTerms(triple, varsknown, varscount): - return (len([ x for x in triple if x not in varsknown and - isinstance(x, (Variable, BNode)) ]), + return (len([x for x in triple if x not in varsknown and + isinstance(x, (Variable, BNode))]), -sum(varscount.get(x, 0) for x in triple), not isinstance(triple[2], Literal), - ) + ) def reorderTriples(l): @@ -117,8 +119,8 @@ def reorderTriples(l): 1], varsknown, varscount), x[1]) for x in l[i:]) t = l[i][0][0] # top block has this many terms bound j = 0 - while i+j < len(l) and l[i+j][0][0] == t: - for c in l[i+j][1]: + while i + j < len(l) and l[i + j][0][0] == t: + for c in l[i + j][1]: _addvar(c, varsknown) j += 1 i += 1 @@ -150,7 +152,6 @@ def translatePName(p, prologue): def translatePath(p): - """ Translate PropertyPath expressions """ @@ -196,7 +197,6 @@ def translatePath(p): def translateExists(e): - """ Translate the graph pattern used by EXISTS and NOT EXISTS http://www.w3.org/TR/sparql11-query/#sparqlCollectFilters @@ -216,7 +216,6 @@ def translateExists(e): def collectAndRemoveFilters(parts): - """ FILTER expressions apply to the whole group graph pattern in which @@ -444,7 +443,8 @@ def _addVars(x, children): x["_vars"] = set() elif x.name == "Extend": # vars only used in the expr for a bind should not be included - x["_vars"] = reduce(operator.or_, [ child for child,part in zip(children,x) if part!='expr' ], set()) + x["_vars"] = reduce(operator.or_, [child for child, + part in zip(children, x) if part != 'expr'], set()) else: x["_vars"] = set(reduce(operator.or_, children, set())) @@ -490,7 +490,6 @@ def translateAggregates(q, M): v.expr = traverse(v.expr, functools.partial(_sample, v=v.evar)) v.expr = traverse(v.expr, functools.partial(_aggs, A=A)) - # having clause if traverse(q.having, _hasAggregate, complete=False): q.having = traverse(q.having, _sample) @@ -606,7 +605,7 @@ def translate(q): # ORDER BY if q.orderby: M = OrderBy(M, [CompValue('OrderCondition', expr=c.expr, - order=c.order) for c in q.orderby.condition]) + order=c.order) for c in q.orderby.condition]) # PROJECT M = Project(M, PV) @@ -645,7 +644,6 @@ def simplify(n): def analyse(n, children): - """ Some things can be lazily joined. This propegates whether they can up the tree @@ -807,6 +805,7 @@ def pprintAlgebra(q): for x in q: pp(x) + if __name__ == '__main__': import sys from rdflib.plugins.sparql import parser diff --git a/rdflib/plugins/sparql/evaluate.py b/rdflib/plugins/sparql/evaluate.py index a693dff7..4ce4c954 100644 --- a/rdflib/plugins/sparql/evaluate.py +++ b/rdflib/plugins/sparql/evaluate.py @@ -30,8 +30,8 @@ from rdflib.plugins.sparql.evalutils import ( from rdflib.plugins.sparql.aggregates import Aggregator from rdflib.plugins.sparql.algebra import Join, ToMultiSet, Values -def evalBGP(ctx, bgp): +def evalBGP(ctx, bgp): """ A basic graph pattern """ @@ -96,7 +96,7 @@ def evalLazyJoin(ctx, join): for a in evalPart(ctx, join.p1): c = ctx.thaw(a) for b in evalPart(c, join.p2): - yield b.merge(a) # merge, as some bindings may have been forgotten + yield b.merge(a) # merge, as some bindings may have been forgotten def evalJoin(ctx, join): @@ -142,8 +142,8 @@ def evalLeftJoin(ctx, join): # even without prior bindings... p1_vars = join.p1._vars if p1_vars is None \ - or not any(_ebv(join.expr, b) for b in - evalPart(ctx.thaw(a.remember(p1_vars)), join.p2)): + or not any(_ebv(join.expr, b) for b in + evalPart(ctx.thaw(a.remember(p1_vars)), join.p2)): yield a @@ -272,7 +272,6 @@ def evalPart(ctx, part): def evalGroup(ctx, group): - """ http://www.w3.org/TR/sparql11-query/#defn_algGroup """ @@ -324,7 +323,7 @@ def evalOrderBy(ctx, part): def evalSlice(ctx, slice): res = evalPart(ctx, slice.p) - return itertools.islice(res, slice.start, slice.start+slice.length if slice.length is not None else None) + return itertools.islice(res, slice.start, slice.start + slice.length if slice.length is not None else None) def evalReduced(ctx, part): @@ -355,7 +354,7 @@ def evalReduced(ctx, part): # forget last position of row mru_queue.remove(row) else: - #row seems to be new + # row seems to be new yield row mru_set.add(row) if len(mru_set) > MAX: @@ -422,7 +421,7 @@ def evalConstructQuery(ctx, query): def evalQuery(graph, query, initBindings, base=None): - initBindings = dict( ( Variable(k),v ) for k,v in iteritems(initBindings) ) + initBindings = dict((Variable(k), v) for k, v in iteritems(initBindings)) ctx = QueryContext(graph, initBindings=initBindings) diff --git a/rdflib/plugins/sparql/evalutils.py b/rdflib/plugins/sparql/evalutils.py index dd0924d0..25353fe0 100644 --- a/rdflib/plugins/sparql/evalutils.py +++ b/rdflib/plugins/sparql/evalutils.py @@ -23,7 +23,6 @@ def _minus(a, b): yield x - def _join(a, b): for x in a: for y in b: @@ -32,7 +31,6 @@ def _join(a, b): def _ebv(expr, ctx): - """ Return true/false for the given expr Either the expr is itself true/false @@ -88,7 +86,6 @@ def _filter(a, expr): def _fillTemplate(template, solution): - """ For construct/deleteWhere and friends @@ -113,6 +110,7 @@ def _fillTemplate(template, solution): yield (_s, _p, _o) + def _val(v): """ utilitity for ordering things""" if isinstance(v, Variable): diff --git a/rdflib/plugins/sparql/operators.py b/rdflib/plugins/sparql/operators.py index 5fec1f45..74cd1269 100644 --- a/rdflib/plugins/sparql/operators.py +++ b/rdflib/plugins/sparql/operators.py @@ -534,7 +534,6 @@ def Builtin_UCASE(e, ctx): def Builtin_LANG(e, ctx): - """ http://www.w3.org/TR/sparql11-query/#func-lang @@ -587,6 +586,7 @@ def Builtin_EXISTS(e, ctx): _CUSTOM_FUNCTIONS = {} + def register_custom_function(uri, func, override=False, raw=False): """ Register a custom SPARQL function. @@ -600,6 +600,7 @@ def register_custom_function(uri, func, override=False, raw=False): raise ValueError("A function is already registered as %s" % uri.n3()) _CUSTOM_FUNCTIONS[uri] = (func, raw) + def custom_function(uri, override=False, raw=False): """ Decorator version of :func:`register_custom_function`. @@ -609,17 +610,18 @@ def custom_function(uri, override=False, raw=False): return func return decorator + def unregister_custom_function(uri, func): if _CUSTOM_FUNCTIONS.get(uri, (None, None))[0] != func: raise ValueError("This function is not registered as %s" % uri.n3()) del _CUSTOM_FUNCTIONS[uri] - + def Function(e, ctx): """ Custom functions and casts """ - pair =_CUSTOM_FUNCTIONS.get(e.iri) + pair = _CUSTOM_FUNCTIONS.get(e.iri) if pair is None: # no such function is registered raise SPARQLError('Unknown function %r' % e.iri) @@ -644,71 +646,71 @@ def Function(e, ctx): @custom_function(XSD.integer, raw=True) @custom_function(XSD.boolean, raw=True) def default_cast(e, ctx): - if not e.expr: - raise SPARQLError("Nothing given to cast.") - if len(e.expr) > 1: - raise SPARQLError("Cannot cast more than one thing!") + if not e.expr: + raise SPARQLError("Nothing given to cast.") + if len(e.expr) > 1: + raise SPARQLError("Cannot cast more than one thing!") - x = e.expr[0] + x = e.expr[0] - if e.iri == XSD.string: + if e.iri == XSD.string: - if isinstance(x, (URIRef, Literal)): - return Literal(x, datatype=XSD.string) - else: - raise SPARQLError( - "Cannot cast term %r of type %r" % (x, type(x))) - - if not isinstance(x, Literal): + if isinstance(x, (URIRef, Literal)): + return Literal(x, datatype=XSD.string) + else: raise SPARQLError( - "Can only cast Literals to non-string data-types") + "Cannot cast term %r of type %r" % (x, type(x))) - if x.datatype and not x.datatype in XSD_DTs: - raise SPARQLError( - "Cannot cast literal with unknown datatype: %r" % x.datatype) + if not isinstance(x, Literal): + raise SPARQLError( + "Can only cast Literals to non-string data-types") - if e.iri == XSD.dateTime: - if x.datatype and x.datatype not in (XSD.dateTime, XSD.string): - raise SPARQLError( - "Cannot cast %r to XSD:dateTime" % x.datatype) - try: - return Literal(isodate.parse_datetime(x), datatype=e.iri) - except: - raise SPARQLError("Cannot interpret '%r' as datetime" % x) + if x.datatype and not x.datatype in XSD_DTs: + raise SPARQLError( + "Cannot cast literal with unknown datatype: %r" % x.datatype) - if x.datatype == XSD.dateTime: - raise SPARQLError("Cannot cast XSD.dateTime to %r" % e.iri) + if e.iri == XSD.dateTime: + if x.datatype and x.datatype not in (XSD.dateTime, XSD.string): + raise SPARQLError( + "Cannot cast %r to XSD:dateTime" % x.datatype) + try: + return Literal(isodate.parse_datetime(x), datatype=e.iri) + except: + raise SPARQLError("Cannot interpret '%r' as datetime" % x) - if e.iri in (XSD.float, XSD.double): - try: - return Literal(float(x), datatype=e.iri) - except: - raise SPARQLError("Cannot interpret '%r' as float" % x) + if x.datatype == XSD.dateTime: + raise SPARQLError("Cannot cast XSD.dateTime to %r" % e.iri) - elif e.iri == XSD.decimal: - if "e" in x or "E" in x: # SPARQL/XSD does not allow exponents in decimals - raise SPARQLError("Cannot interpret '%r' as decimal" % x) - try: - return Literal(Decimal(x), datatype=e.iri) - except: - raise SPARQLError("Cannot interpret '%r' as decimal" % x) + if e.iri in (XSD.float, XSD.double): + try: + return Literal(float(x), datatype=e.iri) + except: + raise SPARQLError("Cannot interpret '%r' as float" % x) - elif e.iri == XSD.integer: - try: - return Literal(int(x), datatype=XSD.integer) - except: - raise SPARQLError("Cannot interpret '%r' as int" % x) - - elif e.iri == XSD.boolean: - # # I would argue that any number is True... - # try: - # return Literal(bool(int(x)), datatype=XSD.boolean) - # except: - if x.lower() in ("1", "true"): - return Literal(True) - if x.lower() in ("0", "false"): - return Literal(False) - raise SPARQLError("Cannot interpret '%r' as bool" % x) + elif e.iri == XSD.decimal: + if "e" in x or "E" in x: # SPARQL/XSD does not allow exponents in decimals + raise SPARQLError("Cannot interpret '%r' as decimal" % x) + try: + return Literal(Decimal(x), datatype=e.iri) + except: + raise SPARQLError("Cannot interpret '%r' as decimal" % x) + + elif e.iri == XSD.integer: + try: + return Literal(int(x), datatype=XSD.integer) + except: + raise SPARQLError("Cannot interpret '%r' as int" % x) + + elif e.iri == XSD.boolean: + # # I would argue that any number is True... + # try: + # return Literal(bool(int(x)), datatype=XSD.boolean) + # except: + if x.lower() in ("1", "true"): + return Literal(True) + if x.lower() in ("0", "false"): + return Literal(False) + raise SPARQLError("Cannot interpret '%r' as bool" % x) def UnaryNot(expr, ctx): @@ -905,6 +907,7 @@ def and_(*args): return Expr('ConditionalAndExpression', ConditionalAndExpression, expr=args[0], other=list(args[1:])) + TrueFilter = Expr('TrueFilter', lambda _1, _2: Literal(True)) diff --git a/rdflib/plugins/sparql/parser.py b/rdflib/plugins/sparql/parser.py index 62624c05..ab99e58b 100644 --- a/rdflib/plugins/sparql/parser.py +++ b/rdflib/plugins/sparql/parser.py @@ -42,7 +42,6 @@ def setDataType(terms): def expandTriples(terms): - """ Expand ; and , syntax for repeat predicates, subjects """ @@ -56,8 +55,8 @@ def expandTriples(terms): if t == ',': res.extend([res[-3], res[-2]]) elif t == ';': - if i+1 == len(terms) or terms[i+1] == ";" or terms[i+1] == ".": - continue # this semicolon is spurious + if i + 1 == len(terms) or terms[i + 1] == ";" or terms[i + 1] == ".": + continue # this semicolon is spurious res.append(res[0]) elif isinstance(t, list): # BlankNodePropertyList @@ -68,7 +67,7 @@ def expandTriples(terms): if len(t) > 1: res += t # is this bnode the subject of more triples? - if i + 1 < l and terms[i + 1] not in ".,;" : + if i + 1 < l and terms[i + 1] not in ".,;": res.append(t[0]) elif isinstance(t, ParseResults): res += t.asList() @@ -178,7 +177,7 @@ PN_CHARS_re = u'\\-0-9\u00B7\u0300-\u036F\u203F-\u2040' + PN_CHARS_U_re # [168] PN_PREFIX ::= PN_CHARS_BASE ((PN_CHARS|'.')* PN_CHARS)? PN_PREFIX = Regex(u'[%s](?:[%s\\.]*[%s])?' % (PN_CHARS_BASE_re, - PN_CHARS_re, PN_CHARS_re), flags=re.U) + PN_CHARS_re, PN_CHARS_re), flags=re.U) # [140] PNAME_NS ::= PN_PREFIX? ':' PNAME_NS = Optional( @@ -187,7 +186,7 @@ PNAME_NS = Optional( # [173] PN_LOCAL_ESC ::= '\' ( '_' | '~' | '.' | '-' | '!' | '$' | '&' | "'" | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%' ) PN_LOCAL_ESC_re = '\\\\[_~\\.\\-!$&"\'()*+,;=/?#@%]' -#PN_LOCAL_ESC = Regex(PN_LOCAL_ESC_re) # regex'd +# PN_LOCAL_ESC = Regex(PN_LOCAL_ESC_re) # regex'd #PN_LOCAL_ESC.setParseAction(lambda x: x[0][1:]) # [172] HEX ::= [0-9] | [A-F] | [a-f] @@ -195,28 +194,28 @@ PN_LOCAL_ESC_re = '\\\\[_~\\.\\-!$&"\'()*+,;=/?#@%]' # [171] PERCENT ::= '%' HEX HEX PERCENT_re = '%[0-9a-fA-F]{2}' -#PERCENT = Regex(PERCENT_re) # regex'd +# PERCENT = Regex(PERCENT_re) # regex'd #PERCENT.setParseAction(lambda x: unichr(int(x[0][1:], 16))) # [170] PLX ::= PERCENT | PN_LOCAL_ESC -PLX_re = '(%s|%s)'%(PN_LOCAL_ESC_re,PERCENT_re) -#PLX = PERCENT | PN_LOCAL_ESC # regex'd +PLX_re = '(%s|%s)' % (PN_LOCAL_ESC_re, PERCENT_re) +# PLX = PERCENT | PN_LOCAL_ESC # regex'd # [169] PN_LOCAL ::= (PN_CHARS_U | ':' | [0-9] | PLX ) ((PN_CHARS | '.' | ':' | PLX)* (PN_CHARS | ':' | PLX) )? PN_LOCAL = Regex(u"""([%(PN_CHARS_U)s:0-9]|%(PLX)s) (([%(PN_CHARS)s\\.:]|%(PLX)s)* - ([%(PN_CHARS)s:]|%(PLX)s) )?"""%dict(PN_CHARS_U=PN_CHARS_U_re, - PN_CHARS=PN_CHARS_re, - PLX=PLX_re), flags=re.X|re.UNICODE) + ([%(PN_CHARS)s:]|%(PLX)s) )?""" % dict(PN_CHARS_U=PN_CHARS_U_re, + PN_CHARS=PN_CHARS_re, + PLX=PLX_re), flags=re.X | re.UNICODE) + def _hexExpand(match): return unichr(int(match.group(0)[1:], 16)) -PN_LOCAL.setParseAction(lambda x: re.sub("(%s)"%PERCENT_re, _hexExpand, x[0])) - +PN_LOCAL.setParseAction(lambda x: re.sub("(%s)" % PERCENT_re, _hexExpand, x[0])) # [141] PNAME_LN ::= PNAME_NS PN_LOCAL @@ -267,7 +266,7 @@ DOUBLE.setParseAction( # [149] INTEGER_POSITIVE ::= '+' INTEGER INTEGER_POSITIVE = Suppress('+') + INTEGER.copy().leaveWhitespace() INTEGER_POSITIVE.setParseAction(lambda x: rdflib.Literal( - "+"+x[0], datatype=rdflib.XSD.integer)) + "+" + x[0], datatype=rdflib.XSD.integer)) # [150] DECIMAL_POSITIVE ::= '+' DECIMAL DECIMAL_POSITIVE = Suppress('+') + DECIMAL.copy().leaveWhitespace() @@ -505,7 +504,7 @@ PropertyListPath = Optional(PropertyListPathNotEmpty) # [77] PropertyListNotEmpty ::= Verb ObjectList ( ';' ( Verb ObjectList )? )* PropertyListNotEmpty = Verb + ObjectList + ZeroOrMore(';' + Optional(Verb + - ObjectList)) + ObjectList)) # [76] PropertyList ::= Optional(PropertyListNotEmpty) @@ -765,7 +764,7 @@ MultiplicativeExpression = Comp('MultiplicativeExpression', Param('expr', UnaryE # [116] AdditiveExpression ::= MultiplicativeExpression ( '+' MultiplicativeExpression | '-' MultiplicativeExpression | ( NumericLiteralPositive | NumericLiteralNegative ) ( ( '*' UnaryExpression ) | ( '/' UnaryExpression ) )* )* -### NOTE: The second part of this production is there because: +# NOTE: The second part of this production is there because: ### "In signed numbers, no white space is allowed between the sign and the number. The AdditiveExpression grammar rule allows for this by covering the two cases of an expression followed by a signed number. These produce an addition or subtraction of the unsigned number as appropriate." # Here (I think) this is not nescessary since pyparsing doesn't separate @@ -774,7 +773,7 @@ MultiplicativeExpression = Comp('MultiplicativeExpression', Param('expr', UnaryE AdditiveExpression = Comp('AdditiveExpression', Param('expr', MultiplicativeExpression) + ZeroOrMore(ParamList('op', '+') + ParamList('other', MultiplicativeExpression) | - ParamList('op', '-') + ParamList('other', MultiplicativeExpression))).setEvalFn(op.AdditiveExpression) + ParamList('op', '-') + ParamList('other', MultiplicativeExpression))).setEvalFn(op.AdditiveExpression) # [115] NumericExpression ::= AdditiveExpression @@ -979,7 +978,7 @@ SolutionModifier = Optional(Param('groupby', GroupClause)) + Optional(Param('hav # [9] SelectClause ::= 'SELECT' ( 'DISTINCT' | 'REDUCED' )? ( ( Var | ( '(' Expression 'AS' Var ')' ) )+ | '*' ) SelectClause = Keyword('SELECT') + Optional(Param('modifier', Keyword('DISTINCT') | Keyword('REDUCED'))) + (OneOrMore(ParamList('projection', Comp('vars', - Param('var', Var) | (Literal('(') + Param('expr', Expression) + Keyword('AS') + Param('evar', Var) + ')')))) | '*') + Param('var', Var) | (Literal('(') + Param('expr', Expression) + Keyword('AS') + Param('evar', Var) + ')')))) | '*') # [17] WhereClause ::= 'WHERE'? GroupGraphPattern WhereClause = Optional(Keyword('WHERE')) + Param('where', GroupGraphPattern) @@ -1013,7 +1012,7 @@ DescribeQuery = Comp('DescribeQuery', Keyword('DESCRIBE') + (OneOrMore(ParamList # [29] Update ::= Prologue ( Update1 ( ';' Update )? )? Update = Forward() Update <<= (ParamList('prologue', Prologue) + Optional(ParamList('request', - Update1) + Optional(';' + Update))) + Update1) + Optional(';' + Update))) # [2] Query ::= Prologue diff --git a/rdflib/plugins/sparql/parserutils.py b/rdflib/plugins/sparql/parserutils.py index 64b51d17..0a27d70d 100644 --- a/rdflib/plugins/sparql/parserutils.py +++ b/rdflib/plugins/sparql/parserutils.py @@ -45,7 +45,6 @@ the resulting CompValue # Comp('Sum')( Param('x')(Number) + '+' + Param('y')(Number) ) def value(ctx, val, variables=False, errors=False): - """ utility function for evaluating something... @@ -91,6 +90,7 @@ class ParamValue(object): This just keeps the name/value All cleverness is in the CompValue """ + def __init__(self, name, tokenList, isList): self.isList = isList self.name = name @@ -109,6 +109,7 @@ class Param(TokenConverter): if isList is true repeat occurrences of ParamList have their values merged in a list """ + def __init__(self, name, expr, isList=False): self.name = name self.isList = isList @@ -123,6 +124,7 @@ class ParamList(Param): """ A shortcut for a Param with isList=True """ + def __init__(self, name, expr): Param.__init__(self, name, expr, True) @@ -242,28 +244,28 @@ class Comp(TokenConverter): def prettify_parsetree(t, indent='', depth=0): - out = [] - if isinstance(t, ParseResults): - for e in t.asList(): - out.append(prettify_parsetree(e, indent, depth + 1)) - for k, v in sorted(t.items()): - out.append("%s%s- %s:\n" % (indent, ' ' * depth, k)) - out.append(prettify_parsetree(v, indent, depth + 1)) - elif isinstance(t, CompValue): - out.append("%s%s> %s:\n" % (indent, ' ' * depth, t.name)) - for k, v in t.items(): - out.append("%s%s- %s:\n" % (indent, ' ' * (depth + 1), k)) - out.append(prettify_parsetree(v, indent, depth + 2)) - elif isinstance(t, dict): - for k, v in t.items(): - out.append("%s%s- %s:\n" % (indent, ' ' * (depth + 1), k)) - out.append(prettify_parsetree(v, indent, depth + 2)) - elif isinstance(t, list): - for e in t: - out.append(prettify_parsetree(e, indent, depth + 1)) - else: - out.append("%s%s- %r\n" % (indent, ' ' * depth, t)) - return "".join(out) + out = [] + if isinstance(t, ParseResults): + for e in t.asList(): + out.append(prettify_parsetree(e, indent, depth + 1)) + for k, v in sorted(t.items()): + out.append("%s%s- %s:\n" % (indent, ' ' * depth, k)) + out.append(prettify_parsetree(v, indent, depth + 1)) + elif isinstance(t, CompValue): + out.append("%s%s> %s:\n" % (indent, ' ' * depth, t.name)) + for k, v in t.items(): + out.append("%s%s- %s:\n" % (indent, ' ' * (depth + 1), k)) + out.append(prettify_parsetree(v, indent, depth + 2)) + elif isinstance(t, dict): + for k, v in t.items(): + out.append("%s%s- %s:\n" % (indent, ' ' * (depth + 1), k)) + out.append(prettify_parsetree(v, indent, depth + 2)) + elif isinstance(t, list): + for e in t: + out.append(prettify_parsetree(e, indent, depth + 1)) + else: + out.append("%s%s- %r\n" % (indent, ' ' * depth, t)) + return "".join(out) if __name__ == '__main__': diff --git a/rdflib/plugins/sparql/processor.py b/rdflib/plugins/sparql/processor.py index 5ecbb435..857f5e03 100644 --- a/rdflib/plugins/sparql/processor.py +++ b/rdflib/plugins/sparql/processor.py @@ -46,13 +46,14 @@ class SPARQLResult(Result): self.askAnswer = res.get("askAnswer") self.graph = res.get("graph") + class SPARQLUpdateProcessor(UpdateProcessor): def __init__(self, graph): self.graph = graph def update(self, strOrQuery, initBindings={}, initNs={}): if isinstance(strOrQuery, string_types): - strOrQuery=translateUpdate(parseUpdate(strOrQuery), initNs=initNs) + strOrQuery = translateUpdate(parseUpdate(strOrQuery), initNs=initNs) return evalUpdate(self.graph, strOrQuery, initBindings) diff --git a/rdflib/plugins/sparql/results/graph.py b/rdflib/plugins/sparql/results/graph.py index b02aab7d..c47daa72 100644 --- a/rdflib/plugins/sparql/results/graph.py +++ b/rdflib/plugins/sparql/results/graph.py @@ -7,11 +7,12 @@ from rdflib.query import ( ResultException ) + class GraphResultParser(ResultParser): def parse(self, source, content_type): - res = Result('CONSTRUCT') # hmm - or describe?type_) + res = Result('CONSTRUCT') # hmm - or describe?type_) res.graph = Graph() res.graph.parse(source, format=content_type) diff --git a/rdflib/plugins/sparql/results/rdfresults.py b/rdflib/plugins/sparql/results/rdfresults.py index 94639154..08826809 100644 --- a/rdflib/plugins/sparql/results/rdfresults.py +++ b/rdflib/plugins/sparql/results/rdfresults.py @@ -21,7 +21,7 @@ class RDFResult(Result): graph = source rs = graph.value(predicate=RDF.type, object=RS.ResultSet) - # there better be only one :) + # there better be only one :) if rs is None: type_ = 'CONSTRUCT' diff --git a/rdflib/plugins/sparql/results/tsvresults.py b/rdflib/plugins/sparql/results/tsvresults.py index fb5da07d..6e9366f3 100644 --- a/rdflib/plugins/sparql/results/tsvresults.py +++ b/rdflib/plugins/sparql/results/tsvresults.py @@ -90,6 +90,7 @@ class TSVResultParser(ResultParser): else: return t + if __name__ == '__main__': import sys r = Result.parse(file(sys.argv[1]), format='tsv') diff --git a/rdflib/plugins/sparql/results/txtresults.py b/rdflib/plugins/sparql/results/txtresults.py index 7e91bc9e..d381f4ee 100644 --- a/rdflib/plugins/sparql/results/txtresults.py +++ b/rdflib/plugins/sparql/results/txtresults.py @@ -2,6 +2,7 @@ from rdflib import URIRef, BNode, Literal from rdflib.query import ResultSerializer + def _termString(t, namespace_manager): if t == None: return "-" @@ -21,23 +22,22 @@ class TXTResultSerializer(ResultSerializer): A write only QueryResult serializer for text/ascii tables """ - def serialize(self, stream, encoding, namespace_manager = None): - + def serialize(self, stream, encoding, namespace_manager=None): """ return a text table of query results """ - def c(s, w): """ center the string s in w wide string """ w -= len(s) h1 = h2 = w // 2 - if w % 2: h2 += 1 + if w % 2: + h2 += 1 return " " * h1 + s + " " * h2 - if self.result.type!='SELECT': + if self.result.type != 'SELECT': raise Exception("Can only pretty print SELECT results!") if not self.result: @@ -53,8 +53,7 @@ class TXTResultSerializer(ResultSerializer): stream.write( "|".join([c(k, maxlen[i]) for i, k in enumerate(keys)]) + "\n") - stream.write("-" * (len(maxlen)+sum(maxlen)) + "\n") + stream.write("-" * (len(maxlen) + sum(maxlen)) + "\n") for r in sorted(b): stream.write("|".join( [t + " " * (i - len(t)) for i, t in zip(maxlen, r)]) + "\n") - diff --git a/rdflib/plugins/sparql/results/xmlresults.py b/rdflib/plugins/sparql/results/xmlresults.py index ba35749c..e1daff92 100644 --- a/rdflib/plugins/sparql/results/xmlresults.py +++ b/rdflib/plugins/sparql/results/xmlresults.py @@ -80,9 +80,6 @@ class XMLResult(Result): self.askAnswer = boolean.text.lower().strip() == "true" - - - def parseTerm(element): """rdflib object (Literal, URIRef, BNode) for the given elementtree element""" @@ -137,6 +134,7 @@ class SPARQLXMLWriter: """ Python saxutils-based SPARQL XML Writer """ + def __init__(self, output, encoding='utf-8'): writer = XMLGenerator(output, encoding) writer.startDocument() diff --git a/rdflib/plugins/sparql/sparql.py b/rdflib/plugins/sparql/sparql.py index 146f9fad..9f6a5c17 100644 --- a/rdflib/plugins/sparql/sparql.py +++ b/rdflib/plugins/sparql/sparql.py @@ -17,7 +17,6 @@ from rdflib.plugins.sparql.parserutils import CompValue import rdflib.plugins.sparql - class SPARQLError(Exception): def __init__(self, msg=None): Exception.__init__(self, msg) @@ -30,6 +29,7 @@ class NotBoundError(SPARQLError): class AlreadyBound(SPARQLError): """Raised when trying to bind a variable that is already bound!""" + def __init__(self): SPARQLError.__init__(self) @@ -89,7 +89,7 @@ class Bindings(MutableMapping): d = d.outer def __str__(self): - return "Bindings({"+", ".join((k, self[k]) for k in self)+"})" + return "Bindings({" + ", ".join((k, self[k]) for k in self) + "})" def __repr__(self): return text_type(self) @@ -102,6 +102,7 @@ class FrozenDict(Mapping): Taken from http://stackoverflow.com/a/2704866/81121 """ + def __init__(self, *args, **kwargs): self._d = dict(*args, **kwargs) self._hash = None @@ -230,7 +231,8 @@ class QueryContext(object): def __init__(self, graph=None, bindings=None, initBindings=None): self.initBindings = initBindings self.bindings = Bindings(d=bindings or []) - if initBindings: self.bindings.update(initBindings) + if initBindings: + self.bindings.update(initBindings) if isinstance(graph, ConjunctiveGraph): self._dataset = graph @@ -281,7 +283,7 @@ class QueryContext(object): except: raise Exception( "Could not load %s as either RDF/XML, N3 or NTriples" % ( - source)) + source)) if not rdflib.plugins.sparql.SPARQL_LOAD_GRAPHS: # we are not loading - if we already know the graph @@ -375,7 +377,6 @@ class Prologue(object): self.namespace_manager.bind(prefix, uri, replace=True) def absolutize(self, iri): - """ Apply BASE / PREFIXes to URIs (and to datatypes in Literals) diff --git a/rdflib/plugins/sparql/update.py b/rdflib/plugins/sparql/update.py index 94cb01cd..daf380a3 100644 --- a/rdflib/plugins/sparql/update.py +++ b/rdflib/plugins/sparql/update.py @@ -64,6 +64,7 @@ def evalClear(ctx, u): for g in _graphAll(ctx, u.graphiri): g.remove((None, None, None)) + def evalDrop(ctx, u): """ http://www.w3.org/TR/sparql11-update/#drop @@ -276,12 +277,11 @@ def evalUpdate(graph, update, initBindings={}): for u in update: - initBindings = dict( ( Variable(k),v ) for k,v in iteritems(initBindings) ) + initBindings = dict((Variable(k), v) for k, v in iteritems(initBindings)) ctx = QueryContext(graph, initBindings=initBindings) ctx.prologue = u.prologue - try: if u.name == 'Load': evalLoad(ctx, u) diff --git a/rdflib/plugins/stores/auditable.py b/rdflib/plugins/stores/auditable.py index 61893d27..7a3492b7 100644 --- a/rdflib/plugins/stores/auditable.py +++ b/rdflib/plugins/stores/auditable.py @@ -56,7 +56,7 @@ class AuditableStore(Store): context = context.__class__(self.store, context.identifier) if context is not None else None ctxId = context.identifier if context is not None else None if list(self.store.triples(triple, context)): - return # triple already in store, do nothing + return # triple already in store, do nothing self.reverseOps.append((s, p, o, ctxId, 'remove')) try: self.reverseOps.remove((s, p, o, ctxId, 'add')) @@ -88,7 +88,7 @@ class AuditableStore(Store): self.reverseOps.append((s, p, o, ctx.identifier, 'add')) else: if not list(self.triples((subject, predicate, object_), context)): - return # triple not present in store, do nothing + return # triple not present in store, do nothing try: self.reverseOps.remove((subject, predicate, object_, ctxId, 'remove')) except ValueError: diff --git a/rdflib/plugins/stores/regexmatching.py b/rdflib/plugins/stores/regexmatching.py index a3e188f8..773dfab3 100644 --- a/rdflib/plugins/stores/regexmatching.py +++ b/rdflib/plugins/stores/regexmatching.py @@ -27,6 +27,7 @@ class REGEXTerm(text_type): perform a REGEX match (not a string comparison) using the value (pre-compiled) for checking rdf:type matches """ + def __init__(self, expr): self.compiledExpr = re.compile(expr) @@ -69,15 +70,15 @@ class REGEXMatching(Store): if isinstance(subject, REGEXTerm) or \ isinstance(predicate, REGEXTerm) or \ isinstance(object_, REGEXTerm) or \ - (context is not None - and isinstance(context.identifier, REGEXTerm)): + (context is not None and + isinstance(context.identifier, REGEXTerm)): # One or more of the terms is a REGEX expression, so we must # replace it / them with wildcard(s)and match after we query. s = not isinstance(subject, REGEXTerm) and subject or None p = not isinstance(predicate, REGEXTerm) and predicate or None o = not isinstance(object_, REGEXTerm) and object_ or None - c = (context is not None - and not isinstance(context.identifier, REGEXTerm)) \ + c = (context is not None and + not isinstance(context.identifier, REGEXTerm)) \ and context \ or None @@ -100,15 +101,15 @@ class REGEXMatching(Store): if isinstance(subject, REGEXTerm) or \ isinstance(predicate, REGEXTerm) or \ isinstance(object_, REGEXTerm) or \ - (context is not None - and isinstance(context.identifier, REGEXTerm)): + (context is not None and + isinstance(context.identifier, REGEXTerm)): # One or more of the terms is a REGEX expression, so we must # replace it / them with wildcard(s) and match after we query. s = not isinstance(subject, REGEXTerm) and subject or None p = not isinstance(predicate, REGEXTerm) and predicate or None o = not isinstance(object_, REGEXTerm) and object_ or None - c = (context is not None - and not isinstance(context.identifier, REGEXTerm)) \ + c = (context is not None and + not isinstance(context.identifier, REGEXTerm)) \ and context \ or None for (s1, p1, o1), cg in self.storage.triples((s, p, o), c): diff --git a/rdflib/plugins/stores/sparqlstore.py b/rdflib/plugins/stores/sparqlstore.py index 124f505a..42e8d2a2 100644 --- a/rdflib/plugins/stores/sparqlstore.py +++ b/rdflib/plugins/stores/sparqlstore.py @@ -27,6 +27,7 @@ from six import string_types BNODE_IDENT_PATTERN = re.compile('(?P<label>_\:[^\s]+)') + def _node_to_sparql(node): if isinstance(node, BNode): raise Exception( @@ -222,7 +223,7 @@ class SPARQLStore(SPARQLWrapper, Store): if vars: v = ' '.join([term.n3() for term in vars]) - verb = 'SELECT %s '%v + verb = 'SELECT %s ' % v else: verb = 'ASK' @@ -253,7 +254,6 @@ class SPARQLStore(SPARQLWrapper, Store): except (ValueError, TypeError, AttributeError): pass - result = self._query(query, default_graph=context.identifier if self._is_contextual(context) else None) @@ -261,10 +261,10 @@ class SPARQLStore(SPARQLWrapper, Store): for row in result: yield (row.get(s, s), row.get(p, p), - row.get(o, o)), None # why is the context here not the passed in graph 'context'? + row.get(o, o)), None # why is the context here not the passed in graph 'context'? else: if result.askAnswer: - yield (s,p,o), None + yield (s, p, o), None def triples_choices(self, _, context=None): """ @@ -316,7 +316,7 @@ class SPARQLStore(SPARQLWrapper, Store): result = self._query(q) - return ( row.name for row in result ) + return (row.name for row in result) # Namespace persistence interface implementation def bind(self, prefix, namespace): @@ -400,7 +400,8 @@ class SPARQLUpdateStore(SPARQLStore): STRING_LITERAL2 = u'"([^"\\\\]|\\\\.)*"' STRING_LITERAL_LONG1 = u"'''(('|'')?([^'\\\\]|\\\\.))*'''" STRING_LITERAL_LONG2 = u'"""(("|"")?([^"\\\\]|\\\\.))*"""' - String = u'(%s)|(%s)|(%s)|(%s)' % (STRING_LITERAL1, STRING_LITERAL2, STRING_LITERAL_LONG1, STRING_LITERAL_LONG2) + String = u'(%s)|(%s)|(%s)|(%s)' % (STRING_LITERAL1, STRING_LITERAL2, + STRING_LITERAL_LONG1, STRING_LITERAL_LONG2) IRIREF = u'<([^<>"{}|^`\\]\\\\\[\\x00-\\x20])*>' COMMENT = u'#[^\\x0D\\x0A]*([\\x0D\\x0A]|\\Z)' @@ -420,7 +421,6 @@ class SPARQLUpdateStore(SPARQLStore): ################################################################## - def __init__(self, queryEndpoint=None, update_endpoint=None, sparql11=True, @@ -455,7 +455,6 @@ class SPARQLUpdateStore(SPARQLStore): self._edits = None self._updates = 0 - def query(self, *args, **kwargs): if not self.autocommit and not self.dirty_reads: self.commit() @@ -543,7 +542,7 @@ class SPARQLUpdateStore(SPARQLStore): contexts = collections.defaultdict(list) for subject, predicate, obj, context in quads: - contexts[context].append((subject,predicate,obj)) + contexts[context].append((subject, predicate, obj)) data = [] nts = self.node_to_sparql for context in contexts: @@ -591,8 +590,6 @@ class SPARQLUpdateStore(SPARQLStore): SPARQLWrapper.update(self, update) - - def update(self, query, initNs={}, initBindings={}, @@ -721,7 +718,8 @@ class SPARQLUpdateStore(SPARQLStore): def close(self, commit_pending_transaction=False): - if commit_pending_transaction: self.commit() + if commit_pending_transaction: + self.commit() super(SPARQLStore, self).close() diff --git a/rdflib/plugins/stores/sparqlwrapper.py b/rdflib/plugins/stores/sparqlwrapper.py index 5504307e..c3fbb946 100644 --- a/rdflib/plugins/stores/sparqlwrapper.py +++ b/rdflib/plugins/stores/sparqlwrapper.py @@ -10,12 +10,16 @@ from rdflib.query import Result log = logging.getLogger(__name__) -class SPARQLWrapperException(Exception): pass + +class SPARQLWrapperException(Exception): + pass + _response_mime_types = { 'xml': 'application/sparql-results+xml, application/rdf+xml', } + class SPARQLWrapper(object): """ @@ -23,7 +27,6 @@ class SPARQLWrapper(object): """ def __init__(self, query_endpoint=None, update_endpoint=None, returnFormat='xml', method='GET', **kwargs): - """ Any additional keyword arguments will be passed to requests, and can be used to setup timesouts, basic auth, etc. """ @@ -39,10 +42,9 @@ class SPARQLWrapper(object): self._session = threading.local() - @property def session(self): - k = 'session_%d'%os.getpid() + k = 'session_%d' % os.getpid() self._session.__dict__.setdefault(k, requests.Session()) log.debug('Session %s %s', os.getpid(), id(self._session.__dict__[k])) return self._session.__dict__[k] @@ -58,16 +60,16 @@ class SPARQLWrapper(object): self._method = method - def query(self, query, default_graph=None): if not self.query_endpoint: raise SPARQLWrapperException("Query endpoint not set!") - params = { 'query': query } - if default_graph: params["default-graph-uri"] = default_graph + params = {'query': query} + if default_graph: + params["default-graph-uri"] = default_graph - headers = { 'Accept': _response_mime_types[self.returnFormat] } + headers = {'Accept': _response_mime_types[self.returnFormat]} args = dict(self.kwargs) args.update(url=self.query_endpoint) @@ -83,7 +85,7 @@ class SPARQLWrapper(object): elif self.method == 'POST': args['data'] = params else: - raise SPARQLWrapperException("Unknown method %s"%self.method) + raise SPARQLWrapperException("Unknown method %s" % self.method) res = self.session.request(self.method, **args) @@ -95,11 +97,12 @@ class SPARQLWrapper(object): if not self.update_endpoint: raise SPARQLWrapperException("Query endpoint not set!") - params = { } + params = {} - if default_graph: params["using-graph-uri"] = default_graph + if default_graph: + params["using-graph-uri"] = default_graph - headers = { 'Accept': _response_mime_types[self.returnFormat] } + headers = {'Accept': _response_mime_types[self.returnFormat]} args = dict(self.kwargs) @@ -114,9 +117,7 @@ class SPARQLWrapper(object): res = self.session.post(**args) - res.raise_for_status() - def close(self): self.session.close() diff --git a/rdflib/query.py b/rdflib/query.py index 929fa338..1b1803dc 100644 --- a/rdflib/query.py +++ b/rdflib/query.py @@ -18,8 +18,6 @@ __all__ = ['Processor', 'Result', 'ResultParser', 'ResultSerializer', 'ResultException'] - - class Processor(object): """ Query plugin interface. @@ -36,6 +34,7 @@ class Processor(object): def query(self, strOrQuery, initBindings={}, initNs={}, DEBUG=False): pass + class UpdateProcessor(object): """ Update plugin interface. @@ -51,9 +50,11 @@ class UpdateProcessor(object): def __init__(self, graph): pass + def update(self, strOrQuery, initBindings={}, initNs={}): pass + class ResultException(Exception): pass @@ -166,6 +167,7 @@ class Result(object): len(result) also works. """ + def __init__(self, type_): if type_ not in ('CONSTRUCT', 'DESCRIBE', 'SELECT', 'ASK'): @@ -249,7 +251,7 @@ class Result(object): if self.type == 'ASK': return self.askAnswer else: - return len(self)>0 + return len(self) > 0 if PY2: __nonzero__ = __bool__ diff --git a/rdflib/resource.py b/rdflib/resource.py index 9985023b..7b43b394 100644 --- a/rdflib/resource.py +++ b/rdflib/resource.py @@ -341,7 +341,7 @@ class Resource(object): self._graph == other._graph and self._identifier == other._identifier) - __ne__ = lambda self, other: not self == other + def __ne__(self, other): return not self == other def __lt__(self, other): if isinstance(other, Resource): @@ -349,9 +349,11 @@ class Resource(object): else: return False - __gt__ = lambda self, other: not (self < other or self == other) - __le__ = lambda self, other: self < other or self == other - __ge__ = lambda self, other: not self < other + def __gt__(self, other): return not (self < other or self == other) + + def __le__(self, other): return self < other or self == other + + def __ge__(self, other): return not self < other def __unicode__(self): return text_type(self._identifier) @@ -439,7 +441,7 @@ class Resource(object): yield self._cast(s1), self._cast(s2) def _resource_triples(self, triples): - for s,p,o in triples: + for s, p, o in triples: yield self._cast(s), self._cast(p), self._cast(o) def _resources(self, nodes): @@ -459,9 +461,11 @@ class Resource(object): if isinstance(item, slice): if item.step: raise TypeError("Resources fix the subject for slicing, and can only be sliced by predicate/object. ") - p,o=item.start,item.stop - if isinstance(p, Resource): p = p._identifier - if isinstance(o, Resource): o = o._identifier + p, o = item.start, item.stop + if isinstance(p, Resource): + p = p._identifier + if isinstance(o, Resource): + o = o._identifier if p is None and o is None: return self.predicate_objects() elif p is None: diff --git a/rdflib/store.py b/rdflib/store.py index 3688c642..32c3f650 100644 --- a/rdflib/store.py +++ b/rdflib/store.py @@ -1,3 +1,10 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from six import BytesIO +from six.moves import cPickle +from rdflib.events import Dispatcher, Event """ ============ rdflib.store @@ -24,9 +31,6 @@ RDF operations performed on it. ------ """ -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function # Constants representing the state of a Store (returned by the open method) @@ -35,10 +39,7 @@ CORRUPTED_STORE = 0 NO_STORE = -1 UNKNOWN = None -from rdflib.events import Dispatcher, Event -from six.moves import cPickle -from six import BytesIO Pickler = cPickle.Pickler Unpickler = cPickle.Unpickler UnpicklingError = cPickle.UnpicklingError @@ -79,7 +80,6 @@ class TripleRemovedEvent(Event): """ - class NodePickler(object): def __init__(self): self._objects = {} @@ -117,7 +117,7 @@ class NodePickler(object): state.update({ '_ids': tuple(self._ids.items()), '_objects': tuple(self._objects.items()) - }) + }) return state def __setstate__(self, state): diff --git a/rdflib/term.py b/rdflib/term.py index 93851379..3665ff22 100644 --- a/rdflib/term.py +++ b/rdflib/term.py @@ -71,16 +71,21 @@ skolems = {} _invalid_uri_chars = '<>" {}|\\^`' + def _is_valid_uri(uri): for c in _invalid_uri_chars: - if c in uri: return False + if c in uri: + return False return True + _lang_tag_regex = compile('^[a-zA-Z]+(?:-[a-zA-Z0-9]+)*$') + def _is_valid_langtag(tag): return bool(_lang_tag_regex.match(tag)) + def _is_valid_unicode(value): """ Verify that the provided value can be converted into a Python @@ -100,6 +105,7 @@ def _is_valid_unicode(value): return False return True + class Node(object): """ A Node in the Graph. @@ -234,7 +240,7 @@ class URIRef(Identifier): def toPython(self): return text_type(self) - def n3(self, namespace_manager = None): + def n3(self, namespace_manager=None): """ This will do a limited check for valid URIs, essentially just making sure that the string includes no illegal @@ -286,8 +292,6 @@ class URIRef(Identifier): def __mod__(self, other): return self.__class__(text_type(self) % other) - - def de_skolemize(self): """ Create a Blank Node from a skolem URI, in accordance with http://www.w3.org/TR/rdf11-concepts/#section-skolemization. @@ -392,8 +396,8 @@ class BNode(Identifier): # as a nodeID for N3 ?? Unless we require these # constraints be enforced elsewhere? pass # assert is_ncname(text_type(value)), "BNode identifiers - # must be valid NCNames" _:[A-Za-z][A-Za-z0-9]* - # http://www.w3.org/TR/2004/REC-rdf-testcases-20040210/#nodeID + # must be valid NCNames" _:[A-Za-z][A-Za-z0-9]* + # http://www.w3.org/TR/2004/REC-rdf-testcases-20040210/#nodeID return Identifier.__new__(cls, value) def toPython(self): @@ -520,7 +524,6 @@ class Literal(Identifier): """ - if not PY3: __slots__ = ("language", "datatype", "value", "_language", "_datatype", "_value") @@ -540,7 +543,7 @@ class Literal(Identifier): "per http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal") if lang and not _is_valid_langtag(lang): - raise Exception("'%s' is not a valid language tag!"%lang) + raise Exception("'%s' is not a valid language tag!" % lang) if datatype: datatype = URIRef(datatype) @@ -560,12 +563,12 @@ class Literal(Identifier): elif isinstance(lexical_or_value, string_types): # passed a string # try parsing lexical form of datatyped literal - value = _castLexicalToPython(lexical_or_value, datatype) + value = _castLexicalToPython(lexical_or_value, datatype) - if value is not None and normalize: - _value, _datatype = _castPythonToLiteral(value) - if _value is not None and _is_valid_unicode(_value): - lexical_or_value = _value + if value is not None and normalize: + _value, _datatype = _castPythonToLiteral(value) + if _value is not None and _is_valid_unicode(_value): + lexical_or_value = _value else: # passed some python object @@ -591,7 +594,6 @@ class Literal(Identifier): inst._value = value return inst - def normalize(self): """ Returns a new literal with a normalised lexical representation @@ -634,7 +636,6 @@ class Literal(Identifier): self._language = d["language"] self._datatype = d["datatype"] - def __add__(self, val): """ >>> Literal(1) + 1 @@ -665,7 +666,6 @@ class Literal(Identifier): if PY2: __nonzero__ = __bool__ - def __neg__(self): """ >>> (- Literal(1)) @@ -688,7 +688,6 @@ class Literal(Identifier): else: raise TypeError("Not a number; %s" % repr(self)) - def __pos__(self): """ >>> (+ Literal(1)) @@ -709,7 +708,6 @@ class Literal(Identifier): else: raise TypeError("Not a number; %s" % repr(self)) - def __abs__(self): """ >>> abs(Literal(-1)) @@ -729,7 +727,6 @@ class Literal(Identifier): else: raise TypeError("Not a number; %s" % repr(self)) - def __invert__(self): """ >>> ~(Literal(-1)) @@ -793,7 +790,7 @@ class Literal(Identifier): if self.datatype in _NUMERIC_LITERAL_TYPES and \ other.datatype in _NUMERIC_LITERAL_TYPES: - return self.value>other.value + return self.value > other.value # plain-literals and xsd:string literals # are "the same" @@ -939,7 +936,6 @@ class Literal(Identifier): res ^= hash(self.datatype) return res - def __eq__(self, other): """ Literals are only equal to other literals. @@ -1090,8 +1086,7 @@ class Literal(Identifier): def neq(self, other): return not self.eq(other) - - def n3(self, namespace_manager = None): + def n3(self, namespace_manager=None): r''' Returns a representation in the N3 format. @@ -1145,12 +1140,10 @@ class Literal(Identifier): u'"1"^^xsd:integer' ''' if namespace_manager: - return self._literal_n3(qname_callback = - namespace_manager.normalizeUri) + return self._literal_n3(qname_callback=namespace_manager.normalizeUri) else: return self._literal_n3() - def _literal_n3(self, use_plain=False, qname_callback=None): ''' Using plain literal (shorthand) output:: @@ -1349,6 +1342,7 @@ def _writeXML(xmlnode): s = b('') return s + # Cannot import Namespace/XSD because of circular dependencies _XSD_PFX = 'http://www.w3.org/2001/XMLSchema#' _RDF_PFX = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#' @@ -1426,6 +1420,7 @@ _TOTAL_ORDER_CASTERS = { xml.dom.minidom.Document: lambda value: value.toxml(), } + def _castPythonToLiteral(obj): """ Casts a python datatype to a tuple of the lexical value and a @@ -1454,7 +1449,6 @@ from decimal import Decimal # python longs have no limit # both map to the abstract integer type, # rather than some concrete bit-limited datatype - _PythonToXSD = [ (string_types, (None, None)), (float, (None, _XSD_DOUBLE)), @@ -1476,7 +1470,7 @@ _PythonToXSD = [ ] XSDToPython = { - None : None, # plain literals map directly to value space + None: None, # plain literals map directly to value space URIRef(_XSD_PFX + 'time'): parse_time, URIRef(_XSD_PFX + 'date'): parse_date, URIRef(_XSD_PFX + 'gYear'): parse_date, @@ -1516,6 +1510,7 @@ _toPythonMapping = {} _toPythonMapping.update(XSDToPython) + def _castLexicalToPython(lexical, datatype): """ Map a lexical form to the value-space for the given datatype @@ -1538,6 +1533,7 @@ def _castLexicalToPython(lexical, datatype): # no convFunc - unknown data-type return None + def bind(datatype, pythontype, constructor=None, lexicalizer=None): """ register a new datatype<->pythontype binding @@ -1552,7 +1548,7 @@ def bind(datatype, pythontype, constructor=None, lexicalizer=None): """ if datatype in _toPythonMapping: logger.warning("datatype '%s' was already bound. Rebinding." % - datatype) + datatype) if constructor == None: constructor = pythontype @@ -1586,7 +1582,7 @@ class Variable(Identifier): def toPython(self): return "?%s" % self - def n3(self, namespace_manager = None): + def n3(self, namespace_manager=None): return "?%s" % self def __reduce__(self): @@ -1609,6 +1605,7 @@ class Statement(Node, tuple): def toPython(self): return (self[0], self[1]) + # Nodes are ordered like this # See http://www.w3.org/TR/sparql11-query/#modOrderBy # we leave "space" for more subclasses of Node elsewhere @@ -1619,7 +1616,7 @@ _ORDERING.update({ Variable: 20, URIRef: 30, Literal: 40 - }) +}) def _isEqualXMLNode(node, other): @@ -1651,8 +1648,8 @@ def _isEqualXMLNode(node, other): elif node.nodeType == Node.ELEMENT_NODE: # Get the basics right - if not (node.tagName == other.tagName - and node.namespaceURI == other.namespaceURI): + if not (node.tagName == other.tagName and + node.namespaceURI == other.namespaceURI): return False # Handle the (namespaced) attributes; the namespace setting key @@ -1697,6 +1694,7 @@ def _isEqualXMLNode(node, other): raise Exception( 'I dont know how to compare XML Node type: %s' % node.nodeType) + if __name__ == '__main__': import doctest doctest.testmod() diff --git a/rdflib/tools/csv2rdf.py b/rdflib/tools/csv2rdf.py index 8d5b06b2..a4e55c4e 100644 --- a/rdflib/tools/csv2rdf.py +++ b/rdflib/tools/csv2rdf.py @@ -27,7 +27,7 @@ from six import text_type from rdflib import RDF, RDFS from rdflib.namespace import split_uri -__all__ = [ 'CSV2RDF' ] +__all__ = ['CSV2RDF'] HELP = """ csv2rdf.py \ @@ -198,6 +198,7 @@ class NodeInt(NodeLiteral): def range(self): return rdflib.XSD.int + class NodeBool(NodeLiteral): def __call__(self, x): if not self.f: @@ -245,6 +246,7 @@ class NodeSplit(NodeMaker): return self.f.range() return NodeMaker.range(self) + default_node_make = NodeMaker() @@ -271,6 +273,7 @@ def _config_replace(a, b): def _config_int(f=None): return NodeInt(f) + def _config_bool(f=None): return NodeBool(f) @@ -282,6 +285,7 @@ def _config_date(format_): def _config_split(sep=None, f=None): return NodeSplit(sep, f) + config_functions = {"ignore": _config_ignore, "uri": _config_uri, "literal": _config_literal, @@ -406,13 +410,13 @@ class CSV2RDF(object): warnings.warn( "Could not process value for column " + "%d:%s in row %d, ignoring: %s " % ( - i, headers[i], rows, e.message)) + i, headers[i], rows, e.message)) rows += 1 if rows % 100000 == 0: sys.stderr.write( "%d rows, %d triples, elapsed %.2fs.\n" % ( - rows, self.triples, time.time() - start)) + rows, self.triples, time.time() - start)) except: sys.stderr.write("Error processing line: %d\n" % rows) raise diff --git a/rdflib/tools/graphisomorphism.py b/rdflib/tools/graphisomorphism.py index 9ecab86b..abc84fa1 100644 --- a/rdflib/tools/graphisomorphism.py +++ b/rdflib/tools/graphisomorphism.py @@ -9,12 +9,14 @@ from rdflib import Graph from rdflib import BNode from itertools import combinations + class IsomorphicTestableGraph(Graph): """ Ported from: http://www.w3.org/2001/sw/DataAccess/proto-tests/tools/rdfdiff.py (Sean B Palmer's RDF Graph Isomorphism Tester) """ + def __init__(self, **kargs): super(IsomorphicTestableGraph, self).__init__(**kargs) self.hash = None @@ -100,5 +102,6 @@ def main(): assert graph1 == graph2, "%s != %s" % ( graph2FName[graph1], graph2FName[graph2]) + if __name__ == '__main__': main() diff --git a/rdflib/tools/rdf2dot.py b/rdflib/tools/rdf2dot.py index 9c098786..84b251a1 100644 --- a/rdflib/tools/rdf2dot.py +++ b/rdflib/tools/rdf2dot.py @@ -130,5 +130,6 @@ language to stdout def main(): rdflib.extras.cmdlineutils.main(rdf2dot, _help) + if __name__ == '__main__': main() diff --git a/rdflib/tools/rdfpipe.py b/rdflib/tools/rdfpipe.py index 568e52e0..7bd63fc9 100644 --- a/rdflib/tools/rdfpipe.py +++ b/rdflib/tools/rdfpipe.py @@ -99,8 +99,8 @@ def make_option_parser(): "%prog [-h] [-i INPUT_FORMAT] [-o OUTPUT_FORMAT] " + "[--ns=PFX=NS ...] [-] [FILE ...]", description=__doc__.strip() + ( - " Reads file system paths, URLs or from stdin if '-' is given." - " The result is serialized to stdout."), + " Reads file system paths, URLs or from stdin if '-' is given." + " The result is serialized to stdout."), version="%prog " + "(using rdflib %s)" % rdflib.__version__) oparser.add_option( @@ -149,7 +149,8 @@ def make_option_parser(): return oparser -_get_plugin_names = lambda kind: ", ".join( + +def _get_plugin_names(kind): return ", ".join( p.name for p in plugin.plugins(kind=kind)) diff --git a/rdflib/tools/rdfs2dot.py b/rdflib/tools/rdfs2dot.py index 15857a6b..7135fe62 100644 --- a/rdflib/tools/rdfs2dot.py +++ b/rdflib/tools/rdfs2dot.py @@ -79,7 +79,7 @@ def rdfs2dot(g, stream, opts={}): l = "literal" fields[node(a)].add((label(x, g), l)) else: - # if a in nodes and b in nodes: + # if a in nodes and b in nodes: stream.write( "\t%s -> %s [ color=%s, label=\"%s\" ];\n" % ( node(a), node(b), EDGECOLOR, label(x, g))) @@ -110,5 +110,6 @@ DOT language to stdout def main(): rdflib.extras.cmdlineutils.main(rdfs2dot, _help) + if __name__ == '__main__': main() diff --git a/rdflib/util.py b/rdflib/util.py index 7d97942b..f0c6207d 100644 --- a/rdflib/util.py +++ b/rdflib/util.py @@ -340,9 +340,6 @@ def parse_date_time(val): return t - - - SUFFIX_FORMAT_MAP = { 'rdf': 'xml', 'rdfs': 'xml', @@ -484,12 +481,11 @@ def get_tree(graph, return (mapper(root), sorted(tree, key=sortkey)) - - def test(): import doctest doctest.testmod() + if __name__ == "__main__": # try to make the tests work outside of the time zone they were written in # import os, time diff --git a/rdflib/void.py b/rdflib/void.py index 8a23f569..db9bcc32 100644 --- a/rdflib/void.py +++ b/rdflib/void.py @@ -96,7 +96,7 @@ def generateVoID(g, dataset=None, res=None, distinctForPartitions=True): res.add( (part, VOID.properties, Literal(len(classProps[c])))) res.add((part, VOID.distinctObjects, - Literal(len(classObjects[c])))) + Literal(len(classObjects[c])))) for i, p in enumerate(properties): part = URIRef(dataset + "_property%d" % i) @@ -122,8 +122,8 @@ def generateVoID(g, dataset=None, res=None, distinctForPartitions=True): res.add((part, VOID.classes, Literal(len(propClasses)))) res.add((part, VOID.distinctSubjects, - Literal(len(propSubjects[p])))) + Literal(len(propSubjects[p])))) res.add((part, VOID.distinctObjects, - Literal(len(propObjects[p])))) + Literal(len(propObjects[p])))) return res, dataset diff --git a/test/earl.py b/test/earl.py index 50971f67..9e4d0413 100644 --- a/test/earl.py +++ b/test/earl.py @@ -28,6 +28,7 @@ report.add((rdflib, RDF.type, DOAP.Project)) now = Literal(datetime.now()) + @nottest def add_test(test, res, info=None): a = BNode() diff --git a/test/manifest.py b/test/manifest.py index 4f91dd6d..2c95e4d7 100644 --- a/test/manifest.py +++ b/test/manifest.py @@ -14,7 +14,8 @@ RDFT = Namespace('http://www.w3.org/ns/rdftest#') DAWG = Namespace('http://www.w3.org/2001/sw/DataAccess/tests/test-dawg#') RDFTest = namedtuple('RDFTest', ['uri', 'name', 'comment', 'data', - 'graphdata', 'action', 'result', 'syntax']) + 'graphdata', 'action', 'result', 'syntax']) + def read_manifest(f, base=None, legacy=False): @@ -63,7 +64,6 @@ def read_manifest(f, base=None, legacy=False): res = None syntax = True - if _type in (MF.QueryEvaluationTest, MF.CSVResultFormatTest): a = g.value(e, MF.action) query = g.value(a, QT.query) @@ -93,7 +93,7 @@ def read_manifest(f, base=None, legacy=False): syntax = _type == MF.PositiveSyntaxTest11 elif _type in (MF.PositiveUpdateSyntaxTest11, - MF.NegativeUpdateSyntaxTest11): + MF.NegativeUpdateSyntaxTest11): query = g.value(e, MF.action) syntax = _type == MF.PositiveUpdateSyntaxTest11 @@ -105,7 +105,7 @@ def read_manifest(f, base=None, legacy=False): RDFT.TestNTriplesNegativeSyntax, RDFT.TestTurtlePositiveSyntax, RDFT.TestTurtleNegativeSyntax, - ): + ): query = g.value(e, MF.action) syntax = _type in (RDFT.TestNQuadsPositiveSyntax, RDFT.TestNTriplesPositiveSyntax, @@ -124,8 +124,9 @@ def read_manifest(f, base=None, legacy=False): continue yield _type, RDFTest(e, _str(name), _str(comment), - _str(data), graphdata, _str(query), - res, syntax) + _str(data), graphdata, _str(query), + res, syntax) + @nottest def nose_tests(testers, manifest, base=None, legacy=False): diff --git a/test/test_aggregate_graphs.py b/test/test_aggregate_graphs.py index a289d1a3..4dace1cc 100644 --- a/test/test_aggregate_graphs.py +++ b/test/test_aggregate_graphs.py @@ -8,7 +8,7 @@ from rdflib.graph import Graph from rdflib.graph import ReadOnlyGraphAggregate from rdflib.graph import ConjunctiveGraph -testGraph1N3=""" +testGraph1N3 = """ @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/> . @@ -18,7 +18,7 @@ testGraph1N3=""" """ -testGraph2N3=""" +testGraph2N3 = """ @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/> . @@ -28,7 +28,7 @@ testGraph2N3=""" :a :d :e. """ -testGraph3N3=""" +testGraph3N3 = """ @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix log: <http://www.w3.org/2000/10/swap/log#>. @@ -37,7 +37,7 @@ testGraph3N3=""" """ sparqlQ = \ -""" + """ PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT * FROM NAMED <http://example.com/graph1> @@ -48,50 +48,52 @@ FROM <http://www.w3.org/2000/01/rdf-schema#> WHERE {?sub ?pred rdfs:Class }""" sparqlQ2 =\ -""" + """ PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?class WHERE { GRAPH ?graph { ?member a ?class } }""" sparqlQ3 =\ -""" + """ PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX log: <http://www.w3.org/2000/10/swap/log#> SELECT ?n3Doc WHERE {?n3Doc a log:N3Document }""" + class GraphAggregates1(unittest.TestCase): def setUp(self): - memStore = plugin.get('IOMemory',Store)() + memStore = plugin.get('IOMemory', Store)() self.graph1 = Graph(memStore) self.graph2 = Graph(memStore) self.graph3 = Graph(memStore) - for n3Str,graph in [(testGraph1N3,self.graph1), - (testGraph2N3,self.graph2), - (testGraph3N3,self.graph3)]: - graph.parse(StringIO(n3Str),format='n3') + for n3Str, graph in [(testGraph1N3, self.graph1), + (testGraph2N3, self.graph2), + (testGraph3N3, self.graph3)]: + graph.parse(StringIO(n3Str), format='n3') - self.G = ReadOnlyGraphAggregate([self.graph1,self.graph2,self.graph3]) + self.G = ReadOnlyGraphAggregate([self.graph1, self.graph2, self.graph3]) def testAggregateRaw(self): - #Test triples - assert len(list(self.G.triples((None,RDF.type,None)))) == 4 - assert len(list(self.G.triples((URIRef("http://test/bar"),None,None)))) == 2 - assert len(list(self.G.triples((None,URIRef("http://test/d"),None)))) == 3 + # Test triples + assert len(list(self.G.triples((None, RDF.type, None)))) == 4 + assert len(list(self.G.triples((URIRef("http://test/bar"), None, None)))) == 2 + assert len(list(self.G.triples((None, URIRef("http://test/d"), None)))) == 3 - #Test __len__ + # Test __len__ assert len(self.G) == 8 - #assert context iteration + # assert context iteration for g in self.G.contexts(): - assert isinstance(g,Graph) + assert isinstance(g, Graph) + + # Test __contains__ + assert (URIRef("http://test/foo"), RDF.type, RDFS.Resource) in self.G - #Test __contains__ - assert (URIRef("http://test/foo"),RDF.type,RDFS.Resource) in self.G + barPredicates = [URIRef("http://test/d"), RDFS.isDefinedBy] + assert len(list(self.G.triples_choices((URIRef("http://test/bar"), barPredicates, None)))) == 2 - barPredicates = [URIRef("http://test/d"),RDFS.isDefinedBy] - assert len(list(self.G.triples_choices((URIRef("http://test/bar"),barPredicates,None)))) == 2 class GraphAggregates2(unittest.TestCase): @@ -99,19 +101,20 @@ class GraphAggregates2(unittest.TestCase): sparql = True def setUp(self): - memStore = plugin.get('IOMemory',Store)() - self.graph1 = Graph(memStore,URIRef("http://example.com/graph1")) - self.graph2 = Graph(memStore,URIRef("http://example.com/graph2")) - self.graph3 = Graph(memStore,URIRef("http://example.com/graph3")) + memStore = plugin.get('IOMemory', Store)() + self.graph1 = Graph(memStore, URIRef("http://example.com/graph1")) + self.graph2 = Graph(memStore, URIRef("http://example.com/graph2")) + self.graph3 = Graph(memStore, URIRef("http://example.com/graph3")) - for n3Str,graph in [(testGraph1N3,self.graph1), - (testGraph2N3,self.graph2), - (testGraph3N3,self.graph3)]: - graph.parse(StringIO(n3Str),format='n3') + for n3Str, graph in [(testGraph1N3, self.graph1), + (testGraph2N3, self.graph2), + (testGraph3N3, self.graph3)]: + graph.parse(StringIO(n3Str), format='n3') - self.graph4 = Graph(memStore,RDFS) + self.graph4 = Graph(memStore, RDFS) self.graph4.parse(RDFS.uri) self.G = ConjunctiveGraph(memStore) + if __name__ == '__main__': unittest.main() diff --git a/test/test_auditable.py b/test/test_auditable.py index d6bdc0e6..63c7c5e5 100644 --- a/test/test_auditable.py +++ b/test/test_auditable.py @@ -303,4 +303,3 @@ class TestAuditableStoreEmbeded(BaseTestAuditableStore): (EX.s0, EX.p0, EX.o0), (EX.s0, EX.p0, EX.o0bis), ]) - diff --git a/test/test_bnode_ncname.py b/test/test_bnode_ncname.py index f3421b5c..78d96567 100644 --- a/test/test_bnode_ncname.py +++ b/test/test_bnode_ncname.py @@ -24,18 +24,20 @@ except ImportError: # Have doubts about this. random.seed will just hash the string random.seed('%s%s%s' % (preseed, os.getpid(), time.time())) del preseed - t = int( time.time() * 1000.0 ) - r = int( random.random()*100000000000000000 ) + t = int(time.time() * 1000.0) + r = int(random.random() * 100000000000000000) try: - a = socket.gethostbyname( socket.gethostname() ) + a = socket.gethostbyname(socket.gethostname()) except: # if we can't get a network address, just imagine one - a = random.random()*100000000000000000 - strdata = str(t)+' '+str(r)+' '+str(a) + a = random.random() * 100000000000000000 + strdata = str(t) + ' ' + str(r) + ' ' + str(a) data = md5(strdata.encode('ascii')).hexdigest() yield data # Adapted from http://icodesnip.com/snippet/python/simple-universally-unique-id-uuid-or-guid + + def bnode_uuid(): yield uuid4() @@ -76,6 +78,7 @@ def is_ncname(value): else: return False + if __name__ == '__main__': import doctest doctest.testmod() diff --git a/test/test_canonicalization.py b/test/test_canonicalization.py index 9b094ce6..3ed8ce96 100644 --- a/test/test_canonicalization.py +++ b/test/test_canonicalization.py @@ -8,49 +8,51 @@ from rdflib.plugins.memory import IOMemory from six import text_type from io import StringIO + def get_digest_value(rdf, mimetype): graph = Graph() - graph.load(StringIO(rdf),format=mimetype) + graph.load(StringIO(rdf), format=mimetype) stats = {} ig = to_isomorphic(graph) result = ig.graph_digest(stats) print(stats) return result + def negative_graph_match_test(): '''Test of FRIR identifiers against tricky RDF graphs with blank nodes.''' testInputs = [ - [ text_type('''@prefix : <http://example.org/ns#> . + [text_type('''@prefix : <http://example.org/ns#> . <http://example.org> :rel [ :label "Same" ]. '''), - text_type('''@prefix : <http://example.org/ns#> . + text_type('''@prefix : <http://example.org/ns#> . <http://example.org> :rel [ :label "Same" ], [ :label "Same" ]. '''), - False - ], - [ text_type('''@prefix : <http://example.org/ns#> . + False + ], + [text_type('''@prefix : <http://example.org/ns#> . <http://example.org> :rel <http://example.org/a>. '''), - text_type('''@prefix : <http://example.org/ns#> . + text_type('''@prefix : <http://example.org/ns#> . <http://example.org> :rel <http://example.org/a>, <http://example.org/a>. '''), - True - ], - [ text_type('''@prefix : <http://example.org/ns#> . + True + ], + [text_type('''@prefix : <http://example.org/ns#> . :linear_two_step_symmetry_start :related [ :related [ :related :linear_two_step_symmatry_end]], [ :related [ :related :linear_two_step_symmatry_end]].'''), - text_type('''@prefix : <http://example.org/ns#> . + text_type('''@prefix : <http://example.org/ns#> . :linear_two_step_symmetry_start :related [ :related [ :related :linear_two_step_symmatry_end]], [ :related [ :related :linear_two_step_symmatry_end]].'''), - True - ], - [ text_type('''@prefix : <http://example.org/ns#> . + True + ], + [text_type('''@prefix : <http://example.org/ns#> . _:a :rel [ :rel [ :rel [ @@ -60,7 +62,7 @@ def negative_graph_match_test(): ]; ]; ].'''), - text_type('''@prefix : <http://example.org/ns#> . + text_type('''@prefix : <http://example.org/ns#> . _:a :rel [ :rel [ :rel [ @@ -72,10 +74,10 @@ def negative_graph_match_test(): ]; ]; ].'''), - False - ], - # This test fails because the algorithm purposefully breaks the symmetry of symetric - [ text_type('''@prefix : <http://example.org/ns#> . + False + ], + # This test fails because the algorithm purposefully breaks the symmetry of symetric + [text_type('''@prefix : <http://example.org/ns#> . _:a :rel [ :rel [ :rel [ @@ -85,7 +87,7 @@ def negative_graph_match_test(): ]; ]; ].'''), - text_type('''@prefix : <http://example.org/ns#> . + text_type('''@prefix : <http://example.org/ns#> . _:a :rel [ :rel [ :rel [ @@ -95,9 +97,9 @@ def negative_graph_match_test(): ]; ]; ].'''), - True - ], - [ text_type('''@prefix : <http://example.org/ns#> . + True + ], + [text_type('''@prefix : <http://example.org/ns#> . _:a :rel [ :rel [ :label "foo"; @@ -108,7 +110,7 @@ def negative_graph_match_test(): ]; ]; ].'''), - text_type('''@prefix : <http://example.org/ns#> . + text_type('''@prefix : <http://example.org/ns#> . _:a :rel [ :rel [ :rel [ @@ -118,9 +120,9 @@ def negative_graph_match_test(): ]; ]; ].'''), - False - ], - [ text_type('''@prefix : <http://example.org/ns#> . + False + ], + [text_type('''@prefix : <http://example.org/ns#> . _:0001 :rel _:0003, _:0004. _:0002 :rel _:0005, _:0006. _:0003 :rel _:0001, _:0007, _:0010. @@ -132,7 +134,7 @@ def negative_graph_match_test(): _:0009 :rel _:0004, _:0005, _:0007. _:0010 :rel _:0003, _:0006, _:0008. '''), - text_type('''@prefix : <http://example.org/ns#> . + text_type('''@prefix : <http://example.org/ns#> . _:0001 :rel _:0003, _:0004. _:0002 :rel _:0005, _:0006. _:0003 :rel _:0001, _:0007, _:0010. @@ -144,12 +146,13 @@ def negative_graph_match_test(): _:0006 :rel _:0002, _:0008, _:0010. _:0007 :rel _:0003, _:0005, _:0009. '''), - True - ], + True + ], ] + def fn(rdf1, rdf2, identical): - digest1 = get_digest_value(rdf1,"text/turtle") - digest2 = get_digest_value(rdf2,"text/turtle") + digest1 = get_digest_value(rdf1, "text/turtle") + digest2 = get_digest_value(rdf2, "text/turtle") print(rdf1) print(digest1) print(rdf2) @@ -158,6 +161,7 @@ def negative_graph_match_test(): for inputs in testInputs: yield fn, inputs[0], inputs[1], inputs[2] + def test_issue494_collapsing_bnodes(): """Test for https://github.com/RDFLib/rdflib/issues/494 collapsing BNodes""" g = Graph() @@ -281,13 +285,13 @@ def test_issue682_signing_named_graphs(): mary = BNode() john = URIRef("http://love.com/lovers/john#") - cmary=URIRef("http://love.com/lovers/mary#") - cjohn=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) + g.bind("love", ns) gmary = Graph(store=store, identifier=cmary) @@ -441,7 +445,7 @@ def test_issue725_collapsing_bnodes_2(): assert len(g.all_nodes()) == len(cg.all_nodes()), \ 'canonicalization changed number of nodes in graph' assert len(list(g.subjects(RDF['type'], RDF['Statement']))) == \ - len(list(cg.subjects(RDF['type'], RDF['Statement']))), \ + len(list(cg.subjects(RDF['type'], RDF['Statement']))), \ 'canonicalization changed number of statements' # counter for subject, predicate and object nodes diff --git a/test/test_comparison.py b/test/test_comparison.py index 316718f0..3c8e50d4 100644 --- a/test/test_comparison.py +++ b/test/test_comparison.py @@ -30,6 +30,8 @@ Ah... it's coming back to me... [6:38p] eikeon: I know many of the backends break if URIRef("foo")==Literal("foo") [6:39p] eikeon: And if we want "foo"==Literal("foo") --- then we really can't have URIRef("foo") also == "foo" """ + + class IdentifierEquality(unittest.TestCase): def setUp(self): @@ -40,25 +42,25 @@ class IdentifierEquality(unittest.TestCase): self.python_literal_2 = u"foo" def testA(self): - self.assertEqual(self.uriref==self.literal, False) + self.assertEqual(self.uriref == self.literal, False) def testB(self): - self.assertEqual(self.literal==self.uriref, False) + self.assertEqual(self.literal == self.uriref, False) def testC(self): - self.assertEqual(self.uriref==self.python_literal, False) + self.assertEqual(self.uriref == self.python_literal, False) def testD(self): - self.assertEqual(self.python_literal==self.uriref, False) + self.assertEqual(self.python_literal == self.uriref, False) def testE(self): - self.assertEqual(self.literal==self.python_literal, False) + self.assertEqual(self.literal == self.python_literal, False) - def testE2(self): + def testE2(self): self.assertTrue(self.literal.eq(self.python_literal), True) def testF(self): - self.assertEqual(self.python_literal==self.literal, False) + self.assertEqual(self.python_literal == self.literal, False) def testG(self): self.assertEqual("foo" in CORE_SYNTAX_TERMS, False) @@ -75,5 +77,3 @@ class IdentifierEquality(unittest.TestCase): if __name__ == "__main__": unittest.main() - - diff --git a/test/test_conjunctive_graph.py b/test/test_conjunctive_graph.py index 8bd7d2f8..5c686027 100644 --- a/test/test_conjunctive_graph.py +++ b/test/test_conjunctive_graph.py @@ -14,36 +14,38 @@ DATA = u""" PUBLIC_ID = u"http://example.org/record/1" -def test_bnode_publicid(): + +def test_bnode_publicid(): g = ConjunctiveGraph() b = BNode() data = '<d:d> <e:e> <f:f> .' - print ("Parsing %r into %r"%(data, b)) + print("Parsing %r into %r" % (data, b)) g.parse(data=data, format='turtle', publicID=b) - triples = list( g.get_context(b).triples((None,None,None)) ) + triples = list(g.get_context(b).triples((None, None, None))) if not triples: - raise Exception("No triples found in graph %r"%b) + raise Exception("No triples found in graph %r" % b) u = URIRef(b) - triples = list( g.get_context(u).triples((None,None,None)) ) + triples = list(g.get_context(u).triples((None, None, None))) if triples: - raise Exception("Bad: Found in graph %r: %r"%(u, triples)) + raise Exception("Bad: Found in graph %r: %r" % (u, triples)) -def test_quad_contexts(): +def test_quad_contexts(): g = ConjunctiveGraph() a = URIRef('urn:a') b = URIRef('urn:b') - g.get_context(a).add((a,a,a)) - g.addN([(b,b,b,b)]) + g.get_context(a).add((a, a, a)) + g.addN([(b, b, b, b)]) - assert set(g) == set([(a,a,a), (b,b,b)]) - for q in g.quads(): + assert set(g) == set([(a, a, a), (b, b, b)]) + for q in g.quads(): assert isinstance(q[3], Graph) + def test_graph_ids(): def check(kws): cg = ConjunctiveGraph() diff --git a/test/test_conneg.py b/test/test_conneg.py index d0777a00..91d15d34 100644 --- a/test/test_conneg.py +++ b/test/test_conneg.py @@ -12,7 +12,7 @@ by graph.parse """ -xmltestdoc="""<?xml version="1.0" encoding="UTF-8"?> +xmltestdoc = """<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns="http://example.org/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" @@ -23,12 +23,12 @@ xmltestdoc="""<?xml version="1.0" encoding="UTF-8"?> </rdf:RDF> """ -n3testdoc="""@prefix : <http://example.org/> . +n3testdoc = """@prefix : <http://example.org/> . :a :b :c . """ -nttestdoc="<http://example.org/a> <http://example.org/b> <http://example.org/c> .\n" +nttestdoc = "<http://example.org/a> <http://example.org/b> <http://example.org/c> .\n" class TestHTTPHandler(BaseHTTPRequestHandler): @@ -37,32 +37,33 @@ class TestHTTPHandler(BaseHTTPRequestHandler): self.send_response(200, "OK") # fun fun fun parsing accept header. - acs=self.headers["Accept"].split(",") - acq=[x.split(";") for x in acs if ";" in x] - acn=[(x,"q=1") for x in acs if ";" not in x] - acs=[(x[0], float(x[1].strip()[2:])) for x in acq+acn] - ac=sorted(acs, key=lambda x: x[1]) - ct=ac[-1] + acs = self.headers["Accept"].split(",") + acq = [x.split(";") for x in acs if ";" in x] + acn = [(x, "q=1") for x in acs if ";" not in x] + acs = [(x[0], float(x[1].strip()[2:])) for x in acq + acn] + ac = sorted(acs, key=lambda x: x[1]) + ct = ac[-1] if "application/rdf+xml" in ct: - rct="application/rdf+xml" - content=xmltestdoc + rct = "application/rdf+xml" + content = xmltestdoc elif "text/n3" in ct: - rct="text/n3" - content=n3testdoc + rct = "text/n3" + content = n3testdoc elif "text/plain" in ct: - rct="text/plain" - content=nttestdoc + rct = "text/plain" + content = nttestdoc - self.send_header("Content-type",rct) + self.send_header("Content-type", rct) self.end_headers() self.wfile.write(content.encode('utf-8')) def log_message(self, *args): pass + def runHttpServer(server_class=HTTPServer, - handler_class=TestHTTPHandler): + handler_class=TestHTTPHandler): """Start a server than can handle 3 requests :)""" server_address = ('localhost', 12345) httpd = server_class(server_address, handler_class) @@ -76,7 +77,7 @@ def testConNeg(): _thread.start_new_thread(runHttpServer, tuple()) # hang on a second while server starts time.sleep(1) - graph=Graph() + graph = Graph() graph.parse("http://localhost:12345/foo", format="xml") graph.parse("http://localhost:12345/foo", format="n3") graph.parse("http://localhost:12345/foo", format="nt") @@ -86,5 +87,5 @@ if __name__ == "__main__": import sys import nose - if len(sys.argv)==1: + if len(sys.argv) == 1: nose.main(defaultTest=sys.argv[0]) diff --git a/test/test_conventions.py b/test/test_conventions.py index 2bd858a2..268047d7 100644 --- a/test/test_conventions.py +++ b/test/test_conventions.py @@ -10,6 +10,7 @@ Test module naming conventions modules should all be lower-case initial """ + class A(unittest.TestCase): def module_names(self, path=None, names=None): @@ -22,7 +23,7 @@ class A(unittest.TestCase): names = set() # TODO: handle cases where len(path) is not 1 - assert len(path)==1, "We're assuming the path has exactly one item in it for now" + assert len(path) == 1, "We're assuming the path has exactly one item in it for now" path = path[0] for importer, name, ispkg in pkgutil.iter_modules([path]): @@ -31,13 +32,15 @@ class A(unittest.TestCase): names=names) names.union(result) else: - if name!=name.lower() and name not in skip_as_ignorably_private: + if name != name.lower() and name not in skip_as_ignorably_private: names.add(name) return names def test_module_names(self): names = self.module_names() - self.assertTrue(names==set(), "module names '%s' are not lower case" % names) + self.assertTrue( + names == set(), "module names '%s' are not lower case" % names) + if __name__ == "__main__": unittest.main() diff --git a/test/test_core_sparqlstore.py b/test/test_core_sparqlstore.py index 83bf2e94..26c7554d 100644 --- a/test/test_core_sparqlstore.py +++ b/test/test_core_sparqlstore.py @@ -20,5 +20,6 @@ class TestSPARQLStoreGraphCore(unittest.TestCase): def test(self): print("Done") + if __name__ == '__main__': unittest.main() diff --git a/test/test_dataset.py b/test/test_dataset.py index 50eb2805..51ba887a 100644 --- a/test/test_dataset.py +++ b/test/test_dataset.py @@ -77,10 +77,10 @@ class DatasetTestCase(unittest.TestCase): else: os.remove(self.tmppath) - def testGraphAware(self): - if not self.graph.store.graph_aware: return + if not self.graph.store.graph_aware: + return g = self.graph g1 = g.graph(self.c1) @@ -90,21 +90,21 @@ class DatasetTestCase(unittest.TestCase): if self.store != "SPARQLUpdateStore": # added graph exists self.assertEqual(set(x.identifier for x in self.graph.contexts()), - set([self.c1, DATASET_DEFAULT_GRAPH_ID])) + set([self.c1, DATASET_DEFAULT_GRAPH_ID])) # added graph is empty self.assertEqual(len(g1), 0) - g1.add( (self.tarek, self.likes, self.pizza) ) + g1.add((self.tarek, self.likes, self.pizza)) # added graph still exists self.assertEqual(set(x.identifier for x in self.graph.contexts()), - set([self.c1, DATASET_DEFAULT_GRAPH_ID])) + set([self.c1, DATASET_DEFAULT_GRAPH_ID])) # added graph contains one triple self.assertEqual(len(g1), 1) - g1.remove( (self.tarek, self.likes, self.pizza) ) + g1.remove((self.tarek, self.likes, self.pizza)) # added graph is empty self.assertEqual(len(g1), 0) @@ -114,25 +114,25 @@ class DatasetTestCase(unittest.TestCase): if self.store != "SPARQLUpdateStore": # graph still exists, although empty self.assertEqual(set(x.identifier for x in self.graph.contexts()), - set([self.c1, DATASET_DEFAULT_GRAPH_ID])) + set([self.c1, DATASET_DEFAULT_GRAPH_ID])) g.remove_graph(self.c1) # graph is gone self.assertEqual(set(x.identifier for x in self.graph.contexts()), - set([DATASET_DEFAULT_GRAPH_ID])) + set([DATASET_DEFAULT_GRAPH_ID])) def testDefaultGraph(self): # Something the default graph is read-only (e.g. TDB in union mode) if self.store == "SPARQLUpdateStore": - print("Please make sure updating the default graph " \ + print("Please make sure updating the default graph " "is supported by your SPARQL endpoint") - self.graph.add(( self.tarek, self.likes, self.pizza)) + self.graph.add((self.tarek, self.likes, self.pizza)) self.assertEqual(len(self.graph), 1) # only default exists self.assertEqual(set(x.identifier for x in self.graph.contexts()), - set([DATASET_DEFAULT_GRAPH_ID])) + set([DATASET_DEFAULT_GRAPH_ID])) # removing default graph removes triples but not actual graph self.graph.remove_graph(DATASET_DEFAULT_GRAPH_ID) @@ -140,12 +140,12 @@ class DatasetTestCase(unittest.TestCase): self.assertEqual(len(self.graph), 0) # default still exists self.assertEqual(set(x.identifier for x in self.graph.contexts()), - set([DATASET_DEFAULT_GRAPH_ID])) + set([DATASET_DEFAULT_GRAPH_ID])) def testNotUnion(self): # Union depends on the SPARQL endpoint configuration if self.store == "SPARQLUpdateStore": - print("Please make sure your SPARQL endpoint has not configured " \ + print("Please make sure your SPARQL endpoint has not configured " "its default graph as the union of the named graphs") g1 = self.graph.graph(self.c1) g1.add((self.tarek, self.likes, self.pizza)) diff --git a/test/test_datetime.py b/test/test_datetime.py index d4c5ab3d..c2cad4b6 100644 --- a/test/test_datetime.py +++ b/test/test_datetime.py @@ -45,10 +45,10 @@ class TestRelativeBase(unittest.TestCase): self.assertTrue(isinstance(l.toPython(), datetime)) self.assertEqual(datetime_isoformat(l.toPython(), - DATE_EXT_COMPLETE + 'T' + '%H:%M:%S.%f' + TZ_EXT), - dt) + DATE_EXT_COMPLETE + 'T' + '%H:%M:%S.%f' + TZ_EXT), + dt) self.assertEqual(l.toPython().isoformat(), - "2008-12-01T18:02:00.522630+00:00") + "2008-12-01T18:02:00.522630+00:00") def test_timezone_offset(self): dt = "2010-02-10T12:36:00+03:00" @@ -65,7 +65,7 @@ class TestRelativeBase(unittest.TestCase): utc_dt = l.toPython().astimezone(UTC) self.assertEqual(datetime_isoformat(utc_dt), - "2010-02-10T09:36:00Z") + "2010-02-10T09:36:00Z") def test_timezone_offset_millisecond(self): dt = "2011-01-16T19:39:18.239743+01:00" @@ -75,5 +75,6 @@ class TestRelativeBase(unittest.TestCase): self.assertTrue(isinstance(l.toPython(), datetime)) self.assertEqual(l.toPython().isoformat(), dt) + if __name__ == "__main__": unittest.main() diff --git a/test/test_dawg.py b/test/test_dawg.py index 3027f561..c6370e89 100644 --- a/test/test_dawg.py +++ b/test/test_dawg.py @@ -52,9 +52,9 @@ from nose import SkipTest from .manifest import nose_tests, MF, UP from .earl import report, add_test +def eq(a, b, msg): + return eq_(a, b, msg + ': (%r!=%r)' % (a, b)) -def eq(a,b,msg): - return eq_(a,b,msg+': (%r!=%r)'%(a,b)) def setFlags(): import rdflib @@ -67,6 +67,7 @@ def setFlags(): # we obviously need this rdflib.DAWG_LITERAL_COLLATION = True + def resetFlags(): import rdflib # Several tests rely on lexical form of literals being kept! @@ -97,7 +98,6 @@ DETAILEDASSERT = True # DETAILEDASSERT=False - NAME = None fails = Counter() @@ -126,10 +126,7 @@ def _fmt(f): return "turtle" - - def bindingsCompatible(a, b): - """ Are two binding-sets compatible. @@ -432,7 +429,7 @@ def query_test(t): elif res.type == 'ASK': eq(res.askAnswer, res2.askAnswer, "Ask answer does not match: %r != %r" % ( - res.askAnswer, res2.askAnswer)) + res.askAnswer, res2.askAnswer)) elif res.type in ('DESCRIBE', 'CONSTRUCT'): assert isomorphic( res.graph, res2.graph), 'graphs are not isomorphic!' @@ -523,11 +520,9 @@ def test_dawg(): for t in nose_tests(testers, "test/DAWG/rdflib/manifest.ttl"): yield t - resetFlags() - if __name__ == '__main__': import sys @@ -543,7 +538,6 @@ if __name__ == '__main__': for _type, t in test_dawg(): - if NAME and not str(t[0]).startswith(NAME): continue i += 1 diff --git a/test/test_diff.py b/test/test_diff.py index 73d274df..bf49dd9d 100644 --- a/test/test_diff.py +++ b/test/test_diff.py @@ -5,27 +5,26 @@ from rdflib.compare import graph_diff """Test for graph_diff - much more extensive testing would certainly be possible""" + class TestDiff(unittest.TestCase): """Unicode literals for graph_diff test (issue 151)""" - def testA(self): + def testA(self): """with bnode""" - g=rdflib.Graph() - g.add( (rdflib.BNode(), rdflib.URIRef("urn:p"), rdflib.Literal(u'\xe9') ) ) - - diff=graph_diff(g,g) + g = rdflib.Graph() + g.add((rdflib.BNode(), rdflib.URIRef("urn:p"), rdflib.Literal(u'\xe9'))) - def testB(self): + diff = graph_diff(g, g) + def testB(self): """Curiously, this one passes, even before the fix in issue 151""" - g=rdflib.Graph() - g.add( (rdflib.URIRef("urn:a"), rdflib.URIRef("urn:p"), rdflib.Literal(u'\xe9') ) ) + g = rdflib.Graph() + g.add((rdflib.URIRef("urn:a"), rdflib.URIRef("urn:p"), rdflib.Literal(u'\xe9'))) - diff=graph_diff(g,g) + diff = graph_diff(g, g) if __name__ == "__main__": unittest.main() - diff --git a/test/test_duration.py b/test/test_duration.py index 5be15105..07542a45 100644 --- a/test/test_duration.py +++ b/test/test_duration.py @@ -39,5 +39,6 @@ class TestDuration(unittest.TestCase): Literal("P2Y4M8DT10H12M14S", datatype=XSD.duration) ) + if __name__ == "__main__": unittest.main() diff --git a/test/test_empty_xml_base.py b/test/test_empty_xml_base.py index fdbf05d8..a2714ee7 100644 --- a/test/test_empty_xml_base.py +++ b/test/test_empty_xml_base.py @@ -36,27 +36,34 @@ test_data2 = """ </rdf:RDF>""" -baseUri = URIRef('http://example.com/') +baseUri = URIRef('http://example.com/') baseUri2 = URIRef('http://example.com/foo/bar') + class TestEmptyBase(unittest.TestCase): def setUp(self): self.graph = ConjunctiveGraph() - self.graph.parse(StringIO(test_data),publicID=baseUri) + self.graph.parse(StringIO(test_data), publicID=baseUri) def test_base_ref(self): - self.assertTrue(len(self.graph) == 1,"There should be at least one statement in the graph") - self.assertTrue((baseUri,RDF.type,FOAF.Document) in self.graph,"There should be a triple with %s as the subject" % baseUri) + self.assertTrue(len(self.graph) == 1, + "There should be at least one statement in the graph") + self.assertTrue((baseUri, RDF.type, FOAF.Document) in self.graph, + "There should be a triple with %s as the subject" % baseUri) + class TestRelativeBase(unittest.TestCase): def setUp(self): self.graph = ConjunctiveGraph() - self.graph.parse(StringIO(test_data2),publicID=baseUri2) + self.graph.parse(StringIO(test_data2), publicID=baseUri2) def test_base_ref(self): - self.assertTrue(len(self.graph) == 1,"There should be at least one statement in the graph") + self.assertTrue(len(self.graph) == 1, + "There should be at least one statement in the graph") resolvedBase = URIRef('http://example.com/baz') - self.assertTrue((resolvedBase,RDF.type,FOAF.Document) in self.graph,"There should be a triple with %s as the subject" % resolvedBase) + self.assertTrue((resolvedBase, RDF.type, FOAF.Document) in self.graph, + "There should be a triple with %s as the subject" % resolvedBase) + if __name__ == "__main__": unittest.main() diff --git a/test/test_events.py b/test/test_events.py index c64a0a8e..f7f706a9 100644 --- a/test/test_events.py +++ b/test/test_events.py @@ -2,27 +2,35 @@ import unittest from rdflib import events -class AddedEvent(events.Event): pass -class RemovedEvent(events.Event): pass +class AddedEvent(events.Event): + pass + + +class RemovedEvent(events.Event): + pass + def subscribe_to(source, target): target.subscribe(AddedEvent, source._add_handler) target.subscribe(RemovedEvent, source._remove_handler) + def subscribe_all(caches): for cache in caches: for other in caches: if other != cache: subscribe_to(cache, other) + class Cache(events.Dispatcher): def __init__(self, data=None): - if data is None: data = {} + if data is None: + data = {} self._data = data self.subscribe(AddedEvent, self._add_handler) - self.subscribe(RemovedEvent, self._remove_handler) + self.subscribe(RemovedEvent, self._remove_handler) def _add_handler(self, event): self._data[event.key] = event.value @@ -35,13 +43,13 @@ class Cache(events.Dispatcher): def __setitem__(self, key, value): self.dispatch(AddedEvent(key=key, value=value)) - + def __delitem__(self, key): self.dispatch(RemovedEvent(key=key)) def __contains__(self, key): return key in self._data - + has_key = __contains__ @@ -51,7 +59,7 @@ class EventTestCase(unittest.TestCase): c1 = Cache() c2 = Cache() c3 = Cache() - subscribe_all([c1,c2,c3]) + subscribe_all([c1, c2, c3]) c1['bob'] = 'uncle' assert c2['bob'] == 'uncle' assert c3['bob'] == 'uncle' @@ -59,5 +67,6 @@ class EventTestCase(unittest.TestCase): assert ('bob' in c1) == False assert ('bob' in c2) == False + if __name__ == "__main__": unittest.main() diff --git a/test/test_extras_external_graph_libs.py b/test/test_extras_external_graph_libs.py index 83286ca5..5ccd67bc 100644 --- a/test/test_extras_external_graph_libs.py +++ b/test/test_extras_external_graph_libs.py @@ -2,6 +2,7 @@ from nose import SkipTest from rdflib import Graph, URIRef, Literal from six import text_type + def test_rdflib_to_networkx(): try: import networkx @@ -17,7 +18,6 @@ def test_rdflib_to_networkx(): for t in edges: g.add(t) - mdg = rdflib_to_networkx_multidigraph(g) assert len(mdg.edges()) == 4 assert mdg.has_edge(a, b) @@ -28,7 +28,6 @@ def test_rdflib_to_networkx(): assert mdg.has_edge(a, b, key=0) assert mdg.has_edge(a, b, key=1) - dg = rdflib_to_networkx_digraph(g) assert dg[a][b]['weight'] == 2 assert sorted(dg[a][b]['triples']) == [(a, p, b), (a, q, b)] @@ -36,11 +35,10 @@ def test_rdflib_to_networkx(): assert dg.size() == 3 assert dg.size(weight='weight') == 4.0 - dg = rdflib_to_networkx_graph(g, False, edge_attrs=lambda s, p, o:{}) + dg = rdflib_to_networkx_graph(g, False, edge_attrs=lambda s, p, o: {}) assert 'weight' not in dg[a][b] assert 'triples' not in dg[a][b] - ug = rdflib_to_networkx_graph(g) assert ug[a][b]['weight'] == 3 assert sorted(ug[a][b]['triples']) == [(a, p, b), (a, q, b), (b, p, a)] @@ -48,7 +46,7 @@ def test_rdflib_to_networkx(): assert ug.size() == 2 assert ug.size(weight='weight') == 4.0 - ug = rdflib_to_networkx_graph(g, False, edge_attrs=lambda s, p, o:{}) + ug = rdflib_to_networkx_graph(g, False, edge_attrs=lambda s, p, o: {}) assert 'weight' not in ug[a][b] assert 'triples' not in ug[a][b] @@ -87,6 +85,7 @@ def test_rdflib_to_graphtool(): assert len(list(gt_util.find_edge(mdg, epterm, text_type(p)))) == 3 assert len(list(gt_util.find_edge(mdg, epterm, text_type(q)))) == 1 + if __name__ == "__main__": import sys import nose diff --git a/test/test_finalnewline.py b/test/test_finalnewline.py index 733b490c..956d6c0a 100644 --- a/test/test_finalnewline.py +++ b/test/test_finalnewline.py @@ -4,13 +4,14 @@ import rdflib.plugin from six import b + def testFinalNewline(): """ http://code.google.com/p/rdflib/issues/detail?id=5 """ import sys - graph=ConjunctiveGraph() + graph = ConjunctiveGraph() graph.add((URIRef("http://ex.org/a"), URIRef("http://ex.org/b"), URIRef("http://ex.org/c"))) @@ -19,13 +20,14 @@ def testFinalNewline(): for p in rdflib.plugin.plugins(None, rdflib.plugin.Serializer): v = graph.serialize(format=p.name) lines = v.split(b("\n")) - if b("\n") not in v or (lines[-1]!=b('')): + if b("\n") not in v or (lines[-1] != b('')): failed.add(p.name) - assert len(failed)==0, "No final newline for formats: '%s'" % failed + assert len(failed) == 0, "No final newline for formats: '%s'" % failed + if __name__ == "__main__": import sys import nose - if len(sys.argv)==1: + if len(sys.argv) == 1: nose.main(defaultTest=sys.argv[0]) diff --git a/test/test_graph_context.py b/test/test_graph_context.py index 50319600..cc5786dd 100644 --- a/test/test_graph_context.py +++ b/test/test_graph_context.py @@ -316,7 +316,7 @@ class ContextTestCase(unittest.TestCase): asserte(set(c.predicate_objects( michel)), set([(likes, cheese), (likes, pizza)])) asserte(set(c.predicate_objects(bob)), set([(likes, - cheese), (hates, pizza), (hates, michel)])) + cheese), (hates, pizza), (hates, michel)])) asserte(set(c.predicate_objects( tarek)), set([(likes, cheese), (likes, pizza)])) @@ -338,10 +338,7 @@ class ContextTestCase(unittest.TestCase): asserte(len(list(triples((Any, Any, Any)))), 0) - - # dynamically create classes for each registered Store - pluginname = None if __name__ == '__main__': if len(sys.argv) > 1: diff --git a/test/test_graph_formula.py b/test/test_graph_formula.py index 4857577c..412e7a77 100644 --- a/test/test_graph_formula.py +++ b/test/test_graph_formula.py @@ -1,3 +1,5 @@ +from nose.exc import SkipTest +from nose.tools import nottest import sys import os from tempfile import mkdtemp, mkstemp @@ -14,8 +16,6 @@ testN3 = """ _:foo a rdfs:Class. :a :d :c.""" -from nose.tools import nottest -from nose.exc import SkipTest # Thorough test suite for formula-aware store @@ -52,10 +52,10 @@ def testFormulaStore(store="default", configString=None): universe = ConjunctiveGraph(g.store) - #test formula as terms + # test formula as terms assert len(list(universe.triples((formulaA, implies, formulaB)))) == 1 - #test variable as term and variable roundtrip + # 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: @@ -92,7 +92,7 @@ def testFormulaStore(store="default", configString=None): # <Graph identifier=_:Formula16 (<class 'rdflib.graph.Graph'>)> # ] - #Remove test cases + # 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 @@ -105,7 +105,7 @@ def testFormulaStore(store="default", configString=None): universe.remove((None, RDF.type, RDFS.Class)) - #remove_context tests + # remove_context tests universe.remove_context(formulaB) assert len(list(universe.triples((None, RDF.type, None)))) == 0 assert len(universe) == 1 @@ -138,7 +138,7 @@ def testFormulaStores(): if s.name in ( 'Auditable', 'Concurrent', 'SPARQLStore', 'SPARQLUpdateStore', - ): + ): continue if not s.getClass().formula_aware: continue diff --git a/test/test_graph_items.py b/test/test_graph_items.py index c1e96c89..b6cb2529 100644 --- a/test/test_graph_items.py +++ b/test/test_graph_items.py @@ -1,7 +1,8 @@ from rdflib import Graph, RDF + def test_recursive_list_detection(): - g = Graph().parse(data=""" + g = Graph().parse(data=""" @prefix : <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . <> :value _:a . @@ -15,10 +16,10 @@ def test_recursive_list_detection(): """, format="turtle") - for v in g.objects(None, RDF.value): - try: - list(g.items(v)) - except ValueError as e: - pass - else: - assert False, "Expected detection of recursive rdf:rest reference" + for v in g.objects(None, RDF.value): + try: + list(g.items(v)) + except ValueError as e: + pass + else: + assert False, "Expected detection of recursive rdf:rest reference" diff --git a/test/test_initbindings.py b/test/test_initbindings.py index e44f9fff..efa94191 100644 --- a/test/test_initbindings.py +++ b/test/test_initbindings.py @@ -11,121 +11,141 @@ g = ConjunctiveGraph() def testStr(): a = set(g.query("SELECT (STR(?target) AS ?r) WHERE { }", initBindings={'target': URIRef('example:a')})) b = set(g.query("SELECT (STR(?target) AS ?r) WHERE { } VALUES (?target) {(<example:a>)}")) - assert a==b, "STR: %r != %r"%(a,b) + assert a == b, "STR: %r != %r" % (a, b) + def testIsIRI(): a = set(g.query("SELECT (isIRI(?target) AS ?r) WHERE { }", initBindings={'target': URIRef('example:a')})) b = set(g.query("SELECT (isIRI(?target) AS ?r) WHERE { } VALUES (?target) {(<example:a>)}")) - assert a==b, "isIRI: %r != %r"%(a,b) + assert a == b, "isIRI: %r != %r" % (a, b) + def testIsBlank(): a = set(g.query("SELECT (isBlank(?target) AS ?r) WHERE { }", initBindings={'target': URIRef('example:a')})) b = set(g.query("SELECT (isBlank(?target) AS ?r) WHERE { } VALUES (?target) {(<example:a>)}")) - assert a==b, "isBlank: %r != %r"%(a,b) + assert a == b, "isBlank: %r != %r" % (a, b) + def testIsLiteral(): a = set(g.query("SELECT (isLiteral(?target) AS ?r) WHERE { }", initBindings={'target': Literal('example')})) b = set(g.query("SELECT (isLiteral(?target) AS ?r) WHERE { } VALUES (?target) {('example')}")) - assert a==b, "isLiteral: %r != %r"%(a,b) + assert a == b, "isLiteral: %r != %r" % (a, b) + def testUCase(): a = set(g.query("SELECT (UCASE(?target) AS ?r) WHERE { }", initBindings={'target': Literal('example')})) b = set(g.query("SELECT (UCASE(?target) AS ?r) WHERE { } VALUES (?target) {('example')}")) - assert a==b, "UCASE: %r != %r"%(a,b) + assert a == b, "UCASE: %r != %r" % (a, b) + def testNoFunc(): a = set(g.query("SELECT ?target WHERE { }", initBindings={'target': Literal('example')})) b = set(g.query("SELECT ?target WHERE { } VALUES (?target) {('example')}")) - assert a==b, "no func: %r != %r"%(a,b) + assert a == b, "no func: %r != %r" % (a, b) + def testOrderBy(): a = set(g.query("SELECT ?target WHERE { } ORDER BY ?target", initBindings={'target': Literal('example')})) b = set(g.query("SELECT ?target WHERE { } ORDER BY ?target VALUES (?target) {('example')}")) - assert a==b, "orderby: %r != %r"%(a,b) + assert a == b, "orderby: %r != %r" % (a, b) + def testOrderByFunc(): a = set(g.query("SELECT (UCASE(?target) as ?r) WHERE { } ORDER BY ?target", initBindings={'target': Literal('example')})) b = set(g.query("SELECT (UCASE(?target) as ?r) WHERE { } ORDER BY ?target VALUES (?target) {('example')} ")) - assert a==b, "orderbyFunc: %r != %r"%(a,b) + assert a == b, "orderbyFunc: %r != %r" % (a, b) + def testNoFuncLimit(): a = set(g.query("SELECT ?target WHERE { } LIMIT 1", initBindings={'target': Literal('example')})) b = set(g.query("SELECT ?target WHERE { } LIMIT 1 VALUES (?target) {('example')}")) - assert a==b, "limit: %r != %r"%(a,b) + assert a == b, "limit: %r != %r" % (a, b) + def testOrderByLimit(): a = set(g.query("SELECT ?target WHERE { } ORDER BY ?target LIMIT 1", initBindings={'target': Literal('example')})) b = set(g.query("SELECT ?target WHERE { } ORDER BY ?target LIMIT 1 VALUES (?target) {('example')}")) - assert a==b, "orderbyLimit: %r != %r"%(a,b) + assert a == b, "orderbyLimit: %r != %r" % (a, b) + def testOrderByFuncLimit(): a = set(g.query("SELECT (UCASE(?target) as ?r) WHERE { } ORDER BY ?target LIMIT 1", initBindings={'target': Literal('example')})) b = set(g.query("SELECT (UCASE(?target) as ?r) WHERE { } ORDER BY ?target LIMIT 1 VALUES (?target) {('example')}")) - assert a==b, "orderbyFuncLimit: %r != %r"%(a,b) + assert a == b, "orderbyFuncLimit: %r != %r" % (a, b) + def testNoFuncOffset(): a = set(g.query("SELECT ?target WHERE { } OFFSET 1", initBindings={'target': Literal('example')})) b = set(g.query("SELECT ?target WHERE { } OFFSET 1 VALUES (?target) {('example')}")) - assert a==b, "offset: %r != %r"%(a,b) + assert a == b, "offset: %r != %r" % (a, b) + def testNoFuncLimitOffset(): a = set(g.query("SELECT ?target WHERE { } LIMIT 1 OFFSET 1", initBindings={'target': Literal('example')})) b = set(g.query("SELECT ?target WHERE { } LIMIT 1 OFFSET 1 VALUES (?target) {('example')}")) - assert a==b, "limitOffset: %r != %r"%(a,b) + assert a == b, "limitOffset: %r != %r" % (a, b) + def testOrderByLimitOffset(): a = set(g.query("SELECT ?target WHERE { } ORDER BY ?target LIMIT 1 OFFSET 1", initBindings={'target': Literal('example')})) b = set(g.query("SELECT ?target WHERE { } ORDER BY ?target LIMIT 1 OFFSET 1 VALUES (?target) {('example')}")) - assert a==b, "orderbyLimitOffset: %r != %r"%(a,b) + assert a == b, "orderbyLimitOffset: %r != %r" % (a, b) + def testOrderByFuncLimitOffset(): a = set(g.query("SELECT (UCASE(?target) as ?r) WHERE { } ORDER BY ?target LIMIT 1 OFFSET 1", initBindings={'target': Literal('example')})) b = set(g.query("SELECT (UCASE(?target) as ?r) WHERE { } ORDER BY ?target LIMIT 1 OFFSET 1 VALUES (?target) {('example')}")) - assert a==b, "orderbyFuncLimitOffset: %r != %r"%(a,b) + assert a == b, "orderbyFuncLimitOffset: %r != %r" % (a, b) + def testDistinct(): a = set(g.query("SELECT DISTINCT ?target WHERE { }", initBindings={'target': Literal('example')})) b = set(g.query("SELECT DISTINCT ?target WHERE { } VALUES (?target) {('example')}")) - assert a==b, "distinct: %r != %r"%(a,b) + assert a == b, "distinct: %r != %r" % (a, b) + def testDistinctOrderBy(): a = set(g.query("SELECT DISTINCT ?target WHERE { } ORDER BY ?target", initBindings={'target': Literal('example')})) b = set(g.query("SELECT DISTINCT ?target WHERE { } ORDER BY ?target VALUES (?target) {('example')}")) - assert a==b, "distinctOrderby: %r != %r"%(a,b) + assert a == b, "distinctOrderby: %r != %r" % (a, b) + def testDistinctOrderByLimit(): a = set(g.query("SELECT DISTINCT ?target WHERE { } ORDER BY ?target LIMIT 1", initBindings={'target': Literal('example')})) b = set(g.query("SELECT DISTINCT ?target WHERE { } ORDER BY ?target LIMIT 1 VALUES (?target) {('example')}")) - assert a==b, "distinctOrderbyLimit: %r != %r"%(a,b) + assert a == b, "distinctOrderbyLimit: %r != %r" % (a, b) + def testPrepare(): q = prepareQuery('SELECT ?target WHERE { }') r = list(g.query(q)) e = [] - assert r == e, 'prepare: %r != %r'%(r,e) + assert r == e, 'prepare: %r != %r' % (r, e) r = list(g.query(q, initBindings={'target': Literal('example')})) e = [(Literal('example'),)] - assert r == e, 'prepare: %r != %r'%(r, e) + assert r == e, 'prepare: %r != %r' % (r, e) r = list(g.query(q)) e = [] - assert r == e, 'prepare: %r != %r'%(r,e) + assert r == e, 'prepare: %r != %r' % (r, e) def testData(): data = ConjunctiveGraph() - data += [ ( URIRef('urn:a'), URIRef('urn:p'), Literal('a') ), - ( URIRef('urn:b'), URIRef('urn:p'), Literal('b') ) ] + data += [(URIRef('urn:a'), URIRef('urn:p'), Literal('a')), + (URIRef('urn:b'), URIRef('urn:p'), Literal('b'))] a = set(g.query("SELECT ?target WHERE { ?target <urn:p> ?val }", initBindings={'val': Literal('a')})) b = set(g.query("SELECT ?target WHERE { ?target <urn:p> ?val } VALUES (?val) {('a')}")) - assert a==b, "data: %r != %r"%(a,b) + + assert a == b, "data: %r != %r" % (a, b) + def testAsk(): a = set(g.query("ASK { }", initBindings={'target': Literal('example')})) b = set(g.query("ASK { } VALUES (?target) {('example')}")) - assert a==b, "ask: %r != %r"%(a,b) + assert a == b, "ask: %r != %r" % (a, b) EX = Namespace("http://example.com/") @@ -134,14 +154,17 @@ g2.bind('', EX) g2.add((EX['s1'], EX['p'], EX['o1'])) g2.add((EX['s2'], EX['p'], EX['o2'])) + def testStringKey(): results = list(g2.query("SELECT ?o WHERE { ?s :p ?o }", initBindings={"s": EX['s1']})) assert len(results) == 1, results + def testStringKeyWithQuestionMark(): results = list(g2.query("SELECT ?o WHERE { ?s :p ?o }", initBindings={"?s": EX['s1']})) assert len(results) == 1, results + def testVariableKey(): results = list(g2.query("SELECT ?o WHERE { ?s :p ?o }", initBindings={Variable("s"): EX['s1']})) assert len(results) == 1, results @@ -150,13 +173,15 @@ def testVariableKeyWithQuestionMark(): results = list(g2.query("SELECT ?o WHERE { ?s :p ?o }", initBindings={Variable("?s"): EX['s1']})) assert len(results) == 1, results + def testFilter(): results = list(g2.query("SELECT ?o WHERE { ?s :p ?o FILTER (?s = ?x)}", initBindings={Variable("?x"): EX['s1']})) assert len(results) == 1, results + if __name__ == "__main__": import sys import nose - if len(sys.argv)==1: + if len(sys.argv) == 1: nose.main(defaultTest=sys.argv[0]) diff --git a/test/test_iomemory.py b/test/test_iomemory.py index 78fd820b..897cc8b2 100644 --- a/test/test_iomemory.py +++ b/test/test_iomemory.py @@ -12,7 +12,8 @@ from rdflib import plugin from rdflib import Graph, Literal, Namespace -def test_concurrent1(): + +def test_concurrent1(): dns = Namespace(u"http://www.example.com/") store = plugin.get("IOMemory", Store)() @@ -26,7 +27,7 @@ def test_concurrent1(): i = 0 for t in g1.triples((None, None, None)): - i+=1 + i += 1 # next line causes problems because it adds a new Subject that needs # to be indexed in __subjectIndex dictionary in IOMemory Store. # which invalidates the iterator used to iterate over g1 @@ -34,7 +35,8 @@ def test_concurrent1(): assert i == n -def test_concurrent2(): + +def test_concurrent2(): dns = Namespace(u"http://www.example.com/") store = plugin.get("IOMemory", Store)() @@ -49,7 +51,7 @@ def test_concurrent2(): i = 0 for t in g1.triples((None, None, None)): - i+=1 + i += 1 g2.add(t) # next line causes problems because it adds a new Subject that needs # to be indexed in __subjectIndex dictionary in IOMemory Store. @@ -60,6 +62,7 @@ def test_concurrent2(): assert i == n + if __name__ == '__main__': test_concurrent1() test_concurrent2() diff --git a/test/test_issue084.py b/test/test_issue084.py index 8775fd0a..75da7615 100644 --- a/test/test_issue084.py +++ b/test/test_issue084.py @@ -25,47 +25,54 @@ rdf_utf8 = rdf.encode('utf-8') rdf_reader = getreader('utf-8')(BytesIO(rdf.encode('utf-8'))) - - def test_a(): """Test reading N3 from a unicode objects as data""" g = Graph() g.parse(data=rdf, format='n3') - v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) - assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + v = g.value(subject=URIRef("http://www.test.org/#CI"), + predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) + assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr') + def test_b(): """Test reading N3 from a utf8 encoded string as data""" g = Graph() g.parse(data=rdf_utf8, format='n3') - v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) - assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + v = g.value(subject=URIRef("http://www.test.org/#CI"), + predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) + assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr') + def test_c(): """Test reading N3 from a codecs.StreamReader, outputting unicode""" g = Graph() # rdf_reader.seek(0) g.parse(source=rdf_reader, format='n3') - v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) - assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + v = g.value(subject=URIRef("http://www.test.org/#CI"), + predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) + assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr') + def test_d(): """Test reading N3 from a StringIO over the unicode object""" g = Graph() g.parse(source=StringIO(rdf), format='n3') - v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) - assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + v = g.value(subject=URIRef("http://www.test.org/#CI"), + predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) + assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr') + def test_e(): """Test reading N3 from a BytesIO over the string object""" g = Graph() g.parse(source=BytesIO(rdf_utf8), format='n3') - v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) - assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + v = g.value(subject=URIRef("http://www.test.org/#CI"), + predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) + assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr') # this is unicode -rdfxml=u"""<?xml version="1.0" encoding="UTF-8"?> +rdfxml = u"""<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" @@ -88,15 +95,18 @@ def test_xml_a(): """Test reading XML from a unicode object as data""" g = Graph() g.parse(data=rdfxml, format='xml') - v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) - assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + v = g.value(subject=URIRef("http://www.test.org/#CI"), + predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) + assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr') + def test_xml_b(): """Test reading XML from a utf8 encoded string object as data""" g = Graph() g.parse(data=rdfxml_utf8, format='xml') - v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) - assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + v = g.value(subject=URIRef("http://www.test.org/#CI"), + predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) + assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr') # The following two cases are currently not supported by Graph.parse # def test_xml_c(): @@ -113,9 +123,11 @@ def test_xml_b(): # v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) # assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + def test_xml_e(): """Test reading XML from a BytesIO created from utf8 encoded string""" g = Graph() g.parse(source=BytesIO(rdfxml_utf8), format='xml') - v = g.value(subject=URIRef("http://www.test.org/#CI"), predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) - assert v==Literal(u"C\u00f4te d'Ivoire", lang='fr') + v = g.value(subject=URIRef("http://www.test.org/#CI"), + predicate=URIRef("http://www.w3.org/2004/02/skos/core#prefLabel")) + assert v == Literal(u"C\u00f4te d'Ivoire", lang='fr') diff --git a/test/test_issue160.py b/test/test_issue160.py index 304f1605..17ae18c5 100644 --- a/test/test_issue160.py +++ b/test/test_issue160.py @@ -41,6 +41,7 @@ target2xml = """\ <ns1:Item rdf:about="http://www.example.org/example/foo/a"/> </rdf:RDF>""" + class CollectionTest(TestCase): def test_collection_render(self): diff --git a/test/test_issue161.py b/test/test_issue161.py index 8448ecda..db8c2857 100644 --- a/test/test_issue161.py +++ b/test/test_issue161.py @@ -9,7 +9,7 @@ class EntityTest(TestCase): g = ConjunctiveGraph() n3 = \ - """ + """ @prefix _9: <http://data.linkedmdb.org/resource/movie/> . @prefix p_9: <urn:test:> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @@ -21,7 +21,6 @@ class EntityTest(TestCase): rdfs:label "Cecil B. DeMille (Director)"; _9:director_name "Cecil B. DeMille" .""" - g.parse(data=n3, format='n3') turtle = g.serialize(format="turtle") @@ -29,6 +28,6 @@ class EntityTest(TestCase): g = ConjunctiveGraph() g.parse(data=turtle, format='turtle') # Shouldn't have got to here - s=g.serialize(format="turtle") + s = g.serialize(format="turtle") self.assertTrue(b('@prefix _9') not in s) diff --git a/test/test_issue184.py b/test/test_issue184.py index f98f2f5c..b4fba8d3 100644 --- a/test/test_issue184.py +++ b/test/test_issue184.py @@ -2,6 +2,7 @@ from rdflib.term import Literal from rdflib.term import URIRef from rdflib.graph import ConjunctiveGraph + def test_escaping_of_triple_doublequotes(): """ Issue 186 - Check escaping of multiple doublequotes. @@ -10,9 +11,9 @@ def test_escaping_of_triple_doublequotes(): quotation marks in the lexical form of the Literal. In this case invalid N3 is emitted by the serializer, which in turn cannot be parsed correctly. """ - g=ConjunctiveGraph() + g = ConjunctiveGraph() g.add((URIRef('http://foobar'), URIRef('http://fooprop'), Literal('abc\ndef"""""'))) # assert g.serialize(format='n3') == '@prefix ns1: <http:// .\n\nns1:foobar ns1:fooprop """abc\ndef\\"\\"\\"\\"\\"""" .\n\n' - g2=ConjunctiveGraph() + g2 = ConjunctiveGraph() g2.parse(data=g.serialize(format='n3'), format='n3') - assert g.isomorphic(g2) is True
\ No newline at end of file + assert g.isomorphic(g2) is True diff --git a/test/test_issue190.py b/test/test_issue190.py index 3825f884..e5173eff 100644 --- a/test/test_issue190.py +++ b/test/test_issue190.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +from nose import SkipTest from rdflib.graph import ConjunctiveGraph from rdflib.parser import StringInputSource import textwrap @@ -34,6 +35,7 @@ a nfo:PaginatedTextDocument ; test_string1 = u"""\ Betriebsnummer der Einzugsstelle:\nKnappschaft\n980 0000 6\nWICHTIGES DOKUMENT - SORGFÄLTIG AUFBEWAHREN!\n """ + def test1(): meta1 = meta.encode('utf-8') % test_string1.encode('utf-8') graph = ConjunctiveGraph() @@ -46,10 +48,10 @@ Knappschaft WICHTIGES DOKUMENT - SORGFÄLTIG AUFBEWAHREN! """ + def test2(): meta2 = meta.encode('utf-8') % test_string2.encode('utf-8') graph = ConjunctiveGraph() graph.parse(StringInputSource(prefix + '<http://example.org/>' + meta2), format='n3') -from nose import SkipTest raise SkipTest("Known issue, with newlines in text") diff --git a/test/test_issue223.py b/test/test_issue223.py index c12f4fa1..e1981a30 100644 --- a/test/test_issue223.py +++ b/test/test_issue223.py @@ -7,13 +7,16 @@ ttl = """ :s :p (:a :b :a). """ + + def test_collection_with_duplicates(): g = Graph().parse(data=ttl, format="turtle") - for _,_,o in g.triples((URIRef("http://example.org/s"), URIRef("http://example.org/p"), None)): + for _, _, o in g.triples((URIRef("http://example.org/s"), URIRef("http://example.org/p"), None)): break c = g.collection(o) assert list(c) == list(URIRef("http://example.org/" + x) for x in ["a", "b", "a"]) assert len(c) == 3 + if __name__ == '__main__': test_collection_with_duplicates() diff --git a/test/test_issue247.py b/test/test_issue247.py index bee1baa7..780d578b 100644 --- a/test/test_issue247.py +++ b/test/test_issue247.py @@ -50,5 +50,6 @@ class TestXMLLiteralwithLangAttr(unittest.TestCase): g = rdflib.Graph() g.parse(data=failxml) + if __name__ == "__main__": unittest.main() diff --git a/test/test_issue248.py b/test/test_issue248.py index f2b984fa..4cc490a6 100644 --- a/test/test_issue248.py +++ b/test/test_issue248.py @@ -89,5 +89,6 @@ class TestSerialization(unittest.TestCase): # Actual test should be the inverse of the below ... self.assertTrue('<1> a skos:Concept ;' in sg, sg) + if __name__ == "__main__": unittest.main() diff --git a/test/test_issue274.py b/test/test_issue274.py index 3affa33e..288d7857 100644 --- a/test/test_issue274.py +++ b/test/test_issue274.py @@ -14,12 +14,15 @@ NS = { 'xsd': XSD, } + def query(querystr, initNs=NS, initBindings=None): return G.query(querystr, initNs=initNs, initBindings=initBindings) + def setup(): pass + def teardown(): pass @@ -28,110 +31,137 @@ def test_cast_string_to_string(): res = query('''SELECT (xsd:string("hello") as ?x) {}''') eq_(list(res)[0][0], Literal("hello", datatype=XSD.string)) + def test_cast_int_to_string(): res = query('''SELECT (xsd:string(42) as ?x) {}''') eq_(list(res)[0][0], Literal("42", datatype=XSD.string)) + def test_cast_float_to_string(): res = query('''SELECT (xsd:string(3.14) as ?x) {}''') eq_(list(res)[0][0], Literal("3.14", datatype=XSD.string)) + def test_cast_bool_to_string(): res = query('''SELECT (xsd:string(true) as ?x) {}''') eq_(list(res)[0][0], Literal("true", datatype=XSD.string)) + def test_cast_iri_to_string(): res = query('''SELECT (xsd:string(<http://example.org/>) as ?x) {}''') eq_(list(res)[0][0], Literal("http://example.org/", datatype=XSD.string)) + def test_cast_datetime_to_datetime(): res = query('''SELECT (xsd:dateTime("1970-01-01T00:00:00Z"^^xsd:dateTime) as ?x) {}''') eq_(list(res)[0][0], Literal("1970-01-01T00:00:00Z", datatype=XSD.dateTime)) + def test_cast_string_to_datetime(): res = query('''SELECT (xsd:dateTime("1970-01-01T00:00:00Z"^^xsd:string) as ?x) {}''') eq_(list(res)[0][0], Literal("1970-01-01T00:00:00Z", datatype=XSD.dateTime)) + def test_cast_string_to_float(): res = query('''SELECT (xsd:float("0.5") as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.float)) + def test_cast_int_to_float(): res = query('''SELECT (xsd:float(1) as ?x) {}''') eq_(list(res)[0][0], Literal("1", datatype=XSD.float)) + def test_cast_float_to_float(): res = query('''SELECT (xsd:float("0.5"^^xsd:float) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.float)) + def test_cast_double_to_float(): res = query('''SELECT (xsd:float("0.5"^^xsd:double) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.float)) + def test_cast_decimal_to_float(): res = query('''SELECT (xsd:float("0.5"^^xsd:decimal) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.float)) + def test_cast_string_to_double(): res = query('''SELECT (xsd:double("0.5") as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.double)) + def test_cast_int_to_double(): res = query('''SELECT (xsd:double(1) as ?x) {}''') eq_(list(res)[0][0], Literal("1", datatype=XSD.double)) + def test_cast_float_to_double(): res = query('''SELECT (xsd:double("0.5"^^xsd:float) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.double)) + def test_cast_double_to_double(): res = query('''SELECT (xsd:double("0.5"^^xsd:double) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.double)) + def test_cast_decimal_to_double(): res = query('''SELECT (xsd:double("0.5"^^xsd:decimal) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.double)) + def test_cast_string_to_decimal(): res = query('''SELECT (xsd:decimal("0.5") as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.decimal)) + def test_cast_int_to_decimal(): res = query('''SELECT (xsd:decimal(1) as ?x) {}''') eq_(list(res)[0][0], Literal("1", datatype=XSD.decimal)) + def test_cast_float_to_decimal(): res = query('''SELECT (xsd:decimal("0.5"^^xsd:float) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.decimal)) + def test_cast_double_to_decimal(): res = query('''SELECT (xsd:decimal("0.5"^^xsd:double) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.decimal)) + def test_cast_decimal_to_decimal(): res = query('''SELECT (xsd:decimal("0.5"^^xsd:decimal) as ?x) {}''') eq_(list(res)[0][0], Literal("0.5", datatype=XSD.decimal)) + def test_cast_string_to_int(): res = query('''SELECT (xsd:integer("42") as ?x) {}''') eq_(list(res)[0][0], Literal("42", datatype=XSD.integer)) + def test_cast_int_to_int(): res = query('''SELECT (xsd:integer(42) as ?x) {}''') eq_(list(res)[0][0], Literal("42", datatype=XSD.integer)) + def test_cast_string_to_bool(): res = query('''SELECT (xsd:boolean("TRUE") as ?x) {}''') eq_(list(res)[0][0], Literal("true", datatype=XSD.boolean)) + def test_cast_bool_to_bool(): res = query('''SELECT (xsd:boolean(true) as ?x) {}''') eq_(list(res)[0][0], Literal("true", datatype=XSD.boolean)) + def test_cast_bool_to_bool(): res = query('''SELECT (ex:f(42, "hello") as ?x) {}''') eq_(len(list(res)), 0) + class TestCustom(TestCase): @staticmethod diff --git a/test/test_issue363.py b/test/test_issue363.py index 1f7cfca7..7fc6cb26 100644 --- a/test/test_issue363.py +++ b/test/test_issue363.py @@ -28,6 +28,7 @@ data2 = '''<?xml version="1.0" encoding="utf-8"?> </rdf:RDF> ''' + def test_broken_rdfxml(): #import ipdb; ipdb.set_trace() def p(): @@ -35,10 +36,12 @@ def test_broken_rdfxml(): assert_raises(Exception, p) + def test_parsetype_resource(): g = rdflib.Graph().parse(data=data2) print(g.serialize(format='n3')) + if __name__ == '__main__': test_broken_rdfxml() test_parsetype_resource() diff --git a/test/test_issue379.py b/test/test_issue379.py index 34f91212..31dfce2b 100644 --- a/test/test_issue379.py +++ b/test/test_issue379.py @@ -31,6 +31,7 @@ class TestBaseAllowsHash(TestCase): """ GitHub Issue 379: https://github.com/RDFLib/rdflib/issues/379 """ + def setUp(self): self.g = rdflib.Graph() @@ -52,5 +53,6 @@ class TestBaseAllowsHash(TestCase): self.g.parse(data=base_data, format='n3') self.assertIsInstance(next(self.g.subjects()), rdflib.URIRef) + if __name__ == "__main__": unittest.main() diff --git a/test/test_issue381.py b/test/test_issue381.py index 4fc48e8c..3ab21d88 100644 --- a/test/test_issue381.py +++ b/test/test_issue381.py @@ -3,6 +3,7 @@ from rdflib.compare import isomorphic NS = Namespace("http://example.org/") + def test_no_spurious_semicolon(): sparql = """ PREFIX : <http://example.org/> @@ -11,13 +12,14 @@ def test_no_spurious_semicolon(): } WHERE {} """ expected = Graph() - expected.addN( t+(expected,) for t in [ + expected.addN(t + (expected,) for t in [ (NS.a, NS.b, NS.c), (NS.a, NS.d, NS.e), ]) got = Graph().query(sparql).graph assert isomorphic(got, expected), got.serialize(format="turtle") + def test_one_spurious_semicolon(): sparql = """ PREFIX : <http://example.org/> @@ -26,13 +28,14 @@ def test_one_spurious_semicolon(): } WHERE {} """ expected = Graph() - expected.addN( t+(expected,) for t in [ + expected.addN(t + (expected,) for t in [ (NS.a, NS.b, NS.c), (NS.a, NS.d, NS.e), ]) got = Graph().query(sparql).graph assert isomorphic(got, expected), got.serialize(format="turtle") + def test_one_spurious_semicolon_no_perdiod(): sparql = """ PREFIX : <http://example.org/> @@ -41,13 +44,14 @@ def test_one_spurious_semicolon_no_perdiod(): } WHERE {} """ expected = Graph() - expected.addN( t+(expected,) for t in [ + expected.addN(t + (expected,) for t in [ (NS.a, NS.b, NS.c), (NS.a, NS.d, NS.e), ]) got = Graph().query(sparql).graph assert isomorphic(got, expected), got.serialize(format="turtle") + def test_two_spurious_semicolons_no_period(): sparql = """ PREFIX : <http://example.org/> @@ -56,13 +60,14 @@ def test_two_spurious_semicolons_no_period(): } WHERE {} """ expected = Graph() - expected.addN( t+(expected,) for t in [ + expected.addN(t + (expected,) for t in [ (NS.a, NS.b, NS.c), (NS.a, NS.d, NS.e), ]) got = Graph().query(sparql).graph assert isomorphic(got, expected), got.serialize(format="turtle") + def test_one_spurious_semicolons_bnode(): sparql = """ PREFIX : <http://example.org/> @@ -71,13 +76,14 @@ def test_one_spurious_semicolons_bnode(): } WHERE {} """ expected = Graph() - expected.addN( t+(expected,) for t in [ + expected.addN(t + (expected,) for t in [ (BNode("a"), NS.b, NS.c), (BNode("a"), NS.d, NS.e), ]) got = Graph().query(sparql).graph assert isomorphic(got, expected), got.serialize(format="turtle") + def test_pathological(): """ This test did not raise an exception, @@ -92,7 +98,7 @@ def test_pathological(): } WHERE {} """ expected = Graph() - expected.addN( t+(expected,) for t in [ + expected.addN(t + (expected,) for t in [ (NS.a, NS.b, NS.c), (NS.a, NS.d, NS.e), (NS.a, NS.f, NS.g), @@ -100,6 +106,7 @@ def test_pathological(): got = Graph().query(sparql).graph assert isomorphic(got, expected), got.serialize(format="turtle") + def test_mixing_spurious_semicolons_and_commas(): sparql = """ PREFIX : <http://example.org/> @@ -109,11 +116,10 @@ def test_mixing_spurious_semicolons_and_commas(): } WHERE {} """ expected = Graph() - expected.addN( t+(expected,) for t in [ + expected.addN(t + (expected,) for t in [ (NS.a, NS.b, NS.c), (NS.a, NS.d, NS.e), (NS.a, NS.d, NS.f), ]) got = Graph().query(sparql).graph assert isomorphic(got, expected), got.serialize(format="turtle") - diff --git a/test/test_issue432.py b/test/test_issue432.py index 9ac4ec00..05d8258a 100644 --- a/test/test_issue432.py +++ b/test/test_issue432.py @@ -1,5 +1,6 @@ import rdflib + def test_trig_default_graph(): ds = rdflib.ConjunctiveGraph() data = """ diff --git a/test/test_issue446.py b/test/test_issue446.py index bc414baf..79cd41be 100644 --- a/test/test_issue446.py +++ b/test/test_issue446.py @@ -3,6 +3,7 @@ from rdflib import Graph, URIRef, Literal + def test_sparql_unicode(): g = Graph() trip = ( diff --git a/test/test_issue492.py b/test/test_issue492.py index dbbf7b38..754e5cbf 100644 --- a/test/test_issue492.py +++ b/test/test_issue492.py @@ -4,6 +4,7 @@ import rdflib + def test_issue492(): query = ''' prefix owl: <http://www.w3.org/2002/07/owl#> diff --git a/test/test_issue523.py b/test/test_issue523.py index 778ecb9c..774167f3 100644 --- a/test/test_issue523.py +++ b/test/test_issue523.py @@ -2,6 +2,7 @@ import rdflib + def test_issue523(): g = rdflib.Graph() r = g.query("SELECT (<../baz> as ?test) WHERE {}", @@ -10,9 +11,9 @@ def test_issue523(): assert res == b'test\r\nhttp://example.org/baz\r\n', repr(res) # expected result: - #test - #http://example.org/baz + # test + # http://example.org/baz # actual result; - #test - #http://example.org/foo/bar../baz + # test + # http://example.org/foo/bar../baz diff --git a/test/test_issue532.py b/test/test_issue532.py index 89aa20b6..422dd507 100644 --- a/test/test_issue532.py +++ b/test/test_issue532.py @@ -2,6 +2,7 @@ from rdflib import Graph + def test_issue532(): data = """ @base <http://purl.org/linkedpolitics/MembersOfParliament_background> . @@ -33,7 +34,7 @@ def test_issue532(): g = Graph() g.parse(data=data, format='n3') - getnewMeps =""" + getnewMeps = """ PREFIX lpv: <http://purl.org/linkedpolitics/vocabulary/> prefix foaf: <http://xmlns.com/foaf/0.1/> prefix xsd: <http://www.w3.org/2001/XMLSchema#> diff --git a/test/test_issue535.py b/test/test_issue535.py index 2799fc02..de38404d 100644 --- a/test/test_issue535.py +++ b/test/test_issue535.py @@ -1,5 +1,6 @@ from rdflib import ConjunctiveGraph, URIRef + def test_nquads_default_graph(): ds = ConjunctiveGraph() @@ -10,7 +11,7 @@ def test_nquads_default_graph(): """ publicID = URIRef("http://example.org/g0") - + ds.parse(data=data, format="nquads", publicID=publicID) assert len(ds) == 3, len(g) diff --git a/test/test_issue545.py b/test/test_issue545.py index 67dd0d35..86c8723a 100644 --- a/test/test_issue545.py +++ b/test/test_issue545.py @@ -2,9 +2,8 @@ from rdflib.plugins import sparql from rdflib.namespace import RDFS, OWL, DC, SKOS -def test_issue(): - +def test_issue(): query = sparql.prepareQuery( """ @@ -16,4 +15,4 @@ def test_issue(): ?property rdfs:label | skos:altLabel ?label . } """, - initNs = {"rdfs":RDFS, "owl":OWL, "dc":DC, "skos":SKOS}) + initNs={"rdfs": RDFS, "owl": OWL, "dc": DC, "skos": SKOS}) diff --git a/test/test_issue554.py b/test/test_issue554.py index 38983fc3..ba946cf4 100644 --- a/test/test_issue554.py +++ b/test/test_issue554.py @@ -2,6 +2,7 @@ import rdflib + def test_sparql_empty_no_row(): g = rdflib.Graph() q = 'select ?whatever { }' diff --git a/test/test_issue563.py b/test/test_issue563.py index 6f042bb7..1ae8460d 100644 --- a/test/test_issue563.py +++ b/test/test_issue563.py @@ -20,6 +20,7 @@ SELECT ?x (%s(?y) as ?ys) (%s(?z) as ?zs) WHERE { GROUP BY ?x """ + def test_sample(): g = Graph() results = set(tuple(i) for i in g.query(QUERY % ("SAMPLE", "SAMPLE"))) @@ -30,6 +31,7 @@ def test_sample(): (Literal(5), None, Literal(25)), ]) + def test_count(): g = Graph() results = set(tuple(i) for i in g.query(QUERY % ("COUNT", "COUNT"))) @@ -40,9 +42,7 @@ def test_count(): (Literal(5), Literal(0), Literal(1)), ]) + if __name__ == "__main__": test_sample() test_count() - - - diff --git a/test/test_issue579.py b/test/test_issue579.py index b7a111e7..9ba326b3 100644 --- a/test/test_issue579.py +++ b/test/test_issue579.py @@ -3,6 +3,7 @@ from rdflib import Graph, URIRef, Literal, Namespace from rdflib.namespace import FOAF, RDF + def test_issue579(): g = Graph() g.bind('foaf', FOAF) diff --git a/test/test_issue604.py b/test/test_issue604.py index 088fd07d..aef19b8c 100644 --- a/test/test_issue604.py +++ b/test/test_issue604.py @@ -3,15 +3,15 @@ from __future__ import print_function from rdflib import * from rdflib.collection import Collection + def test_issue604(): EX = Namespace('http://ex.co/') g = Graph() bn = BNode() g.add((EX.s, EX.p, bn)) - c = Collection(g, bn, map(Literal, [1,2,4])) + c = Collection(g, bn, map(Literal, [1, 2, 4])) c[2] = Literal(3) - got = list(g.objects(bn, RDF.rest/RDF.rest/RDF.first)) - expected = [ Literal(3) ] - assert got == [ Literal(3) ], got - + got = list(g.objects(bn, RDF.rest / RDF.rest / RDF.first)) + expected = [Literal(3)] + assert got == [Literal(3)], got diff --git a/test/test_issue_git_200.py b/test/test_issue_git_200.py index 3d04a08c..32a4ba9f 100644 --- a/test/test_issue_git_200.py +++ b/test/test_issue_git_200.py @@ -2,13 +2,15 @@ import rdflib import nose.tools -def test_broken_add(): - g=rdflib.Graph() - nose.tools.assert_raises(AssertionError, lambda : g.add((1,2,3))) - nose.tools.assert_raises(AssertionError, lambda : g.addN([(1,2,3,g)])) +def test_broken_add(): + g = rdflib.Graph() + nose.tools.assert_raises(AssertionError, lambda: g.add((1, 2, 3))) + nose.tools.assert_raises(AssertionError, lambda: g.addN([(1, 2, 3, g)])) -if __name__=='__main__': - import nose, sys + +if __name__ == '__main__': + import nose + import sys nose.main(defaultTest=sys.argv[0]) diff --git a/test/test_issue_git_336.py b/test/test_issue_git_336.py index 2cad1d10..f3250107 100644 --- a/test/test_issue_git_336.py +++ b/test/test_issue_git_336.py @@ -39,7 +39,6 @@ def test_ns_localname_roundtrip(): g1.parse(data=turtledump, format="turtle") - if __name__ == '__main__': import nose import sys diff --git a/test/test_literal.py b/test/test_literal.py index 7ff0b8e5..feb9d72d 100644 --- a/test/test_literal.py +++ b/test/test_literal.py @@ -1,14 +1,16 @@ import unittest -import rdflib # needed for eval(repr(...)) below +import rdflib # needed for eval(repr(...)) below from rdflib.term import Literal, URIRef, _XSD_DOUBLE, bind from six import integer_types, PY3 + def uformat(s): if PY3: - return s.replace("u'","'") + return s.replace("u'", "'") return s + class TestLiteral(unittest.TestCase): def setUp(self): pass @@ -43,10 +45,11 @@ class TestLiteral(unittest.TestCase): l = rdflib.Literal(True) self.assertEqual(l.datatype, rdflib.XSD["boolean"]) + class TestNew(unittest.TestCase): def testCantPassLangAndDatatype(self): self.assertRaises(TypeError, - Literal, 'foo', lang='en', datatype=URIRef("http://example.com/")) + Literal, 'foo', lang='en', datatype=URIRef("http://example.com/")) def testFromOtherLiteral(self): l = Literal(1) @@ -59,8 +62,6 @@ class TestNew(unittest.TestCase): l2 = Literal(l, datatype=rdflib.XSD.integer) self.assertTrue(isinstance(l2.value, integer_types)) - - def testDatatypeGetsAutoURIRefConversion(self): # drewp disapproves of this behavior, but it should be # represented in the tests @@ -71,7 +72,6 @@ class TestNew(unittest.TestCase): self.assertEqual(x.datatype, URIRef("pennies")) - class TestRepr(unittest.TestCase): def testOmitsMissingDatatypeAndLang(self): self.assertEqual(repr(Literal("foo")), @@ -92,6 +92,7 @@ class TestRepr(unittest.TestCase): x = MyLiteral(u"foo") self.assertEqual(repr(x), uformat("MyLiteral(u'foo')")) + class TestDoubleOutput(unittest.TestCase): def testNoDanglingPoint(self): """confirms the fix for https://github.com/RDFLib/rdflib/issues/237""" @@ -99,45 +100,45 @@ class TestDoubleOutput(unittest.TestCase): out = vv._literal_n3(use_plain=True) self.assertTrue(out in ["8.8e-01", "0.88"], out) + class TestBindings(unittest.TestCase): def testBinding(self): class a: - def __init__(self,v): - self.v=v[3:-3] + def __init__(self, v): + self.v = v[3:-3] + def __str__(self): - return '<<<%s>>>'%self.v + return '<<<%s>>>' % self.v - dtA=rdflib.URIRef('urn:dt:a') - bind(dtA,a) + dtA = rdflib.URIRef('urn:dt:a') + bind(dtA, a) - va=a("<<<2>>>") - la=Literal(va, normalize=True) - self.assertEqual(la.value,va) + va = a("<<<2>>>") + la = Literal(va, normalize=True) + self.assertEqual(la.value, va) self.assertEqual(la.datatype, dtA) - la2=Literal("<<<2>>>", datatype=dtA) + la2 = Literal("<<<2>>>", datatype=dtA) self.assertTrue(isinstance(la2.value, a)) - self.assertEqual(la2.value.v,va.v) + self.assertEqual(la2.value.v, va.v) class b: - def __init__(self,v): - self.v=v[3:-3] + def __init__(self, v): + self.v = v[3:-3] + def __str__(self): - return 'B%s'%self.v + return 'B%s' % self.v - dtB=rdflib.URIRef('urn:dt:b') - bind(dtB,b,None,lambda x: '<<<%s>>>'%x) + dtB = rdflib.URIRef('urn:dt:b') + bind(dtB, b, None, lambda x: '<<<%s>>>' % x) - vb=b("<<<3>>>") - lb=Literal(vb, normalize=True) - self.assertEqual(lb.value,vb) + vb = b("<<<3>>>") + lb = Literal(vb, normalize=True) + self.assertEqual(lb.value, vb) self.assertEqual(lb.datatype, dtB) - - - if __name__ == "__main__": unittest.main() diff --git a/test/test_memory_store.py b/test/test_memory_store.py index 0fb6c82d..f579250e 100644 --- a/test/test_memory_store.py +++ b/test/test_memory_store.py @@ -1,8 +1,9 @@ import unittest import rdflib -rdflib.plugin.register('Memory', rdflib.store.Store, - 'rdflib.plugins.memory', 'Memory') +rdflib.plugin.register('Memory', rdflib.store.Store, + 'rdflib.plugins.memory', 'Memory') + class StoreTestCase(unittest.TestCase): @@ -12,8 +13,8 @@ class StoreTestCase(unittest.TestCase): pred1 = rdflib.URIRef("http://example.org/foo#bar2") obj1 = rdflib.URIRef("http://example.org/foo#bar3") triple1 = (subj1, pred1, obj1) - triple2 = (subj1, - rdflib.URIRef("http://example.org/foo#bar4"), + triple2 = (subj1, + rdflib.URIRef("http://example.org/foo#bar4"), rdflib.URIRef("http://example.org/foo#bar5")) g.add(triple1) self.assertTrue(len(g) == 1) diff --git a/test/test_n3.py b/test/test_n3.py index 7a0f63bd..5d447732 100644 --- a/test/test_n3.py +++ b/test/test_n3.py @@ -1,3 +1,5 @@ +from rdflib.graph import Graph, ConjunctiveGraph +import unittest from rdflib.term import Literal, URIRef from rdflib.plugins.parsers.notation3 import BadSyntax @@ -59,11 +61,6 @@ n3:context a rdf:Property; rdfs:domain n3:statement; """ -import unittest - -from rdflib.graph import Graph, ConjunctiveGraph - - class TestN3Case(unittest.TestCase): def setUp(self): @@ -72,7 +69,6 @@ class TestN3Case(unittest.TestCase): def tearDown(self): pass - def testBaseCumulative(self): """ Test that the n3 parser supports base declarations @@ -221,12 +217,14 @@ foo-bar:Ex foo-bar:name "Test" . """ # this is issue https://github.com/RDFLib/rdflib/issues/312 g1 = Graph() - g1.parse(data = ":a :b :c .", format='n3') + g1.parse(data=":a :b :c .", format='n3') g2 = Graph() - g2.parse(data = "@prefix : <#> . :a :b :c .", format='n3') + g2.parse(data="@prefix : <#> . :a :b :c .", format='n3') + + assert set(g1) == set( + g2), 'Document with declared empty prefix must match default #' - assert set(g1) == set(g2), 'Document with declared empty prefix must match default #' if __name__ == '__main__': unittest.main() diff --git a/test/test_n3_suite.py b/test/test_n3_suite.py index fd1a86cf..f6efe34a 100644 --- a/test/test_n3_suite.py +++ b/test/test_n3_suite.py @@ -6,24 +6,27 @@ try: except: from test.testutils import check_serialize_parse + def _get_test_files_formats(): skiptests = [ ] for f in os.listdir('test/n3'): if f not in skiptests: - fpath = "test/n3/"+f + fpath = "test/n3/" + f if f.endswith('.rdf'): yield fpath, 'xml' elif f.endswith('.n3'): yield fpath, 'n3' + def test_n3_writing(): for fpath, fmt in _get_test_files_formats(): yield check_serialize_parse, fpath, fmt, 'n3' + if __name__ == "__main__": if len(sys.argv) > 1: - check_serialize_parse(sys.argv[1], 'n3','n3', True) + check_serialize_parse(sys.argv[1], 'n3', 'n3', True) sys.exit() else: import nose diff --git a/test/test_namespace.py b/test/test_namespace.py index 520bde9c..69739434 100644 --- a/test/test_namespace.py +++ b/test/test_namespace.py @@ -4,21 +4,22 @@ from rdflib.graph import Graph from rdflib.term import URIRef from six import b + class NamespacePrefixTest(unittest.TestCase): def test_compute_qname(self): """Test sequential assignment of unknown prefixes""" g = Graph() self.assertEqual(g.compute_qname(URIRef("http://foo/bar/baz")), - ("ns1", URIRef("http://foo/bar/"), "baz")) + ("ns1", URIRef("http://foo/bar/"), "baz")) self.assertEqual(g.compute_qname(URIRef("http://foo/bar#baz")), - ("ns2", URIRef("http://foo/bar#"), "baz")) + ("ns2", URIRef("http://foo/bar#"), "baz")) # should skip to ns4 when ns3 is already assigned g.bind("ns3", URIRef("http://example.org/")) self.assertEqual(g.compute_qname(URIRef("http://blip/blop")), - ("ns4", URIRef("http://blip/"), "blop")) + ("ns4", URIRef("http://blip/"), "blop")) def test_n3(self): g = Graph() @@ -39,4 +40,5 @@ class NamespacePrefixTest(unittest.TestCase): URIRef("http://example3.com/baz"))) n3 = g.serialize(format="n3") - self.assertTrue(b("<http://example1.com/foo> ns1:bar <http://example3.com/baz> .") in n3) + self.assertTrue( + b("<http://example1.com/foo> ns1:bar <http://example3.com/baz> .") in n3) diff --git a/test/test_nodepickler.py b/test/test_nodepickler.py index c2dbbac9..31a667da 100644 --- a/test/test_nodepickler.py +++ b/test/test_nodepickler.py @@ -15,10 +15,10 @@ cases = [ '"', "'", '"\'"', - '\\', # len 1 - '\\"', # len 2 - '\\\\"', # len 3 - '\\"\\', # len 3 + '\\', # len 1 + '\\"', # len 2 + '\\\\"', # len 3 + '\\"\\', # len 3 '<a some="typical" html="content">here</a>', ] @@ -46,7 +46,7 @@ class UtilTestCase(unittest.TestCase): dump = pickle.dumps(np) np2 = pickle.loads(dump) self.assertEqual(np._ids, np2._ids) - self.assertEqual(np._objects, np2._objects) + self.assertEqual(np._objects, np2._objects) if __name__ == '__main__': diff --git a/test/test_nquads.py b/test/test_nquads.py index 18ae94c8..559f754f 100644 --- a/test/test_nquads.py +++ b/test/test_nquads.py @@ -4,6 +4,7 @@ from six import b TEST_BASE = 'test/nquads.rdflib' + class NQuadsParserTest(unittest.TestCase): def _load_example(self): diff --git a/test/test_nquads_w3c.py b/test/test_nquads_w3c.py index 1c132e9b..f12850d2 100644 --- a/test/test_nquads_w3c.py +++ b/test/test_nquads_w3c.py @@ -8,6 +8,7 @@ from .testutils import nose_tst_earl_report verbose = False + def nquads(test): g = ConjunctiveGraph() @@ -19,16 +20,19 @@ def nquads(test): if test.syntax: raise + testers = { RDFT.TestNQuadsPositiveSyntax: nquads, RDFT.TestNQuadsNegativeSyntax: nquads } -def test_nquads(tests = None): + +def test_nquads(tests=None): for t in nose_tests(testers, 'test/w3c/nquads/manifest.ttl'): if tests: for test in tests: - if test in t[1].uri: break + if test in t[1].uri: + break else: continue diff --git a/test/test_nt_misc.py b/test/test_nt_misc.py index be97e23d..d9f9e1f9 100644 --- a/test/test_nt_misc.py +++ b/test/test_nt_misc.py @@ -9,6 +9,7 @@ from six.moves.urllib.request import urlopen log = logging.getLogger(__name__) + class NTTestCase(unittest.TestCase): def testIssue859(self): @@ -16,8 +17,8 @@ class NTTestCase(unittest.TestCase): graphB = Graph() graphA.parse("test/nt/quote-01.nt", format="ntriples") graphB.parse("test/nt/quote-02.nt", format="ntriples") - for subjectA,predicateA,objA in graphA: - for subjectB,predicateB,objB in graphB: + for subjectA, predicateA, objA in graphA: + for subjectB, predicateB, objB in graphB: self.assertEqual(subjectA, subjectB) self.assertEqual(predicateA, predicateB) self.assertEqual(objA, objB) @@ -79,7 +80,7 @@ class NTTestCase(unittest.TestCase): self.assertEqual(res, uniquot) def test_NTriplesParser_fpath(self): - fpath = "test/nt/"+os.listdir('test/nt')[0] + fpath = "test/nt/" + os.listdir('test/nt')[0] p = ntriples.NTriplesParser() self.assertRaises(ntriples.ParseError, p.parse, fpath) @@ -95,7 +96,7 @@ class NTTestCase(unittest.TestCase): self.assertTrue(res == None) def test_w3_ntriple_variants(self): - uri = "file:///"+os.getcwd()+"/test/nt/test.ntriples" + uri = "file:///" + os.getcwd() + "/test/nt/test.ntriples" parser = ntriples.NTriplesParser() u = urlopen(uri) diff --git a/test/test_nt_suite.py b/test/test_nt_suite.py index f2e4477b..c9175320 100644 --- a/test/test_nt_suite.py +++ b/test/test_nt_suite.py @@ -10,14 +10,16 @@ Basic code for loading all NT files in test/nt folder The actual tests are done in test_roundtrip """ + def _get_test_files_formats(): for f in os.listdir('test/nt'): - fpath = "test/nt/"+f + fpath = "test/nt/" + f if f.endswith('.rdf'): yield fpath, 'xml' elif f.endswith('.nt'): yield fpath, 'nt' + def all_nt_files(): skiptests = [ # illegal literal as subject diff --git a/test/test_nt_w3c.py b/test/test_nt_w3c.py index 99c52fac..65166f5e 100644 --- a/test/test_nt_w3c.py +++ b/test/test_nt_w3c.py @@ -8,6 +8,7 @@ from .testutils import nose_tst_earl_report verbose = False + def nt(test): g = Graph() @@ -19,16 +20,19 @@ def nt(test): if test.syntax: raise + testers = { RDFT.TestNTriplesPositiveSyntax: nt, RDFT.TestNTriplesNegativeSyntax: nt } + def test_nt(tests=None): for t in nose_tests(testers, 'test/w3c/nt/manifest.ttl', legacy=True): if tests: for test in tests: - if test in t[1].uri: break + if test in t[1].uri: + break else: continue diff --git a/test/test_path_div_future.py b/test/test_path_div_future.py index ca8357d5..82dadc29 100644 --- a/test/test_path_div_future.py +++ b/test/test_path_div_future.py @@ -4,6 +4,7 @@ from rdflib.paths import Path uri_tplt = "http://example.org/%s" + def test_path_div_future(): path = URIRef(uri_tplt % "one") / URIRef(uri_tplt % "other") assert isinstance(path, Path) diff --git a/test/test_prefixTypes.py b/test/test_prefixTypes.py index d49b6abc..415f0459 100644 --- a/test/test_prefixTypes.py +++ b/test/test_prefixTypes.py @@ -13,6 +13,7 @@ graph = Graph().parse(format='n3', data=""" dct:created "2011-03-20"^^xsd:date . """) + class PrefixTypesTest(unittest.TestCase): """N3/Turtle serializers should use prefixes, @@ -22,14 +23,12 @@ class PrefixTypesTest(unittest.TestCase): http://code.google.com/p/rdflib/issues/detail?id=161 """ - def test(self): - s=graph.serialize(format='n3') + s = graph.serialize(format='n3') print(s) self.assertTrue(b("foaf:Document") in s) self.assertTrue(b("xsd:date") in s) - if __name__ == '__main__': unittest.main() diff --git a/test/test_preflabel.py b/test/test_preflabel.py index dd62de4d..76c4131e 100644 --- a/test/test_preflabel.py +++ b/test/test_preflabel.py @@ -6,6 +6,7 @@ from rdflib.namespace import SKOS from rdflib import RDFS from rdflib import URIRef + class TestPrefLabel(unittest.TestCase): def setUp(self): @@ -13,12 +14,12 @@ class TestPrefLabel(unittest.TestCase): self.u = URIRef('http://example.com/foo') self.g.add([self.u, RDFS.label, Literal('foo')]) self.g.add([self.u, RDFS.label, Literal('bar')]) - + def test_default_label_sorting(self): res = sorted(self.g.preferredLabel(self.u)) - tgt = [(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), - rdflib.term.Literal(u'bar')), - (rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), + tgt = [(rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), + rdflib.term.Literal(u'bar')), + (rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal(u'foo'))] self.assertEqual(res, tgt) @@ -54,4 +55,3 @@ class TestPrefLabel(unittest.TestCase): tgt = [(rdflib.term.URIRef('http://www.w3.org/2004/02/skos/core#prefLabel'), rdflib.term.Literal(u'blubb', lang='en'))] self.assertEqual(res, tgt) - diff --git a/test/test_prettyxml.py b/test/test_prettyxml.py index 08071591..996e6e54 100644 --- a/test/test_prettyxml.py +++ b/test/test_prettyxml.py @@ -1,5 +1,5 @@ # -*- coding: UTF-8 -*- -from rdflib.term import URIRef, BNode, Literal +from rdflib.term import URIRef, BNode, Literal from rdflib.namespace import RDF, RDFS from six import b, BytesIO @@ -8,7 +8,6 @@ from rdflib.plugins.serializers.rdfxml import PrettyXMLSerializer from rdflib.graph import ConjunctiveGraph - class SerializerTestBase(object): repeats = 8 @@ -27,7 +26,7 @@ class SerializerTestBase(object): for i in range(self.repeats): self.test_serialize_and_reparse() - #test_multiple.slowtest=True # not really slow? + # test_multiple.slowtest=True # not really slow? def _assert_equal_graphs(g1, g2): @@ -39,16 +38,22 @@ def _assert_equal_graphs(g1, g2): assert len(g1copy) == 0, "Source graph larger than serialized graph." assert len(g2copy) == 0, "Serialized graph larger than source graph." + _blank = BNode() + def _mangled_copy(g): "Makes a copy of the graph, replacing all bnodes with the bnode ``_blank``." gcopy = ConjunctiveGraph() - isbnode = lambda v: isinstance(v, BNode) + + def isbnode(v): return isinstance(v, BNode) for s, p, o in g: - if isbnode(s): s = _blank - if isbnode(p): p = _blank - if isbnode(o): o = _blank + if isbnode(s): + s = _blank + if isbnode(p): + p = _blank + if isbnode(o): + o = _blank gcopy.add((s, p, o)) return gcopy @@ -59,6 +64,7 @@ def serialize(sourceGraph, makeSerializer, getValue=True, extra_args={}): serializer.serialize(stream, **extra_args) return getValue and stream.getvalue() or stream + def serialize_and_load(sourceGraph, makeSerializer): stream = serialize(sourceGraph, makeSerializer, False) stream.seek(0) @@ -126,7 +132,7 @@ class TestPrettyXmlSerializer(SerializerTestBase): def test_result_fragments_with_base(self): rdfXml = serialize(self.sourceGraph, self.serializer, - extra_args={'base':"http://example.org/", 'xml_base':"http://example.org/"}) + extra_args={'base': "http://example.org/", 'xml_base': "http://example.org/"}) assert b('xml:base="http://example.org/"') in rdfXml assert b('<Test rdf:about="data/a">') in rdfXml assert b('<rdf:Description rdf:about="data/b">') in rdfXml @@ -136,8 +142,8 @@ class TestPrettyXmlSerializer(SerializerTestBase): def test_subClassOf_objects(self): reparsedGraph = serialize_and_load(self.sourceGraph, self.serializer) _assert_expected_object_types_for_predicates(reparsedGraph, - [RDFS.seeAlso, RDFS.subClassOf], - [URIRef, BNode]) + [RDFS.seeAlso, RDFS.subClassOf], + [URIRef, BNode]) def test_pretty_xmlliteral(self): # given: @@ -163,4 +169,4 @@ def _assert_expected_object_types_for_predicates(graph, predicates, types): if p in predicates: someTrue = [isinstance(o, t) for t in types] assert True in someTrue, \ - "Bad type %s for object when predicate is <%s>." % (type(o), p) + "Bad type %s for object when predicate is <%s>." % (type(o), p) diff --git a/test/test_rdf_lists.py b/test/test_rdf_lists.py index 628d998c..a73d14d8 100644 --- a/test/test_rdf_lists.py +++ b/test/test_rdf_lists.py @@ -5,8 +5,8 @@ from rdflib.graph import Graph from rdflib.term import URIRef -DATA=\ -"""<http://example.com#C> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class>. +DATA =\ + """<http://example.com#C> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class>. <http://example.com#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> _:fIYNVPxd4. <http://example.com#B> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://example.com#A>. <http://example.com#B> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#Class>. @@ -20,8 +20,8 @@ _:fIYNVPxd3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.c _:fIYNVPxd3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>. """ -DATA_FALSE_ELEMENT=\ -""" +DATA_FALSE_ELEMENT =\ + """ <http://example.org/#ThreeMemberList> <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/#p> . <http://example.org/#ThreeMemberList> <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> _:list2 . _:list2 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> "false"^^<http://www.w3.org/2001/XMLSchema#boolean> . @@ -30,6 +30,7 @@ _:list3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.org/# _:list3 <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> . """ + def main(): unittest.main() @@ -37,15 +38,16 @@ def main(): class OWLCollectionTest(unittest.TestCase): def testCollectionRDFXML(self): - g=Graph().parse(data=DATA, format='nt') - g.namespace_manager.bind('owl',URIRef('http://www.w3.org/2002/07/owl#')) + g = Graph().parse(data=DATA, format='nt') + g.namespace_manager.bind('owl', URIRef('http://www.w3.org/2002/07/owl#')) print(g.serialize(format='pretty-xml')) class ListTest(unittest.TestCase): def testFalseElement(self): - g=Graph().parse(data=DATA_FALSE_ELEMENT, format='nt') - self.assertEqual(len(list(g.items(URIRef('http://example.org/#ThreeMemberList')))), 3) + g = Graph().parse(data=DATA_FALSE_ELEMENT, format='nt') + self.assertEqual( + len(list(g.items(URIRef('http://example.org/#ThreeMemberList')))), 3) if __name__ == '__main__': diff --git a/test/test_rdfxml.py b/test/test_rdfxml.py index d4e78eaf..94275e72 100644 --- a/test/test_rdfxml.py +++ b/test/test_rdfxml.py @@ -1,5 +1,8 @@ from __future__ import print_function +import sys +from encodings.utf_8 import StreamWriter + import unittest import os @@ -18,9 +21,7 @@ _logger = logging.getLogger("parser_rdfcore") verbose = 0 -from encodings.utf_8 import StreamWriter -import sys sw = StreamWriter(sys.stdout) @@ -215,6 +216,7 @@ class ParserTestCase(unittest.TestCase): self.assertEqual( num_failed, 0, "Failed: %s of %s." % (num_failed, total)) + RESULT = Namespace("http://www.w3.org/2002/03owlt/resultsOntology#") FOAF = Namespace("http://xmlns.com/foaf/0.1/") @@ -241,7 +243,7 @@ if __name__ == "__main__": try: argv = sys.argv - if len(argv)>1: + if len(argv) > 1: _logger.setLevel(logging.INFO) _logger.addHandler(logging.StreamHandler()) diff --git a/test/test_roundtrip.py b/test/test_roundtrip.py index 6d1ac3ee..819c944a 100644 --- a/test/test_roundtrip.py +++ b/test/test_roundtrip.py @@ -26,7 +26,8 @@ tests roundtripping through rdf/xml with only the literals-02 file SKIP = [ ('xml', 'test/nt/qname-02.nt'), # uses a property that cannot be qname'd - ('application/rdf+xml', 'test/nt/qname-02.nt'), # uses a property that cannot be qname'd + # uses a property that cannot be qname'd + ('application/rdf+xml', 'test/nt/qname-02.nt'), ] @@ -47,9 +48,9 @@ def roundtrip(e, verbose=False): g2.parse(data=s, format=testfmt) if verbose: - both, first, second = rdflib.compare.graph_diff(g1,g2) + both, first, second = rdflib.compare.graph_diff(g1, g2) print("Diff:") - print("%d triples in both"%len(both)) + print("%d triples in both" % len(both)) print("G1 Only:") for t in first: print(t) @@ -61,7 +62,8 @@ def roundtrip(e, verbose=False): assert rdflib.compare.isomorphic(g1, g2) - if verbose: print("Ok!") + if verbose: + print("Ok!") formats = None @@ -79,7 +81,8 @@ def test_cases(): formats = parsers.intersection(serializers) for testfmt in formats: - if "/" in testfmt: continue # skip double testing + if "/" in testfmt: + continue # skip double testing for f, infmt in all_nt_files(): if (testfmt, f) not in SKIP: yield roundtrip, (infmt, testfmt, f) diff --git a/test/test_rules.py b/test/test_rules.py index bd187b01..008104da 100644 --- a/test/test_rules.py +++ b/test/test_rules.py @@ -19,11 +19,11 @@ try: def _convert(node): if isinstance(node, Variable): return terms.Variable(node) - #return node + # return node elif isinstance(node, BNode): return terms.Exivar(node) elif isinstance(node, URIRef): - #return terms.URI(node) + # return terms.URI(node) return node elif isinstance(node, Literal): return node @@ -36,12 +36,13 @@ try: def facts(g): for s, p, o in g: - if p!=LOG.implies and not isinstance(s, BNode) and not isinstance(o, BNode): + if p != LOG.implies and not isinstance(s, BNode) and not isinstance(o, BNode): yield terms.Fact(_convert(s), _convert(p), _convert(o)) class PychinkoTestCase(unittest.TestCase): backend = 'default' tmppath = None + def setUp(self): self.g = Graph(store=self.backend) self.tmppath = mkdtemp() @@ -69,5 +70,3 @@ try: except ImportError as e: print("Could not test Pychinko: %s" % e) - - diff --git a/test/test_seq.py b/test/test_seq.py index 585a1062..a1411649 100644 --- a/test/test_seq.py +++ b/test/test_seq.py @@ -22,7 +22,6 @@ s = """\ """ - class SeqTestCase(unittest.TestCase): backend = 'default' path = 'store' @@ -43,9 +42,10 @@ class SeqTestCase(unittest.TestCase): # just make sure we can serialize self.store.serialize() + def test_suite(): return unittest.makeSuite(SeqTestCase) + if __name__ == '__main__': unittest.main(defaultTest='test_suite') - diff --git a/test/test_serializexml.py b/test/test_serializexml.py index 3c04e677..0dfa5e69 100644 --- a/test/test_serializexml.py +++ b/test/test_serializexml.py @@ -1,4 +1,4 @@ -from rdflib.term import URIRef, BNode +from rdflib.term import URIRef, BNode from rdflib.namespace import RDFS from six import b, BytesIO @@ -25,7 +25,7 @@ class SerializerTestBase(object): for i in range(self.repeats): self.test_serialize_and_reparse() - #test_multiple.slowtest=True # not really slow? + # test_multiple.slowtest=True # not really slow? def _assert_equal_graphs(g1, g2): @@ -37,16 +37,22 @@ def _assert_equal_graphs(g1, g2): assert len(g1copy) == 0, "Source graph larger than serialized graph." assert len(g2copy) == 0, "Serialized graph larger than source graph." + _blank = BNode() + def _mangled_copy(g): "Makes a copy of the graph, replacing all bnodes with the bnode ``_blank``." gcopy = ConjunctiveGraph() - isbnode = lambda v: isinstance(v, BNode) + + def isbnode(v): return isinstance(v, BNode) for s, p, o in g: - if isbnode(s): s = _blank - if isbnode(p): p = _blank - if isbnode(o): o = _blank + if isbnode(s): + s = _blank + if isbnode(p): + p = _blank + if isbnode(o): + o = _blank gcopy.add((s, p, o)) return gcopy @@ -57,6 +63,7 @@ def serialize(sourceGraph, makeSerializer, getValue=True, extra_args={}): serializer.serialize(stream, **extra_args) return getValue and stream.getvalue() or stream + def serialize_and_load(sourceGraph, makeSerializer): stream = serialize(sourceGraph, makeSerializer, False) stream.seek(0) @@ -113,9 +120,9 @@ class TestXMLSerializer(SerializerTestBase): def test_result_fragments(self): rdfXml = serialize(self.sourceGraph, self.serializer) - #print "--------" - #print rdfXml - #print "--------" + # print "--------" + # print rdfXml + # print "--------" assert b('<rdf:Description rdf:about="http://example.org/data/a">') in rdfXml assert b('<rdf:type rdf:resource="http://example.org/model/test#Test"/>') in rdfXml assert b('<rdf:Description rdf:about="http://example.org/data/b">') in rdfXml @@ -125,10 +132,10 @@ class TestXMLSerializer(SerializerTestBase): def test_result_fragments_with_base(self): rdfXml = serialize(self.sourceGraph, self.serializer, - extra_args={'base':"http://example.org/", 'xml_base':"http://example.org/"}) - #print "--------" - #print rdfXml - #print "--------" + extra_args={'base': "http://example.org/", 'xml_base': "http://example.org/"}) + # print "--------" + # print rdfXml + # print "--------" assert b('xml:base="http://example.org/"') in rdfXml assert b('<rdf:Description rdf:about="data/a">') in rdfXml assert b('<rdf:type rdf:resource="model/test#Test"/>') in rdfXml @@ -139,12 +146,13 @@ class TestXMLSerializer(SerializerTestBase): def test_subClassOf_objects(self): reparsedGraph = serialize_and_load(self.sourceGraph, self.serializer) _assert_expected_object_types_for_predicates(reparsedGraph, - [RDFS.seeAlso, RDFS.subClassOf], - [URIRef, BNode]) + [RDFS.seeAlso, RDFS.subClassOf], + [URIRef, BNode]) + def _assert_expected_object_types_for_predicates(graph, predicates, types): for s, p, o in graph: if p in predicates: someTrue = [isinstance(o, t) for t in types] assert True in someTrue, \ - "Bad type %s for object when predicate is <%s>." % (type(o), p) + "Bad type %s for object when predicate is <%s>." % (type(o), p) diff --git a/test/test_slice.py b/test/test_slice.py index 2b02266c..27e6e49a 100644 --- a/test/test_slice.py +++ b/test/test_slice.py @@ -2,6 +2,7 @@ from rdflib import Graph, URIRef import unittest + class GraphSlice(unittest.TestCase): def testSlice(self): @@ -12,40 +13,38 @@ class GraphSlice(unittest.TestCase): all operations return generators over full triples """ - sl=lambda x,y: self.assertEqual(len(list(x)),y) - soe=lambda x,y: self.assertEqual(set([a[2] for a in x]),set(y)) # equals objects - g=self.graph - + def sl(x, y): return self.assertEqual(len(list(x)), y) + + def soe(x, y): return self.assertEqual( + set([a[2] for a in x]), set(y)) # equals objects + g = self.graph + # Single terms are all trivial: # single index slices by subject, i.e. return triples((x,None,None)) # tell me everything about "tarek" - sl(g[self.tarek],2) - + sl(g[self.tarek], 2) + # single slice slices by s,p,o, with : used to split # tell me everything about "tarek" (same as above) - sl(g[self.tarek::],2) + sl(g[self.tarek::], 2) # give me every "likes" relationship - sl(g[:self.likes:],5) + sl(g[:self.likes:], 5) # give me every relationship to pizza - sl(g[::self.pizza],3) + sl(g[::self.pizza], 3) # give me everyone who likes pizza - sl(g[:self.likes:self.pizza],2) - + sl(g[:self.likes:self.pizza], 2) + # does tarek like pizza? self.assertTrue(g[self.tarek:self.likes:self.pizza]) # More intesting is using paths # everything hated or liked - sl(g[:self.hates|self.likes], 7) - - - - + sl(g[:self.hates | self.likes], 7) def setUp(self): self.graph = Graph() @@ -75,7 +74,7 @@ class GraphSlice(unittest.TestCase): self.graph.add((michel, likes, cheese)) self.graph.add((bob, likes, cheese)) self.graph.add((bob, hates, pizza)) - self.graph.add((bob, hates, michel)) # gasp! + self.graph.add((bob, hates, michel)) # gasp! if __name__ == '__main__': diff --git a/test/test_sparql.py b/test/test_sparql.py index f6064c65..b7b71ee4 100644 --- a/test/test_sparql.py +++ b/test/test_sparql.py @@ -4,6 +4,7 @@ from rdflib.compare import isomorphic from nose.tools import eq_ + def test_graph_prefix(): """ This is issue https://github.com/RDFLib/rdflib/issues/313 @@ -38,10 +39,11 @@ def test_graph_prefix(): eq_(list(g1.query(q_str)), expected) eq_(list(g2.query(q_str)), expected) + def test_variable_order(): g = Graph() - g.add((URIRef("http://foo"),URIRef("http://bar"),URIRef("http://baz"))) + g.add((URIRef("http://foo"), URIRef("http://bar"), URIRef("http://baz"))) res = g.query("SELECT (42 AS ?a) ?b { ?b ?c ?d }") row = list(res)[0] @@ -64,6 +66,7 @@ def test_sparql_bnodelist(): prepareQuery('select * where { ?s ?p ( [ ?p2 ?o2 ] [] ) . }') prepareQuery('select * where { ?s ?p ( [] [ ?p2 ?o2 ] [] ) . }') + def test_complex_sparql_construct(): g = Graph() @@ -75,6 +78,7 @@ def test_complex_sparql_construct(): }''' g.query(q) + if __name__ == '__main__': import nose nose.main(defaultTest=__name__) diff --git a/test/test_sparql_agg_distinct.py b/test/test_sparql_agg_distinct.py index 5bc03c2b..7ab0f58a 100644 --- a/test/test_sparql_agg_distinct.py +++ b/test/test_sparql_agg_distinct.py @@ -10,10 +10,11 @@ SELECT ?x (MIN(?y_) as ?y) (%s(DISTINCT ?z_) as ?z) { } GROUP BY ?x ORDER BY ?x ''' + def test_group_concat_distinct(): g = Graph() results = g.query(query_tpl % 'GROUP_CONCAT') - results = [ [ lit.toPython() for lit in line ] for line in results ] + results = [[lit.toPython() for lit in line] for line in results] # this is the tricky part assert results[0][2] == "1", results[0][2] @@ -24,10 +25,11 @@ def test_group_concat_distinct(): ["x2", 20, "2"], ], results + def test_sum_distinct(): g = Graph() results = g.query(query_tpl % 'SUM') - results = [ [ lit.toPython() for lit in line ] for line in results ] + results = [[lit.toPython() for lit in line] for line in results] # this is the tricky part assert results[0][2] == 1, results[0][2] @@ -38,6 +40,7 @@ def test_sum_distinct(): ["x2", 20, 2], ], results + def test_avg_distinct(): g = Graph() results = g.query(""" @@ -50,7 +53,7 @@ def test_avg_distinct(): } } GROUP BY ?x ORDER BY ?x """) - results = [ [ lit.toPython() for lit in line ] for line in results ] + results = [[lit.toPython() for lit in line] for line in results] # this is the tricky part assert results[0][2] == 2, results[0][2] @@ -61,9 +64,10 @@ def test_avg_distinct(): ["x2", 20, 2], ], results + def test_count_distinct(): g = Graph() - + g.parse(format="turtle", publicID="http://example.org/", data=""" @prefix : <> . @@ -81,7 +85,6 @@ def test_count_distinct(): """) - # Query 1: people knowing someone younger results = g.query(""" PREFIX : <http://example.org/> diff --git a/test/test_sparql_agg_undef.py b/test/test_sparql_agg_undef.py index 6786ab0c..649a5a8c 100644 --- a/test/test_sparql_agg_undef.py +++ b/test/test_sparql_agg_undef.py @@ -13,6 +13,7 @@ SELECT ?x (%s(?y_) as ?y) { Y = Variable("y") + def template_tst(agg_func, first, second): g = Graph() results = list(g.query(query_tpl % agg_func)) @@ -21,15 +22,17 @@ def template_tst(agg_func, first, second): assert results[0][1] == first, (results[0][1], first) assert results[1][1] == second, (results[1][1], second) + def test_aggregates(): yield template_tst, 'SUM', Literal(0), Literal(42) yield template_tst, 'MIN', None, Literal(42) yield template_tst, 'MAX', None, Literal(42) - #yield template_tst, 'AVG', Literal(0), Literal(42) + # yield template_tst, 'AVG', Literal(0), Literal(42) yield template_tst, 'SAMPLE', None, Literal(42) yield template_tst, 'COUNT', Literal(0), Literal(1) yield template_tst, 'GROUP_CONCAT', Literal(''), Literal("42") + def test_group_by_null(): g = Graph() results = list(g.query(""" @@ -47,4 +50,3 @@ def test_group_by_null(): assert len(results) == 2 assert results[0][0] == Literal(1) assert results[1][0] == Literal(2) - diff --git a/test/test_sparqlstore.py b/test/test_sparqlstore.py index 8eca00e6..2d7c1b48 100644 --- a/test/test_sparqlstore.py +++ b/test/test_sparqlstore.py @@ -1,3 +1,5 @@ +from rdflib import Graph, URIRef, Literal +from six.moves.urllib.request import urlopen import os import unittest from nose import SkipTest @@ -5,14 +7,11 @@ from nose import SkipTest if os.getenv("TRAVIS"): raise SkipTest("Doesn't work in travis") -from six.moves.urllib.request import urlopen try: assert len(urlopen("http://dbpedia.org/sparql").read()) > 0 except: raise SkipTest("No HTTP connection.") -from rdflib import Graph, URIRef, Literal - class SPARQLStoreDBPediaTestCase(unittest.TestCase): store_name = 'SPARQLStore' diff --git a/test/test_sparqlupdatestore.py b/test/test_sparqlupdatestore.py index 82b938aa..d72ef104 100644 --- a/test/test_sparqlupdatestore.py +++ b/test/test_sparqlupdatestore.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- - from __future__ import unicode_literals +from nose import SkipTest + import unittest import re @@ -99,16 +100,16 @@ class TestSparql11(unittest.TestCase): # 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. + # 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). + # 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)) + '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") @@ -142,8 +143,8 @@ class TestSparql11(unittest.TestCase): g = self.graph.get_context(graphuri) self.assertEqual( - set(g.triples((None,None,None))), - set([(michel,likes,pizza)]), + set(g.triples((None, None, None))), + set([(michel, likes, pizza)]), 'only michel likes pizza' ) @@ -159,8 +160,8 @@ class TestSparql11(unittest.TestCase): g = self.graph.get_context(graphuri) self.assertEqual( - set(g.triples((None,None,None))), - set([(michel,likes,pizza)]), + set(g.triples((None, None, None))), + set([(michel, likes, pizza)]), 'only michel likes pizza' ) @@ -178,8 +179,8 @@ class TestSparql11(unittest.TestCase): g = self.graph.get_context(graphuri) self.assertEqual( - set(g.triples((None,None,None))), - set([(michel,likes,pizza), (bob,likes,pizza)]), + set(g.triples((None, None, None))), + set([(michel, likes, pizza), (bob, likes, pizza)]), 'michel and bob like pizza' ) @@ -188,8 +189,8 @@ class TestSparql11(unittest.TestCase): r1 = "INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }" g.update(r1) self.assertEqual( - set(g.triples((None,None,None))), - set([(michel,likes,pizza)]), + set(g.triples((None, None, None))), + set([(michel, likes, pizza)]), 'only michel likes pizza' ) @@ -240,7 +241,8 @@ class TestSparql11(unittest.TestCase): 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])) + 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 @@ -273,10 +275,10 @@ class TestSparql11(unittest.TestCase): g = self.graph.get_context(graphuri) r = "INSERT { ?a ?b ?c } WHERE {}" g.update(r, initBindings={ - 'a': michel, - 'b': likes, - 'c': pizza - }) + 'a': michel, + 'b': likes, + 'c': pizza + }) self.assertEqual( set(g.triples((None, None, None))), set([(michel, likes, pizza)]), @@ -306,7 +308,6 @@ class TestSparql11(unittest.TestCase): o = tuple(g)[0][2] self.assertEqual(o, Literal(''), repr(o)) -from nose import SkipTest try: assert len(urlopen(HOST).read()) > 0 diff --git a/test/test_swap_n3.py b/test/test_swap_n3.py index aae1fdc0..c81378e1 100644 --- a/test/test_swap_n3.py +++ b/test/test_swap_n3.py @@ -1,3 +1,4 @@ +from nose.exc import SkipTest import os import sys import unittest @@ -39,7 +40,6 @@ qt = rdflib.Namespace("http://www.w3.org/2001/sw/DataAccess/tests/test-query#") # for tfile in tfiles: # self.graph.parse(tfile, format="n3") -from nose.exc import SkipTest skiptests = [ 'syntax_neg_single_quote', @@ -59,13 +59,17 @@ skiptests = [ # 'contexts', 'syntax_too_nested' ] + + class Envelope(object): def __init__(self, n, f): self.name = n self.file = f + def __repr__(self): return self.name + def generictest(e): """Documentation""" if e.skip: @@ -75,13 +79,14 @@ def generictest(e): g.bind(str(i), i) g.parse(e.file, format="n3") + def dir_to_uri(directory, sep=os.path.sep): ''' Convert a local path to a File URI. - + >>> dir_to_uri('c:\\\\temp\\\\foo\\\\file.txt', sep='\\\\') 'file:///c:/temp/foo/file.txt' - + >>> dir_to_uri('/tmp/foo/file.txt', sep='/') 'file:///tmp/foo/file.txt' ''' @@ -91,6 +96,7 @@ def dir_to_uri(directory, sep=os.path.sep): path = path[1:] return 'file:///%s' % (path,) + def test_cases(): from copy import deepcopy g = rdflib.Graph() @@ -101,17 +107,17 @@ def test_cases(): swap_dir_uri = dir_to_uri(swap_dir) + '/' for tst in g.subjects(): files = [str(tfile).replace('http://www.w3.org/2000/10/', swap_dir_uri) - for tfile in g.objects(tst, rdflib.URIRef("http://www.w3.org/2004/11/n3test#inputDocument")) if tfile.endswith('n3')] + for tfile in g.objects(tst, rdflib.URIRef("http://www.w3.org/2004/11/n3test#inputDocument")) if tfile.endswith('n3')] tfiles += files for tfile in set(tfiles): gname = tfile.split('/swap-n3/swap/test/')[1][:-3].translate(maketrans('-/','__')) e = Envelope(gname, tfile) if gname in skiptests: - e.skip = True + e.skip = True else: e.skip = False # e.skip = True - if sys.version_info[:2] == (2,4): + if sys.version_info[:2] == (2, 4): import pickle gjt = pickle.dumps(generictest) gt = pickle.loads(gjt) diff --git a/test/test_term.py b/test/test_term.py index 432b7e78..c222a8d2 100644 --- a/test/test_term.py +++ b/test/test_term.py @@ -12,9 +12,10 @@ from rdflib.namespace import XSD from six import PY3 + def uformat(s): if PY3: - return s.replace("u'","'") + return s.replace("u'", "'") return s @@ -32,10 +33,10 @@ class TestURIRefRepr(unittest.TestCase): def testGracefulOrdering(self): u = URIRef('cake') g = Graph() - a = u>u - a = u>BNode() - a = u>QuotedGraph(g.store, u) - a = u>g + a = u > u + a = u > BNode() + a = u > QuotedGraph(g.store, u) + a = u > g class TestBNodeRepr(unittest.TestCase): @@ -74,9 +75,9 @@ class TestLiteral(unittest.TestCase): '00:00:00-00:00' ), XSD.gYear: ( - '2001', - '2001Z', - '2001-00:00' + '2001', + '2001Z', + '2001-00:00' ), # interval XSD.gYearMonth: ( '2001-01', diff --git a/test/test_trig.py b/test/test_trig.py index 59c4e818..dff6269d 100644 --- a/test/test_trig.py +++ b/test/test_trig.py @@ -9,48 +9,49 @@ TRIPLE = (rdflib.URIRef("http://example.com/s"), rdflib.RDFS.label, rdflib.Literal("example 1")) + class TestTrig(unittest.TestCase): def testEmpty(self): - g=rdflib.Graph() - s=g.serialize(format='trig') + g = rdflib.Graph() + s = g.serialize(format='trig') self.assertTrue(s is not None) def testRepeatTriples(self): - g=rdflib.ConjunctiveGraph() - g.get_context('urn:a').add(( rdflib.URIRef('urn:1'), - rdflib.URIRef('urn:2'), - rdflib.URIRef('urn:3') )) + g = rdflib.ConjunctiveGraph() + g.get_context('urn:a').add((rdflib.URIRef('urn:1'), + rdflib.URIRef('urn:2'), + rdflib.URIRef('urn:3'))) - g.get_context('urn:b').add(( rdflib.URIRef('urn:1'), - rdflib.URIRef('urn:2'), - rdflib.URIRef('urn:3') )) + g.get_context('urn:b').add((rdflib.URIRef('urn:1'), + rdflib.URIRef('urn:2'), + rdflib.URIRef('urn:3'))) - self.assertEqual(len(g.get_context('urn:a')),1) - self.assertEqual(len(g.get_context('urn:b')),1) + self.assertEqual(len(g.get_context('urn:a')), 1) + self.assertEqual(len(g.get_context('urn:b')), 1) - s=g.serialize(format='trig') - self.assertTrue(b('{}') not in s) # no empty graphs! + s = g.serialize(format='trig') + self.assertTrue(b('{}') not in s) # no empty graphs! def testSameSubject(self): - g=rdflib.ConjunctiveGraph() - g.get_context('urn:a').add(( rdflib.URIRef('urn:1'), - rdflib.URIRef('urn:p1'), - rdflib.URIRef('urn:o1') )) + g = rdflib.ConjunctiveGraph() + g.get_context('urn:a').add((rdflib.URIRef('urn:1'), + rdflib.URIRef('urn:p1'), + rdflib.URIRef('urn:o1'))) - g.get_context('urn:b').add(( rdflib.URIRef('urn:1'), - rdflib.URIRef('urn:p2'), - rdflib.URIRef('urn:o2') )) + g.get_context('urn:b').add((rdflib.URIRef('urn:1'), + rdflib.URIRef('urn:p2'), + rdflib.URIRef('urn:o2'))) - self.assertEqual(len(g.get_context('urn:a')),1) - self.assertEqual(len(g.get_context('urn:b')),1) + self.assertEqual(len(g.get_context('urn:a')), 1) + self.assertEqual(len(g.get_context('urn:b')), 1) - s=g.serialize(format='trig') + s = g.serialize(format='trig') self.assertEqual(len(re.findall(b("p1"), s)), 1) self.assertEqual(len(re.findall(b("p2"), s)), 1) - self.assertTrue(b('{}') not in s) # no empty graphs! + self.assertTrue(b('{}') not in s) # no empty graphs! def testRememberNamespace(self): g = rdflib.ConjunctiveGraph() diff --git a/test/test_trig_w3c.py b/test/test_trig_w3c.py index 1acaf4b5..bb8588e0 100644 --- a/test/test_trig_w3c.py +++ b/test/test_trig_w3c.py @@ -11,25 +11,26 @@ from .testutils import nose_tst_earl_report verbose = False + def trig(test): g = ConjunctiveGraph() try: - base = 'http://www.w3.org/2013/TriGTests/'+split_uri(test.action)[1] + base = 'http://www.w3.org/2013/TriGTests/' + split_uri(test.action)[1] g.parse(test.action, publicID=base, format='trig') if not test.syntax: raise AssertionError("Input shouldn't have parsed!") - if test.result: # eval test + if test.result: # eval test res = ConjunctiveGraph() res.parse(test.result, format='nquads') if verbose: - - both, first, second = graph_diff(g,res) - if not first and not second: return + both, first, second = graph_diff(g, res) + if not first and not second: + return print('===============================') print('TriG') @@ -40,7 +41,7 @@ def trig(test): print('===============================') print("Diff:") - #print "%d triples in both"%len(both) + # print "%d triples in both"%len(both) print("TriG Only:") for t in first: print(t) @@ -57,6 +58,7 @@ def trig(test): if test.syntax: raise + testers = { RDFT.TestTrigPositiveSyntax: trig, RDFT.TestTrigNegativeSyntax: trig, @@ -64,11 +66,13 @@ testers = { RDFT.TestTrigNegativeEval: trig } + def test_trig(tests=None): for t in nose_tests(testers, 'test/w3c/trig/manifest.ttl'): if tests: for test in tests: - if test in t[1].uri: break + if test in t[1].uri: + break else: continue diff --git a/test/test_trix_parse.py b/test/test_trix_parse.py index 225be937..1b0f9fb9 100644 --- a/test/test_trix_parse.py +++ b/test/test_trix_parse.py @@ -4,6 +4,7 @@ from rdflib.graph import ConjunctiveGraph import unittest + class TestTrixParse(unittest.TestCase): def setUp(self): @@ -12,37 +13,37 @@ class TestTrixParse(unittest.TestCase): def tearDown(self): pass - def testAperture(self): + 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.assertEqual(t, 24) + self.assertEqual(len(c), 4) + + # print "Parsed %d triples"%t + + def testSpec(self): + + g = ConjunctiveGraph() - g=ConjunctiveGraph() + g.parse("test/trix/nokia_example.trix", format="trix") - g.parse("test/trix/aperture.trix",format="trix") - c=list(g.contexts()) + # print "Parsed %d triples"%len(g) - #print list(g.contexts()) - t=sum(map(len, g.contexts())) + def testNG4j(self): - self.assertEqual(t,24) - self.assertEqual(len(c),4) - - #print "Parsed %d triples"%t + g = ConjunctiveGraph() - def testSpec(self): + g.parse("test/trix/ng4jtest.trix", format="trix") - g=ConjunctiveGraph() - - g.parse("test/trix/nokia_example.trix",format="trix") - - #print "Parsed %d triples"%len(g) - - def testNG4j(self): + # print "Parsed %d triples"%len(g) - g=ConjunctiveGraph() - - g.parse("test/trix/ng4jtest.trix",format="trix") - - #print "Parsed %d triples"%len(g) -if __name__=='__main__': +if __name__ == '__main__': unittest.main() - diff --git a/test/test_turtle_serialize.py b/test/test_turtle_serialize.py index e3fb018f..0b602b34 100644 --- a/test/test_turtle_serialize.py +++ b/test/test_turtle_serialize.py @@ -12,8 +12,8 @@ def testTurtleFinalDot(): g = Graph() u = URIRef("http://ex.org/bob.") g.bind("ns", "http://ex.org/") - g.add( (u, u, u) ) - s=g.serialize(format='turtle') + g.add((u, u, u)) + s = g.serialize(format='turtle') assert b("ns:bob.") not in s @@ -71,5 +71,6 @@ def test_turtle_valid_list(): if __name__ == "__main__": - import nose, sys + import nose + import sys nose.main(defaultTest=sys.argv[0]) diff --git a/test/test_turtle_sort_issue613.py b/test/test_turtle_sort_issue613.py index 813ce5b9..f81cba33 100644 --- a/test/test_turtle_sort_issue613.py +++ b/test/test_turtle_sort_issue613.py @@ -20,7 +20,7 @@ def test_sort_dates(): y = '''@prefix ex: <http://ex.org> . ex:X ex:p "2016-01-01T00:00:00"^^<http://www.w3.org/2001/XMLSchema#dateTime>, "2016-01-01T00:00:00Z"^^<http://www.w3.org/2001/XMLSchema#dateTime> . ''' - p=g.parse(data=y, format="turtle") + p = g.parse(data=y, format="turtle") p.serialize(format="turtle") @@ -31,9 +31,10 @@ def test_sort_docfrag(): @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . ex:X ex:p "<h1>hi</h1>"^^rdf:HTML, "<h1>ho</h1>"^^rdf:HTML . ''' - p=g.parse(data=y, format="turtle") + p = g.parse(data=y, format="turtle") p.serialize(format="turtle") + if __name__ == '__main__': test_sort_docfrag() diff --git a/test/test_turtle_w3c.py b/test/test_turtle_w3c.py index adeb0868..469ed023 100644 --- a/test/test_turtle_w3c.py +++ b/test/test_turtle_w3c.py @@ -10,25 +10,27 @@ from .testutils import nose_tst_earl_report verbose = False + def turtle(test): g = Graph() try: - base = 'http://www.w3.org/2013/TurtleTests/'+split_uri(test.action)[1] + base = 'http://www.w3.org/2013/TurtleTests/' + split_uri(test.action)[1] g.parse(test.action, publicID=base, format='turtle') if not test.syntax: raise AssertionError("Input shouldn't have parsed!") - if test.result: # eval test + if test.result: # eval test res = Graph() res.parse(test.result, format='nt') if verbose: - both, first, second = graph_diff(g,res) - if not first and not second: return + both, first, second = graph_diff(g, res) + if not first and not second: + return print("Diff:") - #print "%d triples in both"%len(both) + # print "%d triples in both"%len(both) print("Turtle Only:") for t in first: print(t) @@ -41,11 +43,11 @@ def turtle(test): assert isomorphic(g, res), 'graphs must be the same' - except: if test.syntax: raise + testers = { RDFT.TestTurtlePositiveSyntax: turtle, RDFT.TestTurtleNegativeSyntax: turtle, @@ -53,12 +55,14 @@ testers = { RDFT.TestTurtleNegativeEval: turtle } -def test_turtle(tests = None): + +def test_turtle(tests=None): for t in nose_tests(testers, 'test/w3c/turtle/manifest.ttl'): if tests: for test in tests: - if test in t[1].uri: break + if test in t[1].uri: + break else: continue diff --git a/test/test_util.py b/test/test_util.py index a95caa06..61e5b33c 100644 --- a/test/test_util.py +++ b/test/test_util.py @@ -11,7 +11,7 @@ from rdflib import XSD from rdflib.exceptions import SubjectTypeError from rdflib.exceptions import PredicateTypeError from rdflib.exceptions import ObjectTypeError -from rdflib.exceptions import ContextTypeError +from rdflib.exceptions import ContextTypeError n3source = """\ @prefix : <http://www.w3.org/2000/10/swap/Primer#>. @@ -47,7 +47,8 @@ n3source = """\ :Woman = foo:FemaleAdult . :Title a rdf:Property; = dc:title . -""" # --- End of primer code +""" # --- End of primer code + class TestUtilMisc(unittest.TestCase): def setUp(self): @@ -56,20 +57,21 @@ class TestUtilMisc(unittest.TestCase): def test_util_list2set(self): base = [Literal('foo'), self.x] - r = util.list2set(base+base) + r = util.list2set(base + base) self.assertTrue(r == base) def test_util_uniq(self): base = ["michel", "hates", "pizza"] - r = util.uniq(base+base) + r = util.uniq(base + base) self.assertEqual(sorted(r), sorted(base)) base = ["michel", "hates", "pizza"] - r = util.uniq(base+base, strip=True) + r = util.uniq(base + base, strip=True) self.assertEqual(sorted(r), sorted(base)) def test_coverage_dodge(self): util.test() + class TestUtilDateTime(unittest.TestCase): def setUp(self): @@ -108,6 +110,7 @@ class TestUtilDateTime(unittest.TestCase): def test_util_date_timewithtoutz(self): t = time.time() + def ablocaltime(t): from time import gmtime res = gmtime(t) @@ -116,6 +119,7 @@ class TestUtilDateTime(unittest.TestCase): res = util.date_time(t, local_time_zone=True) self.assertTrue(res is not t) + class TestUtilTermConvert(unittest.TestCase): def setUp(self): self.x = Literal("2008-12-01T18:02:00Z", @@ -162,7 +166,6 @@ class TestUtilTermConvert(unittest.TestCase): default = "TestofDefault" res = util.from_n3(s, default=default, backend=None) self.assertTrue(res == default) - def test_util_from_n3_expectdefaultbnode(self): s = "michel" @@ -205,7 +208,7 @@ class TestUtilTermConvert(unittest.TestCase): s = '42' res = util.from_n3(s) self.assertEqual(res, Literal(42)) - + def test_util_from_n3_expectliteralwithdatatypefrombool(self): s = 'true' res = util.from_n3(s) @@ -213,12 +216,12 @@ class TestUtilTermConvert(unittest.TestCase): s = 'false' res = util.from_n3(s) self.assertEqual(res, Literal(False)) - + def test_util_from_n3_expectliteralmultiline(self): s = '"""multi\nline\nstring"""@en' res = util.from_n3(s, default=None, backend=None) self.assertTrue(res, Literal('multi\nline\nstring', lang='en')) - + def test_util_from_n3_expectliteralwithescapedquote(self): s = '"\\""' res = util.from_n3(s, default=None, backend=None) @@ -229,15 +232,15 @@ class TestUtilTermConvert(unittest.TestCase): res = util.from_n3(s) self.assertTrue(res, Literal('trailing\\', datatype=XSD['string'])) self.assertTrue(res.n3(), s) - + def test_util_from_n3_expectpartialidempotencewithn3(self): for n3 in ('<http://ex.com/foo>', '"foo"@de', - #'"\\""', # exception as '\\"' --> '"' by orig parser as well + # '"\\""', # exception as '\\"' --> '"' by orig parser as well '"""multi\n"line"\nstring"""@en'): self.assertEqual(util.from_n3(n3).n3(), n3, 'from_n3(%(n3e)r).n3() != %(n3e)r' % {'n3e': n3}) - + def test_util_from_n3_expectsameasn3parser(self): def parse_n3(term_n3): ''' Disclaimer: Quick and dirty hack using the n3 parser. ''' @@ -246,28 +249,26 @@ class TestUtilTermConvert(unittest.TestCase): g = ConjunctiveGraph() g.parse(data=prepstr, format='n3') return [t for t in g.triples((None, None, None))][0][2] - - for n3 in (# "michel", # won't parse in original parser - # "_:michel", # BNodes won't be the same - '"michel"', - '<http://example.org/schema>', - '"michel"@fr', - # '"michel"@fr^^xsd:fr', # FIXME: invalid n3, orig parser will prefer datatype - # '"true"^^xsd:boolean', # FIXME: orig parser will expand xsd prefix - '42', - 'true', - 'false', - '"""multi\nline\nstring"""@en', - '<http://ex.com/foo>', - '"foo"@de', - '"\\""@en', - '"""multi\n"line"\nstring"""@en'): + + for n3 in ( # "michel", # won't parse in original parser + # "_:michel", # BNodes won't be the same + '"michel"', + '<http://example.org/schema>', + '"michel"@fr', + # '"michel"@fr^^xsd:fr', # FIXME: invalid n3, orig parser will prefer datatype + # '"true"^^xsd:boolean', # FIXME: orig parser will expand xsd prefix + '42', + 'true', + 'false', + '"""multi\nline\nstring"""@en', + '<http://ex.com/foo>', + '"foo"@de', + '"\\""@en', + '"""multi\n"line"\nstring"""@en'): res, exp = util.from_n3(n3), parse_n3(n3) self.assertEqual(res, exp, - 'from_n3(%(n3e)r): %(res)r != parser.notation3: %(exp)r' % { - 'res': res, 'exp': exp, 'n3e':n3}) - - + 'from_n3(%(n3e)r): %(res)r != parser.notation3: %(exp)r' % { + 'res': res, 'exp': exp, 'n3e': n3}) def test_util_from_n3_expectquotedgraph(self): s = '{<http://example.com/schema>}' @@ -279,6 +280,7 @@ class TestUtilTermConvert(unittest.TestCase): res = util.from_n3(s, default=None, backend="IOMemory") self.assertTrue(isinstance(res, Graph)) + class TestUtilCheckers(unittest.TestCase): def setUp(self): self.c = URIRef("http://example.com") @@ -288,10 +290,10 @@ class TestUtilCheckers(unittest.TestCase): def test_util_checker_exceptions(self): c = "http://example.com" - self.assertRaises(ContextTypeError, util.check_context, c) - self.assertRaises(SubjectTypeError, util.check_subject, c) - self.assertRaises(PredicateTypeError, util.check_predicate, c) - self.assertRaises(ObjectTypeError, util.check_object, c) + self.assertRaises(ContextTypeError, util.check_context, c) + self.assertRaises(SubjectTypeError, util.check_subject, c) + self.assertRaises(PredicateTypeError, util.check_predicate, c) + self.assertRaises(ObjectTypeError, util.check_object, c) def test_util_check_context(self): res = util.check_context(self.c) @@ -300,7 +302,7 @@ class TestUtilCheckers(unittest.TestCase): def test_util_check_subject(self): res = util.check_subject(self.s) self.assertTrue(res == None) - + def test_util_check_predicate(self): res = util.check_predicate(self.p) self.assertTrue(res == None) @@ -308,41 +310,41 @@ class TestUtilCheckers(unittest.TestCase): def test_util_check_object(self): res = util.check_object(self.o) self.assertTrue(res == None) - + def test_util_check_statement(self): c = "http://example.com" self.assertRaises( - SubjectTypeError, - util.check_statement, - (c, self.p, self.o)) + SubjectTypeError, + util.check_statement, + (c, self.p, self.o)) self.assertRaises( - PredicateTypeError, - util.check_statement, - (self.s, c, self.o)) + PredicateTypeError, + util.check_statement, + (self.s, c, self.o)) self.assertRaises( - ObjectTypeError, - util.check_statement, - (self.s, self.p, c)) + ObjectTypeError, + util.check_statement, + (self.s, self.p, c)) res = util.check_statement((self.s, self.p, self.o)) self.assertTrue(res == None) - + def test_util_check_pattern(self): c = "http://example.com" self.assertRaises( - SubjectTypeError, - util.check_pattern, - (c, self.p, self.o)) + SubjectTypeError, + util.check_pattern, + (c, self.p, self.o)) self.assertRaises( - PredicateTypeError, - util.check_pattern, - (self.s, c, self.o)) + PredicateTypeError, + util.check_pattern, + (self.s, c, self.o)) self.assertRaises( - ObjectTypeError, - util.check_pattern, - (self.s, self.p, c)) + ObjectTypeError, + util.check_pattern, + (self.s, self.p, c)) res = util.check_pattern((self.s, self.p, self.o)) self.assertTrue(res == None) + if __name__ == "__main__": unittest.main() - diff --git a/test/test_xmlliterals.py b/test/test_xmlliterals.py index fe70996b..b467e82a 100644 --- a/test/test_xmlliterals.py +++ b/test/test_xmlliterals.py @@ -1,32 +1,32 @@ import rdflib from rdflib import RDF, Graph, Literal -def testPythonRoundtrip(): - l1=Literal('<msg>hello</msg>', datatype=RDF.XMLLiteral) + +def testPythonRoundtrip(): + l1 = Literal('<msg>hello</msg>', datatype=RDF.XMLLiteral) assert l1.value is not None, 'xml must have been parsed' - assert l1.datatype==RDF.XMLLiteral, 'literal must have right datatype' + assert l1.datatype == RDF.XMLLiteral, 'literal must have right datatype' - l2=Literal('<msg>good morning</msg>', datatype=RDF.XMLLiteral) + l2 = Literal('<msg>good morning</msg>', datatype=RDF.XMLLiteral) assert l2.value is not None, 'xml must have been parsed' - assert not l1.eq(l2), 'literals must NOT be equal' + assert not l1.eq(l2), 'literals must NOT be equal' - l3=Literal(l1.value) + l3 = Literal(l1.value) assert l1.eq(l3), 'roundtripped literals must be equal' - assert l3.datatype==RDF.XMLLiteral, 'literal must have right datatype' + assert l3.datatype == RDF.XMLLiteral, 'literal must have right datatype' - l4=Literal('<msg >hello</msg>', datatype=RDF.XMLLiteral) - assert l1==l4 + l4 = Literal('<msg >hello</msg>', datatype=RDF.XMLLiteral) + assert l1 == l4 assert l1.eq(l4) - rdflib.NORMALIZE_LITERALS=False - l4=Literal('<msg >hello</msg>', datatype=RDF.XMLLiteral) - assert l1!=l4 + rdflib.NORMALIZE_LITERALS = False + l4 = Literal('<msg >hello</msg>', datatype=RDF.XMLLiteral) + assert l1 != l4 assert l1.eq(l4) - rdflib.NORMALIZE_LITERALS=True - + rdflib.NORMALIZE_LITERALS = True -def testRDFXMLParse(): +def testRDFXMLParse(): rdfxml = """\ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" @@ -41,42 +41,44 @@ def testRDFXMLParse(): </rdf:RDF>""" - g=rdflib.Graph() + g = rdflib.Graph() g.parse(data=rdfxml) - l1=list(g)[0][2] - assert l1.datatype==RDF.XMLLiteral + l1 = list(g)[0][2] + assert l1.datatype == RDF.XMLLiteral + def graph(): - g=rdflib.Graph() - g.add(( rdflib.URIRef('http://example.org/a'), - rdflib.URIRef('http://example.org/p'), - rdflib.Literal('<msg>hei</hei>', datatype=RDF.XMLLiteral))) + g = rdflib.Graph() + g.add((rdflib.URIRef('http://example.org/a'), + rdflib.URIRef('http://example.org/p'), + rdflib.Literal('<msg>hei</hei>', datatype=RDF.XMLLiteral))) return g + def roundtrip(fmt): - g1=graph() - l1=list(g1)[0][2] - g2=rdflib.Graph() + g1 = graph() + l1 = list(g1)[0][2] + g2 = rdflib.Graph() g2.parse(data=g1.serialize(format=fmt), format=fmt) - l2=list(g2)[0][2] + l2 = list(g2)[0][2] assert l1.eq(l2) - -def testRoundtrip(): + + +def testRoundtrip(): roundtrip('xml') roundtrip('n3') roundtrip('nt') def testHTML(): - - l1=Literal('<msg>hello</msg>', datatype=RDF.XMLLiteral) + + l1 = Literal('<msg>hello</msg>', datatype=RDF.XMLLiteral) assert l1.value is not None, 'xml must have been parsed' - assert l1.datatype==RDF.XMLLiteral, 'literal must have right datatype' + assert l1.datatype == RDF.XMLLiteral, 'literal must have right datatype' - l2=Literal('<msg>hello</msg>', datatype=RDF.HTML) + l2 = Literal('<msg>hello</msg>', datatype=RDF.HTML) assert l2.value is not None, 'xml must have been parsed' - assert l2.datatype==RDF.HTML, 'literal must have right datatype' + assert l2.datatype == RDF.HTML, 'literal must have right datatype' - assert l1!=l2 + assert l1 != l2 assert not l1.eq(l2) - diff --git a/test/testutils.py b/test/testutils.py index 6e044e6c..02bc4b23 100644 --- a/test/testutils.py +++ b/test/testutils.py @@ -21,15 +21,19 @@ def crapCompare(g1, g2): for t in g1: s = _no_blank(t[0]) o = _no_blank(t[2]) - if not (s, t[1] ,o) in g2: - e = "(%s, %s, %s) is not in both graphs!"%(s, t[1], o) + if not (s, t[1], o) in g2: + e = "(%s, %s, %s) is not in both graphs!" % (s, t[1], o) raise Exception(e) + + def _no_blank(node): - if isinstance(node, BNode): return None + if isinstance(node, BNode): + return None if isinstance(node, Graph): - return None #node._Graph__identifier = _SQUASHED_NODE + return None # node._Graph__identifier = _SQUASHED_NODE return node + def check_serialize_parse(fpath, infmt, testfmt, verbose=False): g = ConjunctiveGraph() _parse_or_report(verbose, g, fpath, format=infmt) @@ -45,7 +49,7 @@ def check_serialize_parse(fpath, infmt, testfmt, verbose=False): _parse_or_report(verbose, g2, data=s, format=testfmt) if verbose: print(g2.serialize()) - crapCompare(g,g2) + crapCompare(g, g2) def _parse_or_report(verbose, graph, *args, **kwargs): diff --git a/test/triple_store.py b/test/triple_store.py index 7e18c851..b9c5221a 100644 --- a/test/triple_store.py +++ b/test/triple_store.py @@ -30,7 +30,6 @@ class GraphTest(unittest.TestCase): for s, p, o in self.store: pass + if __name__ == "__main__": unittest.main() - - diff --git a/test/type_check.py b/test/type_check.py index 16a0f1b8..605f0916 100644 --- a/test/type_check.py +++ b/test/type_check.py @@ -10,7 +10,7 @@ foo = URIRef("foo") class TypeCheckCase(unittest.TestCase): - unstable = True # TODO: until we decide if we want to add type checking back to rdflib + unstable = True # TODO: until we decide if we want to add type checking back to rdflib backend = 'default' path = 'store' |