#!/usr/bin/env python """ Test harness for GRDDL test suite. Uses RDFLib to process test manifest and perform graph isomorphism testing against expected output. Uses Sean B. Palmer's RDF Graph Isomorphism Tester Copyright (c) 2006, Sean B. Palmer, Chimezie Ogbuji All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of inamidst.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [ a e:Assertion; e:assertedBy [ foaf:homepage ]; e:testSubject ; e:test [ = ; a e:TestCase ]; e:testResult [ a e:TestResult; e:validity e:pass ] ] . """ from pprint import pprint from sets import Set from rdflib.Namespace import Namespace from rdflib import plugin,RDF,RDFS,URIRef,URIRef,Literal,Variable,BNode from rdflib.store import Store from cStringIO import StringIO from rdflib.Graph import Graph,ReadOnlyGraphAggregate,ConjunctiveGraph import sys, getopt import os, tempfile import urllib2 DC_NS = Namespace('http://purl.org/dc/elements/1.1/') def compare(p, q): return hash(Graph(p)) == hash(Graph(q)) 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 def internal_hash(self): """ This is defined instead of __hash__ to avoid a circular recursion scenario with the Memory store for rdflib which requires a hash lookup in order to return a generator of triples """ return hash(tuple(sorted(self.hashtriples()))) def hashtriples(self): for triple in self.triplesCache: g = ((isinstance(t,BNode) and self.vhash(t)) or t for t in triple) yield hash(tuple(g)) def vhash(self, term, done=False): return tuple(sorted(self.vhashtriples(term, done))) def vhashtriples(self, term, done): for t in self.triplesCache: if term in t: yield tuple(self.vhashtriple(t, term, done)) def vhashtriple(self, triple, term, done): for p in xrange(3): if not isinstance(triple[p], BNode): yield triple[p] elif done or (triple[p] == term): yield p else: yield self.vhash(triple[p], done=True) def __eq__(self, G): """Graph isomorphism testing.""" if not isinstance(G, IsomorphicTestableGraph): return False elif len(self) != len(G): return False elif list.__eq__(list(self),list(G)): return True # @@ return self.internal_hash() == G.internal_hash() def __ne__(self, G): """Negative graph isomorphism testing.""" return not self.__eq__(G) def runProcessor(processor,inputUri): if DEBUG: print "running: ", processor + " " + inputUri return os.popen(processor + " " + inputUri,"r") def updateTest(processor,inputUri,outputUri): outputfilename = outputUri[outputUri.rfind('/')+1:] print "Updating ",outputfilename outputfile = open(outputfilename,"w") output = runProcessor(processor,inputUri) outputfile.write(output.read()) outputfile.close() # Returns false when applying processor on inputUri differs from outputUri def runTest(processor,inputUri,outputUri): output = runProcessor(processor,inputUri) outputfilename = outputUri[outputUri.rfind('/')+1:] + ".result" if DEBUG: print "Saving result to ",outputfilename outputfile = open(outputfilename,"w") outputfile.write(output.read()) outputfile.close() expected = IsomorphicTestableGraph().parse(outputUri) try: actual = IsomorphicTestableGraph().parse(outputfilename) except: if DEBUG: print "problems parsing result" return False if len(actual) != len(expected): if DEBUG: print "Unequal lengths: expected = %s actual = %s"%(len(expected),len(actual)) rt = actual == expected if DEBUG and actual != expected: print "Missing: " pprint(list(Set(list(expected)).difference(list(actual)))) return rt def process(action,uri,processor): data = Graph() data.parse(uri) nsMapping = { u'test':Namespace('http://www.w3.org/2000/10/rdf-tests/rdfcore/testSchema#'), u'dc':DC_NS } hasFailure = 0 for descr,test,input,output in data.query("SELECT ?desc ?t ?i ?o WHERE { ?t test:inputDocument ?i. ?t a test:Test . ?t dc:title ?desc. ?t test:outputDocument ?o }",initNs=nsMapping): if DEBUG: print "###", descr, "###" print "\t",input if action=="update": updateTest(processor,input,output) elif action=="run": if not runTest(processor,input,output): print "* %s failed" % test hasFailure = 1 if not hasFailure and action=="run": print "All tests were passed!" def main(argv=None): if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], "dhr:u:", ["help", "run=", "update=","debug"]) except getopt.GetoptError: usage() return 2 processor = None action = None tests = None global DEBUG DEBUG=0 for o, a in opts: if o in ("-d", "--debug"): DEBUG = 1 if o in ("-h", "--help"): usage() return 0 if o in ("-r", "--run"): processor = a action = "run" if o in ("-u", "--update"): processor = a action = "update" if not (processor and action and len(args) == 1): usage() return 2 # URI of the list of tests tests = args[0] process(action,tests,processor) return 0 def usage(): print __doc__ print __version__ if __name__ == '__main__': sys.exit(main())