#!/usr/bin/python # # test.py - RDFa Test Suite # test import os, sys, string, getopt import rdfdiff import unittest import ntriples import RDF import rdfa def usage(): print """ Usage: %s [OPTIONS] Standard arguments: -d, --data Directory containing test manifest.ttl files. -s, --service Execute query at given service. -h, --help Display this help message. Examples: python test.py -s http://sparql.org/sparql """ % sys.argv[:1].pop() def main(): testdir = "../tests" verbose = False try: opts, args = getopt.getopt(sys.argv[1:], "hds:", ["data", "service=", "help"]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ('-d', '--testdir'): testdir = arg suite = unittest.TestSuite() tests = [os.path.splitext(f)[0] for f in os.listdir(testdir) if os.path.splitext(f)[1] == ".htm" ] tests.sort() for testname in tests: suite.addTest(RDFaTestStub(os.path.abspath(os.path.join(testdir,testname)))) unittest.TextTestRunner(verbosity=2,descriptions=1).run(suite) def nodeToString(node): if node.is_blank(): return ntriples.bNode(node.blank_identifier) elif node.is_resource(): return ntriples.URI(str(node.uri)) elif node.is_literal(): lit = node.literal_value return ntriples.Literal(lit['string'], lang= lit['language'] or None, dtype= str(lit['datatype']) or None) def graphToString(graph): from cStringIO import StringIO file_str = StringIO() for t in graph.triples: file_str.write("%s\n" % str(t)) return file_str.getvalue() def toGraph(content, base_uri): graph = rdfdiff.Graph() parser = RDF.Parser(name="turtle") if hasattr(content, 'read'): content = content.read() elif os.path.isfile(str(content)): content = open(content).read() else: content = str(content) for s in parser.parse_string_as_stream(content, "file://" + base_uri): graph.triples.add(tuple(map(nodeToString, (s.subject, s.predicate, s.object)))) return graph class RDFaTestStub(unittest.TestCase): def __init__(self, testbase): unittest.TestCase.__init__(self) self.testbase = testbase def shortDescription(self): return str(os.path.basename(self.testbase)) def runTest(self): testfile = self.testbase + ".htm" resultsf = self.testbase + ".ttl" self.failIf(not os.path.isfile(resultsf), "missing expected results file.") p = toGraph(resultsf, resultsf) results = rdfa.parseRDFa(open(testfile).read()) q = toGraph(results, resultsf) self.failIf(not hash(p) == hash(q), "results do not match.\n%s\n\n%s" % (graphToString(p),graphToString(q))) if __name__ == '__main__': main()