summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGunnar Aastrand Grimnes <gromgull@gmail.com>2016-11-21 16:37:05 +0100
committerGunnar Aastrand Grimnes <gromgull@gmail.com>2017-01-30 17:43:04 +0100
commitc267023ff0a1e89e511ea0b5d138ffcae059444b (patch)
treeb224f7620881804514c18151fa0c97e18b4875e6
parent8bf3523652614337b8b2a12ff9820caeff74a2eb (diff)
downloadrdflib-c267023ff0a1e89e511ea0b5d138ffcae059444b.tar.gz
converted all tests
-rw-r--r--rdflib/py3compat.py11
-rw-r--r--setup.py130
-rw-r--r--test/manifest.py7
-rw-r--r--test/rdfa/run_w3c_rdfa_testsuite.py17
-rw-r--r--test/rdfa/test_non_xhtml.py2
-rw-r--r--test/store_performance.py14
-rw-r--r--test/test_aggregate_graphs.py2
-rw-r--r--test/test_bnode_ncname.py6
-rw-r--r--test/test_canonicalization.py63
-rw-r--r--test/test_conneg.py10
-rw-r--r--test/test_dataset.py12
-rw-r--r--test/test_datetime.py6
-rw-r--r--test/test_dawg.py160
-rw-r--r--test/test_empty_xml_base.py3
-rw-r--r--test/test_events.py4
-rw-r--r--test/test_expressions.py2
-rw-r--r--test/test_extras_external_graph_libs.py9
-rw-r--r--test/test_graph_items.py2
-rw-r--r--test/test_issue084.py6
-rw-r--r--test/test_issue154.py3
-rw-r--r--test/test_issue363.py2
-rw-r--r--test/test_issue379.py4
-rw-r--r--test/test_literal.py3
-rw-r--r--test/test_n3.py8
-rw-r--r--test/test_n3_suite.py2
-rw-r--r--test/test_nquads_w3c.py4
-rw-r--r--test/test_nt_misc.py8
-rw-r--r--test/test_nt_w3c.py4
-rw-r--r--test/test_parser_helpers.py16
-rw-r--r--test/test_parser_structure.py2
-rw-r--r--test/test_prefixTypes.py2
-rw-r--r--test/test_prettyxml.py7
-rw-r--r--test/test_rdf_lists.py2
-rw-r--r--test/test_rdfxml.py17
-rw-r--r--test/test_roundtrip.py22
-rw-r--r--test/test_rules.py4
-rw-r--r--test/test_serializexml.py6
-rw-r--r--test/test_sparql.py2
-rw-r--r--test/test_sparql_agg_undef.py2
-rw-r--r--test/test_sparqlstore.py4
-rw-r--r--test/test_sparqlupdatestore.py45
-rw-r--r--test/test_trig_w3c.py30
-rw-r--r--test/test_trix_serialize.py7
-rw-r--r--test/test_tsvresults.py2
-rw-r--r--test/test_turtle_serialize.py4
-rw-r--r--test/test_turtle_w3c.py16
-rw-r--r--test/testutils.py31
47 files changed, 363 insertions, 362 deletions
diff --git a/rdflib/py3compat.py b/rdflib/py3compat.py
index fc4e21ec..bc09bc63 100644
--- a/rdflib/py3compat.py
+++ b/rdflib/py3compat.py
@@ -45,8 +45,19 @@ from six.moves.urllib.request import url2pathname
from six.moves.urllib.request import urlopen
from six.moves.urllib.request import build_opener
+from six.moves.urllib.error import URLError
from six.moves.urllib.error import HTTPError
+
from six.moves.BaseHTTPServer import BaseHTTPRequestHandler
+from six.moves.BaseHTTPServer import HTTPServer
+
+if PY3:
+ import _thread as thread
+ from html.entities import name2codepoint
+else:
+ import thread
+ from htmlentitydefs import name2codepoint
+
try:
from functools import wraps
diff --git a/setup.py b/setup.py
index 90e1eeb8..07902a2a 100644
--- a/setup.py
+++ b/setup.py
@@ -155,89 +155,89 @@ def setup_python3():
join(tmp_src, 'run_tests.py'),
join(tmp_src, 'test', '__init__.py'),
join(tmp_src, 'test', 'earl.py'),
- # join(tmp_src, 'test', 'manifest.py'),
+ join(tmp_src, 'test', 'manifest.py'),
join(tmp_src, 'test', 'rdfa', '__init__.py'),
- # join(tmp_src, 'test', 'rdfa', 'run_w3c_rdfa_testsuite.py'),
- # join(tmp_src, 'test', 'rdfa', 'test_non_xhtml.py'),
- # join(tmp_src, 'test', 'store_performance.py'),
- # join(tmp_src, 'test', 'test_aggregate_graphs.py'),
- # join(tmp_src, 'test', 'test_bnode_ncname.py'),
- # join(tmp_src, 'test', 'test_comparison.py'),
- # join(tmp_src, 'test', 'test_conjunctive_graph.py'),
- # join(tmp_src, 'test', 'test_conneg.py'),
- # join(tmp_src, 'test', 'test_conventions.py'),
+ join(tmp_src, 'test', 'rdfa', 'run_w3c_rdfa_testsuite.py'),
+ join(tmp_src, 'test', 'rdfa', 'test_non_xhtml.py'),
+ join(tmp_src, 'test', 'store_performance.py'),
+ join(tmp_src, 'test', 'test_aggregate_graphs.py'),
+ join(tmp_src, 'test', 'test_bnode_ncname.py'),
+ join(tmp_src, 'test', 'test_comparison.py'),
+ join(tmp_src, 'test', 'test_conjunctive_graph.py'),
+ join(tmp_src, 'test', 'test_conneg.py'),
+ join(tmp_src, 'test', 'test_conventions.py'),
join(tmp_src, 'test', 'test_core_sparqlstore.py'),
- # join(tmp_src, 'test', 'test_dataset.py'),
- # join(tmp_src, 'test', 'test_datetime.py'),
- # join(tmp_src, 'test', 'test_dawg.py'),
- # join(tmp_src, 'test', 'test_diff.py'),
- # join(tmp_src, 'test', 'test_empty_xml_base.py'),
+ join(tmp_src, 'test', 'test_dataset.py'),
+ join(tmp_src, 'test', 'test_datetime.py'),
+ join(tmp_src, 'test', 'test_dawg.py'),
+ join(tmp_src, 'test', 'test_diff.py'),
+ join(tmp_src, 'test', 'test_empty_xml_base.py'),
join(tmp_src, 'test', 'test_evaluate_bind.py'),
- # join(tmp_src, 'test', 'test_events.py'),
- # join(tmp_src, 'test', 'test_expressions.py'),
+ join(tmp_src, 'test', 'test_events.py'),
+ join(tmp_src, 'test', 'test_expressions.py'),
join(tmp_src, 'test', 'test_finalnewline.py'),
- # join(tmp_src, 'test', 'test_graph.py'),
- # join(tmp_src, 'test', 'test_graph_context.py'),
+ join(tmp_src, 'test', 'test_graph.py'),
+ join(tmp_src, 'test', 'test_graph_context.py'),
join(tmp_src, 'test', 'test_graph_formula.py'),
- # join(tmp_src, 'test', 'test_graph_items.py'),
+ join(tmp_src, 'test', 'test_graph_items.py'),
join(tmp_src, 'test', 'test_initbindings.py'),
- # join(tmp_src, 'test', 'test_iomemory.py'),
- # join(tmp_src, 'test', 'test_issue084.py'),
+ join(tmp_src, 'test', 'test_iomemory.py'),
+ join(tmp_src, 'test', 'test_issue084.py'),
join(tmp_src, 'test', 'test_issue130.py'),
- # join(tmp_src, 'test', 'test_issue154.py'),
+ join(tmp_src, 'test', 'test_issue154.py'),
join(tmp_src, 'test', 'test_issue160.py'),
- # join(tmp_src, 'test', 'test_issue161.py'),
+ join(tmp_src, 'test', 'test_issue161.py'),
join(tmp_src, 'test', 'test_issue184.py'),
- # join(tmp_src, 'test', 'test_issue190.py'),
+ join(tmp_src, 'test', 'test_issue190.py'),
join(tmp_src, 'test', 'test_issue200.py'),
join(tmp_src, 'test', 'test_issue209.py'),
join(tmp_src, 'test', 'test_issue247.py'),
- # join(tmp_src, 'test', 'test_issue248.py'),
- # join(tmp_src, 'test', 'test_issue363.py'),
- # join(tmp_src, 'test', 'test_issue375.py'),
- # join(tmp_src, 'test', 'test_issue379.py'),
+ join(tmp_src, 'test', 'test_issue248.py'),
+ join(tmp_src, 'test', 'test_issue363.py'),
+ join(tmp_src, 'test', 'test_issue375.py'),
+ join(tmp_src, 'test', 'test_issue379.py'),
join(tmp_src, 'test', 'test_issue_git_200.py'),
join(tmp_src, 'test', 'test_issue_git_336.py'),
- # join(tmp_src, 'test', 'test_literal.py'),
- # join(tmp_src, 'test', 'test_memory_store.py'),
- # join(tmp_src, 'test', 'test_n3.py'),
- # join(tmp_src, 'test', 'test_n3_suite.py'),
+ join(tmp_src, 'test', 'test_literal.py'),
+ join(tmp_src, 'test', 'test_memory_store.py'),
+ join(tmp_src, 'test', 'test_n3.py'),
+ join(tmp_src, 'test', 'test_n3_suite.py'),
join(tmp_src, 'test', 'test_namespace.py'),
- # join(tmp_src, 'test', 'test_nodepickler.py'),
- # join(tmp_src, 'test', 'test_nquads.py'),
- # join(tmp_src, 'test', 'test_nquads_w3c.py'),
- # join(tmp_src, 'test', 'test_nt_misc.py'),
+ join(tmp_src, 'test', 'test_nodepickler.py'),
+ join(tmp_src, 'test', 'test_nquads.py'),
+ join(tmp_src, 'test', 'test_nquads_w3c.py'),
+ join(tmp_src, 'test', 'test_nt_misc.py'),
join(tmp_src, 'test', 'test_nt_suite.py'),
- # join(tmp_src, 'test', 'test_nt_w3c.py'),
- # join(tmp_src, 'test', 'test_parser.py'),
- # join(tmp_src, 'test', 'test_parser_helpers.py'),
- # join(tmp_src, 'test', 'test_parser_structure.py'),
- # join(tmp_src, 'test', 'test_path_div_future.py'),
- # join(tmp_src, 'test', 'test_prefixTypes.py'),
- # join(tmp_src, 'test', 'test_preflabel.py'),
- # join(tmp_src, 'test', 'test_prettyxml.py'),
- # join(tmp_src, 'test', 'test_rdf_lists.py'),
- # join(tmp_src, 'test', 'test_rdfxml.py'),
- # join(tmp_src, 'test', 'test_roundtrip.py'),
- # join(tmp_src, 'test', 'test_rules.py'),
- # join(tmp_src, 'test', 'test_seq.py'),
- # join(tmp_src, 'test', 'test_serializexml.py'),
- # join(tmp_src, 'test', 'test_slice.py'),
- # join(tmp_src, 'test', 'test_sparql.py'),
- # join(tmp_src, 'test', 'test_sparqlstore.py'),
- # join(tmp_src, 'test', 'test_sparqlupdatestore.py'),
+ join(tmp_src, 'test', 'test_nt_w3c.py'),
+ join(tmp_src, 'test', 'test_parser.py'),
+ join(tmp_src, 'test', 'test_parser_helpers.py'),
+ join(tmp_src, 'test', 'test_parser_structure.py'),
+ join(tmp_src, 'test', 'test_path_div_future.py'),
+ join(tmp_src, 'test', 'test_prefixTypes.py'),
+ join(tmp_src, 'test', 'test_preflabel.py'),
+ join(tmp_src, 'test', 'test_prettyxml.py'),
+ join(tmp_src, 'test', 'test_rdf_lists.py'),
+ join(tmp_src, 'test', 'test_rdfxml.py'),
+ join(tmp_src, 'test', 'test_roundtrip.py'),
+ join(tmp_src, 'test', 'test_rules.py'),
+ join(tmp_src, 'test', 'test_seq.py'),
+ join(tmp_src, 'test', 'test_serializexml.py'),
+ join(tmp_src, 'test', 'test_slice.py'),
+ join(tmp_src, 'test', 'test_sparql.py'),
+ join(tmp_src, 'test', 'test_sparqlstore.py'),
+ join(tmp_src, 'test', 'test_sparqlupdatestore.py'),
join(tmp_src, 'test', 'test_swap_n3.py'),
- # join(tmp_src, 'test', 'test_term.py'),
- # join(tmp_src, 'test', 'test_trig.py'),
- # join(tmp_src, 'test', 'test_trig_w3c.py'),
- # join(tmp_src, 'test', 'test_trix_parse.py'),
- # join(tmp_src, 'test', 'test_trix_serialize.py'),
- # join(tmp_src, 'test', 'test_tsvresults.py'),
- # join(tmp_src, 'test', 'test_turtle_serialize.py'),
- # join(tmp_src, 'test', 'test_turtle_w3c.py'),
- # join(tmp_src, 'test', 'test_util.py'),
+ join(tmp_src, 'test', 'test_term.py'),
+ join(tmp_src, 'test', 'test_trig.py'),
+ join(tmp_src, 'test', 'test_trig_w3c.py'),
+ join(tmp_src, 'test', 'test_trix_parse.py'),
+ join(tmp_src, 'test', 'test_trix_serialize.py'),
+ join(tmp_src, 'test', 'test_tsvresults.py'),
+ join(tmp_src, 'test', 'test_turtle_serialize.py'),
+ join(tmp_src, 'test', 'test_turtle_w3c.py'),
+ join(tmp_src, 'test', 'test_util.py'),
join(tmp_src, 'test', 'test_xmlliterals.py'),
- # join(tmp_src, 'test', 'testutils.py'),
+ join(tmp_src, 'test', 'testutils.py'),
join(tmp_src, 'test', 'triple_store.py'),
join(tmp_src, 'test', 'type_check.py'),
]
diff --git a/test/manifest.py b/test/manifest.py
index 7502b9f2..14dc256c 100644
--- a/test/manifest.py
+++ b/test/manifest.py
@@ -1,7 +1,10 @@
+from __future__ import print_function
+
from collections import namedtuple
from nose.tools import nottest
from rdflib import Graph, RDF, RDFS, Namespace
+from rdflib.py3compat import text_type
MF = Namespace('http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#')
QT = Namespace('http://www.w3.org/2001/sw/DataAccess/tests/test-query#')
@@ -17,7 +20,7 @@ def read_manifest(f, base=None, legacy=False):
def _str(x):
if x is not None:
- return unicode(x)
+ return text_type(x)
return None
g = Graph()
@@ -117,7 +120,7 @@ def read_manifest(f, base=None, legacy=False):
else:
pass
- print "I dont know DAWG Test Type %s" % _type
+ print("I dont know DAWG Test Type %s" % _type)
continue
yield _type, RDFTest(e, _str(name), _str(comment),
diff --git a/test/rdfa/run_w3c_rdfa_testsuite.py b/test/rdfa/run_w3c_rdfa_testsuite.py
index c37212a0..b9ca6d13 100644
--- a/test/rdfa/run_w3c_rdfa_testsuite.py
+++ b/test/rdfa/run_w3c_rdfa_testsuite.py
@@ -17,8 +17,8 @@ automatically downloads them (to allow for "manual+automatic" update).
from operator import attrgetter
import re
import os
-from urllib2 import urlopen
-from urllib import url2pathname
+
+from rdflib.py3compat import urlopen, url2pathname
from rdflib.graph import Graph
from rdflib.namespace import Namespace, RDF
@@ -149,13 +149,14 @@ def manual_run():
print(test.description)
try:
test()
- print "PASSED"
- except AssertionError, e:
+ print("PASSED")
+ except AssertionError as e:
failed += 1
- print "****FAILED****", e;
- except Exception, e:
- errors += 1; print "****ERROR**** in %s" % test._source_urls, e
- print "Ran %(count)s tests. Failed: %(failed)s. Errors: %(errors)s."%vars()
+ print("****FAILED****", e);
+ except Exception as e:
+ errors += 1
+ print("****ERROR**** in %s" % test._source_urls, e)
+ print("Ran %(count)s tests. Failed: %(failed)s. Errors: %(errors)s."%vars())
if __name__ == '__main__':
diff --git a/test/rdfa/test_non_xhtml.py b/test/rdfa/test_non_xhtml.py
index 9b94e241..8fe714eb 100644
--- a/test/rdfa/test_non_xhtml.py
+++ b/test/rdfa/test_non_xhtml.py
@@ -1,5 +1,5 @@
from unittest import TestCase
-from urllib2 import URLError
+from rdflib.py3compat import URLError
from rdflib.graph import ConjunctiveGraph
diff --git a/test/store_performance.py b/test/store_performance.py
index e9de8af8..578a51e5 100644
--- a/test/store_performance.py
+++ b/test/store_performance.py
@@ -1,3 +1,5 @@
+from __future__ import print_function
+
import unittest
import os
import gc
@@ -51,14 +53,14 @@ class StoreTestCase(unittest.TestCase):
def testTime(self):
number = 1
- print self.store
- print "input:",
+ print(self.store)
+ print("input:", end=' ')
for i in itertools.repeat(None, number):
self._testInput()
- print "random:",
+ print("random:", end=' ')
for i in itertools.repeat(None, number):
self._testRandom()
- print "."
+ print(".")
def _testRandom(self):
number = len(self.input)
@@ -75,7 +77,7 @@ class StoreTestCase(unittest.TestCase):
for _i in it:
add_random()
t1 = time()
- print "%.3g" % (t1 - t0),
+ print("%.3g" % (t1 - t0), end=' ')
def _testInput(self):
number = 1
@@ -90,7 +92,7 @@ class StoreTestCase(unittest.TestCase):
for _i in it:
add_from_input()
t1 = time()
- print "%.3g" % (t1 - t0),
+ print("%.3g" % (t1 - t0), end=' ')
class MemoryStoreTestCase(StoreTestCase):
diff --git a/test/test_aggregate_graphs.py b/test/test_aggregate_graphs.py
index 8730847a..f790345d 100644
--- a/test/test_aggregate_graphs.py
+++ b/test/test_aggregate_graphs.py
@@ -1,9 +1,9 @@
import unittest
from rdflib.namespace import Namespace, RDF, RDFS
from rdflib import plugin
+from rdflib.py3compat import StringIO
from rdflib.term import URIRef
from rdflib.store import Store
-from cStringIO import StringIO
from rdflib.graph import Graph
from rdflib.graph import ReadOnlyGraphAggregate
from rdflib.graph import ConjunctiveGraph
diff --git a/test/test_bnode_ncname.py b/test/test_bnode_ncname.py
index 0669de4f..beb7428e 100644
--- a/test/test_bnode_ncname.py
+++ b/test/test_bnode_ncname.py
@@ -24,13 +24,13 @@ 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 = long( time.time() * 1000.0 )
- r = long( random.random()*100000000000000000L )
+ t = int( time.time() * 1000.0 )
+ r = int( random.random()*100000000000000000 )
try:
a = socket.gethostbyname( socket.gethostname() )
except:
# if we can't get a network address, just imagine one
- a = random.random()*100000000000000000L
+ a = random.random()*100000000000000000
strdata = str(t)+' '+str(r)+' '+str(a)
data = md5(strdata.encode('ascii')).hexdigest()
yield data
diff --git a/test/test_canonicalization.py b/test/test_canonicalization.py
index 87b5eeaa..ef2b8589 100644
--- a/test/test_canonicalization.py
+++ b/test/test_canonicalization.py
@@ -1,5 +1,6 @@
-from rdflib import *
-from rdflib.compare import *
+from rdflib import Graph, RDF, BNode, URIRef
+from rdflib.compare import to_isomorphic, to_canonical_graph
+from rdflib.py3compat import text_type
from io import StringIO
def get_digest_value(rdf, mimetype):
@@ -8,43 +9,43 @@ def get_digest_value(rdf, mimetype):
stats = {}
ig = to_isomorphic(graph)
result = ig.graph_digest(stats)
- print stats
+ print(stats)
return result
def negative_graph_match_test():
'''Test of FRIR identifiers against tricky RDF graphs with blank nodes.'''
testInputs = [
- [ unicode('''@prefix : <http://example.org/ns#> .
+ [ text_type('''@prefix : <http://example.org/ns#> .
<http://example.org> :rel
[ :label "Same" ].
'''),
- unicode('''@prefix : <http://example.org/ns#> .
+ text_type('''@prefix : <http://example.org/ns#> .
<http://example.org> :rel
[ :label "Same" ],
[ :label "Same" ].
'''),
False
],
- [ unicode('''@prefix : <http://example.org/ns#> .
+ [ text_type('''@prefix : <http://example.org/ns#> .
<http://example.org> :rel
<http://example.org/a>.
'''),
- unicode('''@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
],
- [ unicode('''@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]].'''),
- unicode('''@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
],
- [ unicode('''@prefix : <http://example.org/ns#> .
+ [ text_type('''@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
@@ -54,7 +55,7 @@ def negative_graph_match_test():
];
];
].'''),
- unicode('''@prefix : <http://example.org/ns#> .
+ text_type('''@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
@@ -69,7 +70,7 @@ def negative_graph_match_test():
False
],
# This test fails because the algorithm purposefully breaks the symmetry of symetric
- [ unicode('''@prefix : <http://example.org/ns#> .
+ [ text_type('''@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
@@ -79,7 +80,7 @@ def negative_graph_match_test():
];
];
].'''),
- unicode('''@prefix : <http://example.org/ns#> .
+ text_type('''@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
@@ -91,7 +92,7 @@ def negative_graph_match_test():
].'''),
True
],
- [ unicode('''@prefix : <http://example.org/ns#> .
+ [ text_type('''@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:label "foo";
@@ -102,7 +103,7 @@ def negative_graph_match_test():
];
];
].'''),
- unicode('''@prefix : <http://example.org/ns#> .
+ text_type('''@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
@@ -114,7 +115,7 @@ def negative_graph_match_test():
].'''),
False
],
- [ unicode('''@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.
@@ -126,7 +127,7 @@ def negative_graph_match_test():
_:0009 :rel _:0004, _:0005, _:0007.
_:0010 :rel _:0003, _:0006, _:0008.
'''),
- unicode('''@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,10 +145,10 @@ def negative_graph_match_test():
def fn(rdf1, rdf2, identical):
digest1 = get_digest_value(rdf1,"text/turtle")
digest2 = get_digest_value(rdf2,"text/turtle")
- print rdf1
- print digest1
- print rdf2
- print digest2
+ print(rdf1)
+ print(digest1)
+ print(rdf2)
+ print(digest2)
assert (digest1 == digest2) == identical
for inputs in testInputs:
yield fn, inputs[0], inputs[1], inputs[2]
@@ -218,28 +219,28 @@ def test_issue494_collapsing_bnodes():
RDF['Statement']),
]
- print 'graph length: %d, nodes: %d' % (len(g), len(g.all_nodes()))
- print 'triple_bnode degrees:'
+ print('graph length: %d, nodes: %d' % (len(g), len(g.all_nodes())))
+ print('triple_bnode degrees:')
for triple_bnode in g.subjects(RDF['type'], RDF['Statement']):
- print len(list(g.triples([triple_bnode, None, None])))
- print 'all node degrees:'
+ print(len(list(g.triples([triple_bnode, None, None]))))
+ print('all node degrees:')
g_node_degs = sorted([
len(list(g.triples([node, None, None])))
for node in g.all_nodes()
], reverse=True)
- print g_node_degs
+ print(g_node_degs)
cg = to_canonical_graph(g)
- print 'graph length: %d, nodes: %d' % (len(cg), len(cg.all_nodes()))
- print 'triple_bnode degrees:'
+ print('graph length: %d, nodes: %d' % (len(cg), len(cg.all_nodes())))
+ print('triple_bnode degrees:')
for triple_bnode in cg.subjects(RDF['type'], RDF['Statement']):
- print len(list(cg.triples([triple_bnode, None, None])))
- print 'all node degrees:'
+ print(len(list(cg.triples([triple_bnode, None, None]))))
+ print('all node degrees:')
cg_node_degs = sorted([
len(list(cg.triples([node, None, None])))
for node in cg.all_nodes()
], reverse=True)
- print cg_node_degs
+ print(cg_node_degs)
assert len(g) == len(cg), \
'canonicalization changed number of triples in graph'
diff --git a/test/test_conneg.py b/test/test_conneg.py
index 606d0bd6..479cefc9 100644
--- a/test/test_conneg.py
+++ b/test/test_conneg.py
@@ -1,8 +1,8 @@
-import thread
import time
-import BaseHTTPServer
+
from rdflib import Graph
+from rdflib.py3compat import HTTPServer, BaseHTTPRequestHandler, thread
"""
Test that correct content negoation headers are passed
@@ -29,8 +29,8 @@ n3testdoc="""@prefix : <http://example.org/> .
nttestdoc="<http://example.org/a> <http://example.org/b> <http://example.org/c> .\n"
-class TestHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
- def do_GET(self):
+class TestHTTPHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
self.send_response(200, "OK")
# fun fun fun parsing accept header.
@@ -59,7 +59,7 @@ class TestHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def log_message(self, *args):
pass
-def runHttpServer(server_class=BaseHTTPServer.HTTPServer,
+def runHttpServer(server_class=HTTPServer,
handler_class=TestHTTPHandler):
"""Start a server than can handle 3 requests :)"""
server_address = ('localhost', 12345)
diff --git a/test/test_dataset.py b/test/test_dataset.py
index 47e3b716..d166cebd 100644
--- a/test/test_dataset.py
+++ b/test/test_dataset.py
@@ -125,8 +125,8 @@ class DatasetTestCase(unittest.TestCase):
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 " \
- "is supported by your SPARQL endpoint"
+ print("Please make sure updating the default graph " \
+ "is supported by your SPARQL endpoint")
self.graph.add(( self.tarek, self.likes, self.pizza))
self.assertEqual(len(self.graph), 1)
@@ -145,8 +145,8 @@ class DatasetTestCase(unittest.TestCase):
def testNotUnion(self):
# Union depends on the SPARQL endpoint configuration
if self.store == "SPARQLUpdateStore":
- print "Please make sure your SPARQL endpoint has not configured " \
- "its default graph as the union of the named graphs"
+ 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))
@@ -173,9 +173,9 @@ for s in plugin.plugins(pluginname, plugin.Store):
continue
if s.name == "SPARQLUpdateStore":
- import urllib2
+ from rdflib.py3compat import urlopen
try:
- assert len(urllib2.urlopen(HOST).read()) > 0
+ assert len(urlopen(HOST).read()) > 0
except:
sys.stderr.write("No SPARQL endpoint for %s (tests skipped)\n" % s.name)
continue
diff --git a/test/test_datetime.py b/test/test_datetime.py
index 5510bc4b..df1b25fa 100644
--- a/test/test_datetime.py
+++ b/test/test_datetime.py
@@ -9,10 +9,11 @@ from isodate.isostrf import DATE_EXT_COMPLETE, TZ_EXT
from rdflib.term import URIRef
from rdflib.term import Literal
from rdflib.namespace import XSD
+from rdflib.py3compat import text_type
class TestRelativeBase(unittest.TestCase):
- def test_equality(self):
+ def test_equality(self):
x = Literal("2008-12-01T18:02:00Z",
datatype=URIRef('http://www.w3.org/2001/XMLSchema#dateTime'))
self.assertEqual(x == x, True)
@@ -27,7 +28,7 @@ class TestRelativeBase(unittest.TestCase):
# datetime with microseconds should be cast as a literal with using
# XML Schema dateTime as the literal datatype
- self.assertEqual(unicode(l), '2009-06-15T23:37:06.522630')
+ self.assertEqual(text_type(l), '2009-06-15T23:37:06.522630')
self.assertEqual(l.datatype, XSD.dateTime)
dt2 = l.toPython()
@@ -80,4 +81,3 @@ class TestRelativeBase(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
-
diff --git a/test/test_dawg.py b/test/test_dawg.py
index bdacd992..ed72fe2b 100644
--- a/test/test_dawg.py
+++ b/test/test_dawg.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import sys
# Needed to pass
@@ -41,23 +42,14 @@ from rdflib.plugins.sparql.parser import parseQuery, parseUpdate
from rdflib.plugins.sparql.results.rdfresults import RDFResultParser
from rdflib.plugins.sparql.update import evalUpdate
-from rdflib.py3compat import decodeStringEscape, bopen
+from rdflib.py3compat import decodeStringEscape, bopen, urljoin, BytesIO
from nose.tools import nottest, eq_
from nose import SkipTest
-from urlparse import urljoin
-from StringIO import StringIO
-
-if sys.version_info[0:2] < (2, 7):
- from StringIO import StringIO as BytesIO
- assert BytesIO
-else:
- from io import BytesIO
-
-from manifest import nose_tests, MF, UP
-from earl import report, add_test
+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))
@@ -162,7 +154,7 @@ def bindingsCompatible(a, b):
def rowCompatible(x, y):
m = {}
y = y.asdict()
- for v1, b1 in x.asdict().iteritems():
+ for v1, b1 in x.asdict().items():
if v1 not in y:
return False
if isinstance(b1, BNode):
@@ -186,7 +178,7 @@ def bindingsCompatible(a, b):
return False
return True
- x = iter(a).next()
+ x = next(iter(a))
for y in b:
if rowCompatible(x, y):
@@ -267,7 +259,7 @@ def update_test(t):
assert isomorphic(x, resg.get_context(x.identifier)), \
"Graphs with ID %s are not isomorphic" % x.identifier
- except Exception, e:
+ except Exception as e:
if isinstance(e, AssertionError):
failed_tests.append(uri)
@@ -277,54 +269,54 @@ def update_test(t):
errors[str(e)] += 1
if DEBUG_ERROR and not isinstance(e, AssertionError) or DEBUG_FAIL:
- print "======================================"
- print uri
- print name
- print comment
+ print("======================================")
+ print(uri)
+ print(name)
+ print(comment)
if not res:
if syntax:
- print "Positive syntax test"
+ print("Positive syntax test")
else:
- print "Negative syntax test"
+ print("Negative syntax test")
if data:
- print "----------------- DATA --------------------"
- print ">>>", data
- print bopen_read_close(data[7:])
+ print("----------------- DATA --------------------")
+ print(">>>", data)
+ print(bopen_read_close(data[7:]))
if graphdata:
- print "----------------- GRAPHDATA --------------------"
+ print("----------------- GRAPHDATA --------------------")
for x, l in graphdata:
- print ">>>", x, l
- print bopen_read_close(x[7:])
+ print(">>>", x, l)
+ print(bopen_read_close(x[7:]))
- print "----------------- Request -------------------"
- print ">>>", query
- print bopen_read_close(query[7:])
+ print("----------------- Request -------------------")
+ print(">>>", query)
+ print(bopen_read_close(query[7:]))
if res:
if resdata:
- print "----------------- RES DATA --------------------"
- print ">>>", resdata
- print bopen_read_close(resdata[7:])
+ print("----------------- RES DATA --------------------")
+ print(">>>", resdata)
+ print(bopen_read_close(resdata[7:]))
if resgraphdata:
- print "----------------- RES GRAPHDATA -------------------"
+ print("----------------- RES GRAPHDATA -------------------")
for x, l in resgraphdata:
- print ">>>", x, l
- print bopen_read_close(x[7:])
+ print(">>>", x, l)
+ print(bopen_read_close(x[7:]))
- print "------------- MY RESULT ----------"
- print g.serialize(format='trig')
+ print("------------- MY RESULT ----------")
+ print(g.serialize(format='trig'))
try:
pq = translateUpdate(parseUpdate(bopen_read_close(query[7:])))
- print "----------------- Parsed ------------------"
+ print("----------------- Parsed ------------------")
pprintAlgebra(pq)
# print pq
except:
- print "(parser error)"
+ print("(parser error)")
- print decodeStringEscape(unicode(e))
+ print(decodeStringEscape(str(e)))
import pdb
pdb.post_mortem(sys.exc_info()[2])
@@ -342,7 +334,7 @@ def query_test(t):
raise SkipTest()
def skip(reason='(none)'):
- print "Skipping %s from now on." % uri
+ print("Skipping %s from now on." % uri)
with bopen("skiptests.list", "a") as f:
f.write("%s\t%s\n" % (uri, reason))
@@ -445,7 +437,7 @@ def query_test(t):
else:
raise Exception('Unknown result type: %s' % res.type)
- except Exception, e:
+ except Exception as e:
if isinstance(e, AssertionError):
failed_tests.append(uri)
@@ -455,43 +447,43 @@ def query_test(t):
errors[str(e)] += 1
if DEBUG_ERROR and not isinstance(e, AssertionError) or DEBUG_FAIL:
- print "======================================"
- print uri
- print name
- print comment
+ print("======================================")
+ print(uri)
+ print(name)
+ print(comment)
if not resfile:
if syntax:
- print "Positive syntax test"
+ print("Positive syntax test")
else:
- print "Negative syntax test"
+ print("Negative syntax test")
if data:
- print "----------------- DATA --------------------"
- print ">>>", data
- print bopen_read_close(data[7:])
+ print("----------------- DATA --------------------")
+ print(">>>", data)
+ print(bopen_read_close(data[7:]))
if graphdata:
- print "----------------- GRAPHDATA --------------------"
+ print("----------------- GRAPHDATA --------------------")
for x in graphdata:
- print ">>>", x
- print bopen_read_close(x[7:])
+ print(">>>", x)
+ print(bopen_read_close(x[7:]))
- print "----------------- Query -------------------"
- print ">>>", query
- print bopen_read_close(query[7:])
+ print("----------------- Query -------------------")
+ print(">>>", query)
+ print(bopen_read_close(query[7:]))
if resfile:
- print "----------------- Res -------------------"
- print ">>>", resfile
- print bopen_read_close(resfile[7:])
+ print("----------------- Res -------------------")
+ print(">>>", resfile)
+ print(bopen_read_close(resfile[7:]))
try:
pq = parseQuery(bopen_read_close(query[7:]))
- print "----------------- Parsed ------------------"
+ print("----------------- Parsed ------------------")
pprintAlgebra(translateQuery(pq, base=urljoin(query, '.')))
except:
- print "(parser error)"
+ print("(parser error)")
- print decodeStringEscape(unicode(e))
+ print(decodeStringEscape(str(e)))
import pdb
pdb.post_mortem(sys.exc_info()[2])
@@ -563,7 +555,7 @@ if __name__ == '__main__':
except SkipTest as e:
msg = skiptests.get(t[0], e.args)
add_test(t[0], "untested", msg)
- print "skipping %s - %s" % (t[0], msg)
+ print("skipping %s - %s" % (t[0], msg))
skip += 1
except KeyboardInterrupt:
@@ -576,43 +568,43 @@ if __name__ == '__main__':
traceback.print_exc()
sys.stderr.write("%s\n" % t[0])
- print "\n----------------------------------------------------\n"
- print "Failed tests:"
+ print("\n----------------------------------------------------\n")
+ print("Failed tests:")
for failed in failed_tests:
- print failed
+ print(failed)
- print "\n----------------------------------------------------\n"
- print "Error tests:"
+ print("\n----------------------------------------------------\n")
+ print("Error tests:")
for error in error_tests:
- print error
+ print(error)
- print "\n----------------------------------------------------\n"
+ print("\n----------------------------------------------------\n")
- print "Most common fails:"
+ print("Most common fails:")
for failed in fails.most_common(10):
failed = str(failed)
- print failed[:450] + (failed[450:] and "...")
+ print(failed[:450] + (failed[450:] and "..."))
- print "\n----------------------------------------------------\n"
+ print("\n----------------------------------------------------\n")
if errors:
- print "Most common errors:"
+ print("Most common errors:")
for error in errors.most_common(10):
- print error
+ print(error)
else:
- print "(no errors!)"
+ print("(no errors!)")
f_sum = sum(fails.values())
e_sum = sum(errors.values())
if success + f_sum + e_sum + skip != i:
- print "(Something is wrong, %d!=%d)" % (
- success + f_sum + e_sum + skip, i)
+ print("(Something is wrong, %d!=%d)" % (
+ success + f_sum + e_sum + skip, i))
- print "\n%d tests, %d passed, %d failed, %d errors, \
+ print("\n%d tests, %d passed, %d failed, %d errors, \
%d skipped (%.2f%% success)" % (
- i, success, f_sum, e_sum, skip, 100. * success / i)
- print "Took %.2fs" % (time.time() - start)
+ i, success, f_sum, e_sum, skip, 100. * success / i))
+ print("Took %.2fs" % (time.time() - start))
if not NAME:
@@ -629,4 +621,4 @@ if __name__ == '__main__':
report.serialize(earl_report, format='n3')
report.serialize('test_reports/rdflib_sparql-latest.ttl', format='n3')
- print "Wrote EARL-report to '%s'" % earl_report
+ print("Wrote EARL-report to '%s'" % earl_report)
diff --git a/test/test_empty_xml_base.py b/test/test_empty_xml_base.py
index db18d67c..fd490ca4 100644
--- a/test/test_empty_xml_base.py
+++ b/test/test_empty_xml_base.py
@@ -9,7 +9,8 @@ from rdflib.graph import ConjunctiveGraph
from rdflib.term import URIRef
from rdflib.namespace import Namespace
from rdflib.namespace import RDF
-from StringIO import StringIO
+from rdflib.py3compat import StringIO
+
import unittest
FOAF = Namespace('http://xmlns.com/foaf/0.1/')
diff --git a/test/test_events.py b/test/test_events.py
index 3f78cc2f..c64a0a8e 100644
--- a/test/test_events.py
+++ b/test/test_events.py
@@ -56,8 +56,8 @@ class EventTestCase(unittest.TestCase):
assert c2['bob'] == 'uncle'
assert c3['bob'] == 'uncle'
del c3['bob']
- assert c1.has_key('bob') == False
- assert c2.has_key('bob') == False
+ assert ('bob' in c1) == False
+ assert ('bob' in c2) == False
if __name__ == "__main__":
unittest.main()
diff --git a/test/test_expressions.py b/test/test_expressions.py
index 55ec44dc..d88d7766 100644
--- a/test/test_expressions.py
+++ b/test/test_expressions.py
@@ -16,7 +16,7 @@ def _eval(e, ctx=None):
try:
r = e.eval(ctx)
if isinstance(r, SPARQLError):
- print r
+ print(r)
return False
return r
except SPARQLError:
diff --git a/test/test_extras_external_graph_libs.py b/test/test_extras_external_graph_libs.py
index 2986d258..7254df47 100644
--- a/test/test_extras_external_graph_libs.py
+++ b/test/test_extras_external_graph_libs.py
@@ -1,5 +1,6 @@
from nose import SkipTest
from rdflib import Graph, URIRef, Literal
+from rdflib.py3compat import text_type
def test_rdflib_to_networkx():
try:
@@ -80,11 +81,11 @@ def test_rdflib_to_graphtool():
mdg = rdflib_to_graphtool(
g,
- e_prop_names=[str('name')],
- transform_p=lambda s, p, o: {str('name'): unicode(p)})
+ e_prop_names=[text_type('name')],
+ transform_p=lambda s, p, o: {text_type('name'): text_type(p)})
epterm = mdg.edge_properties['name']
- assert len(list(gt_util.find_edge(mdg, epterm, unicode(p)))) == 3
- assert len(list(gt_util.find_edge(mdg, epterm, unicode(q)))) == 1
+ 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
diff --git a/test/test_graph_items.py b/test/test_graph_items.py
index 8075b63e..c1e96c89 100644
--- a/test/test_graph_items.py
+++ b/test/test_graph_items.py
@@ -18,7 +18,7 @@ def test_recursive_list_detection():
for v in g.objects(None, RDF.value):
try:
list(g.items(v))
- except ValueError, e:
+ except ValueError as e:
pass
else:
assert False, "Expected detection of recursive rdf:rest reference"
diff --git a/test/test_issue084.py b/test/test_issue084.py
index 52a9d36c..0a659a03 100644
--- a/test/test_issue084.py
+++ b/test/test_issue084.py
@@ -1,9 +1,5 @@
from codecs import getreader
-try:
- from io import BytesIO, StringIO
-except ImportError:
- from StringIO import StringIO
- BytesIO = StringIO
+from rdflib.py3compat import BytesIO, StringIO
from rdflib import URIRef, Literal
from rdflib.graph import Graph
diff --git a/test/test_issue154.py b/test/test_issue154.py
index b7cfdbbb..4ba80895 100644
--- a/test/test_issue154.py
+++ b/test/test_issue154.py
@@ -3,11 +3,12 @@ import platform
import warnings
from unittest import TestCase
from rdflib.graph import ConjunctiveGraph, URIRef
+from rdflib.py3compat import unichr, name2codepoint
+
from nose.exc import SkipTest
# Workaround for otherwise-dropped HTML entities
import re
-from htmlentitydefs import name2codepoint
def htmlentitydecode(s):
diff --git a/test/test_issue363.py b/test/test_issue363.py
index 45f48010..90f82844 100644
--- a/test/test_issue363.py
+++ b/test/test_issue363.py
@@ -38,7 +38,7 @@ def test_broken_rdfxml():
def test_parsetype_resource():
g = rdflib.Graph().parse(data=data2)
- print g.serialize(format='n3')
+ print(g.serialize(format='n3'))
if __name__ == '__main__':
test_broken_rdfxml()
diff --git a/test/test_issue379.py b/test/test_issue379.py
index 42857aa4..34f91212 100644
--- a/test/test_issue379.py
+++ b/test/test_issue379.py
@@ -41,7 +41,7 @@ class TestBaseAllowsHash(TestCase):
http://www.w3.org/TR/2014/REC-turtle-20140225/#grammar-production-prefixID
"""
self.g.parse(data=prefix_data, format='n3')
- self.assertIsInstance(self.g.subjects().next(), rdflib.URIRef)
+ self.assertIsInstance(next(self.g.subjects()), rdflib.URIRef)
def test_parse_successful_base_with_hash(self):
"""
@@ -50,7 +50,7 @@ class TestBaseAllowsHash(TestCase):
http://www.w3.org/TR/2014/REC-turtle-20140225/#grammar-production-base
"""
self.g.parse(data=base_data, format='n3')
- self.assertIsInstance(self.g.subjects().next(), rdflib.URIRef)
+ self.assertIsInstance(next(self.g.subjects()), rdflib.URIRef)
if __name__ == "__main__":
unittest.main()
diff --git a/test/test_literal.py b/test/test_literal.py
index 10cbba24..d1a98297 100644
--- a/test/test_literal.py
+++ b/test/test_literal.py
@@ -2,6 +2,7 @@ import unittest
import rdflib # needed for eval(repr(...)) below
from rdflib.term import Literal, URIRef, _XSD_DOUBLE, bind
+from rdflib.py3compat import integer_types
from rdflib.py3compat import format_doctest_out as uformat
@@ -53,7 +54,7 @@ class TestNew(unittest.TestCase):
# change datatype
l = Literal("1")
l2 = Literal(l, datatype=rdflib.XSD.integer)
- self.assertTrue(isinstance(l2.value, long))
+ self.assertTrue(isinstance(l2.value, integer_types))
diff --git a/test/test_n3.py b/test/test_n3.py
index 7520fc81..40448770 100644
--- a/test/test_n3.py
+++ b/test/test_n3.py
@@ -1,8 +1,7 @@
from rdflib.term import Literal, URIRef
-from rdflib.namespace import Namespace
from rdflib.plugins.parsers.notation3 import BadSyntax
-from rdflib.py3compat import b
+from rdflib.py3compat import b, URLError
test_data = """
# Definitions of terms describing the n3 model
@@ -60,7 +59,6 @@ n3:context a rdf:Property; rdfs:domain n3:statement;
import unittest
-from urllib2 import URLError
from rdflib.graph import Graph, ConjunctiveGraph
@@ -97,7 +95,7 @@ class TestN3Case(unittest.TestCase):
"""
g = Graph()
g.parse(data=input, format="n3")
- print list(g)
+ print(list(g))
self.assertTrue((None, None, Literal('Foo')) in g)
self.assertTrue(
(URIRef('http://example.com/doc/bar'), None, None) in g)
@@ -121,7 +119,7 @@ class TestN3Case(unittest.TestCase):
"""
g = Graph()
g.parse(data=input, publicID='http://blah.com/', format="n3")
- print list(g)
+ print(list(g))
self.assertTrue(
(URIRef('http://blah.com/foo'), None, Literal('Foo')) in g)
self.assertTrue(
diff --git a/test/test_n3_suite.py b/test/test_n3_suite.py
index bb7a9645..61d9b8ad 100644
--- a/test/test_n3_suite.py
+++ b/test/test_n3_suite.py
@@ -2,7 +2,7 @@ import os
import sys
try:
- from testutils import check_serialize_parse
+ from .testutils import check_serialize_parse
except:
from test.testutils import check_serialize_parse
diff --git a/test/test_nquads_w3c.py b/test/test_nquads_w3c.py
index f4ed0603..1c132e9b 100644
--- a/test/test_nquads_w3c.py
+++ b/test/test_nquads_w3c.py
@@ -2,9 +2,9 @@
test suite."""
from rdflib import ConjunctiveGraph
-from manifest import nose_tests, RDFT
+from .manifest import nose_tests, RDFT
-from testutils import nose_tst_earl_report
+from .testutils import nose_tst_earl_report
verbose = False
diff --git a/test/test_nt_misc.py b/test/test_nt_misc.py
index 486354c7..204482da 100644
--- a/test/test_nt_misc.py
+++ b/test/test_nt_misc.py
@@ -4,7 +4,7 @@ import os
import re
from rdflib import Graph, Literal, URIRef
from rdflib.plugins.parsers import ntriples
-from rdflib.py3compat import bytestype, b
+from rdflib.py3compat import bytestype, text_type, b, urlopen
log = logging.getLogger(__name__)
class NTTestCase(unittest.TestCase):
@@ -32,7 +32,7 @@ class NTTestCase(unittest.TestCase):
safe = """<http://example.org/alice/foaf.rdf#me> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://xmlns.com/foaf/0.1/Person> <http://example.org/alice/foaf1.rdf> ."""
ntriples.validate = False
res = ntriples.unquote(safe)
- self.assertTrue(isinstance(res, unicode))
+ self.assertTrue(isinstance(res, text_type))
def test_validating_unquote(self):
quot = """<http://example.org/alice/foaf.rdf#me> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://xmlns.com/foaf/0.1/Person> <http://example.org/alice/foaf1.rdf> ."""
@@ -83,9 +83,9 @@ class NTTestCase(unittest.TestCase):
def test_w3_ntriple_variants(self):
uri = "file:///"+os.getcwd()+"/test/nt/test.ntriples"
- import urllib
+
parser = ntriples.NTriplesParser()
- u = urllib.urlopen(uri)
+ u = urlopen(uri)
sink = parser.parse(u)
u.close()
# ATM we are only really interested in any exceptions thrown
diff --git a/test/test_nt_w3c.py b/test/test_nt_w3c.py
index cda43038..99c52fac 100644
--- a/test/test_nt_w3c.py
+++ b/test/test_nt_w3c.py
@@ -2,9 +2,9 @@
test suite."""
from rdflib import Graph
-from manifest import nose_tests, RDFT
+from .manifest import nose_tests, RDFT
-from testutils import nose_tst_earl_report
+from .testutils import nose_tst_earl_report
verbose = False
diff --git a/test/test_parser_helpers.py b/test/test_parser_helpers.py
index fd4f7929..58d083cb 100644
--- a/test/test_parser_helpers.py
+++ b/test/test_parser_helpers.py
@@ -4,36 +4,36 @@ from rdflib.plugins.sparql.parser import TriplesSameSubject
def pt(ts):
for t in ts:
- print t
+ print(t)
def test_1():
t0 = TriplesSameSubject.parseString("[] ?p ?o ")
- print t0, len(t0)
+ print(t0, len(t0))
assert len(t0) % 3 == 0
# t=BlankNodePropertyList.parseString("[ :p ?o ]")
t1 = TriplesSameSubject.parseString("[ ?p ?o ]")
- print t1, len(t1)
+ print(t1, len(t1))
assert len(t1) % 3 == 0
t2 = TriplesSameSubject.parseString("[ ?p1 ?o1 ] ?p2 ?o2 ")
- print t2, len(t2)
+ print(t2, len(t2))
assert len(t2) % 3 == 0
t3 = TriplesSameSubject.parseString("?s ?p1 [ ] ")
- print t3, len(t3)
+ print(t3, len(t3))
assert len(t3) % 3 == 0
t4 = TriplesSameSubject.parseString("?s ?p1 [ ?p2 ?o2 ] ")
- print t4, len(t4)
+ print(t4, len(t4))
assert len(t4) % 3 == 0
t5 = TriplesSameSubject.parseString("[ ] ?p2 [ ] ")
- print t5, len(t5)
+ print(t5, len(t5))
assert len(t5) % 3 == 0
t6 = TriplesSameSubject.parseString("[ ?p1 ?o1 ] ?p2 [ ?p3 ?o2 ] ")
- print t6, len(t6)
+ print(t6, len(t6))
assert len(t6) % 3 == 0
diff --git a/test/test_parser_structure.py b/test/test_parser_structure.py
index 0e0ecf20..d759061f 100644
--- a/test/test_parser_structure.py
+++ b/test/test_parser_structure.py
@@ -3,7 +3,7 @@ import pprint
def t(q):
- print q
+ print(q)
pprint.pprint(rdflib.plugins.sparql.parser.parseQuery(q))
diff --git a/test/test_prefixTypes.py b/test/test_prefixTypes.py
index b0b90e7c..78c6d3ef 100644
--- a/test/test_prefixTypes.py
+++ b/test/test_prefixTypes.py
@@ -25,7 +25,7 @@ class PrefixTypesTest(unittest.TestCase):
def test(self):
s=graph.serialize(format='n3')
- print s
+ print(s)
self.assertTrue(b("foaf:Document") in s)
self.assertTrue(b("xsd:date") in s)
diff --git a/test/test_prettyxml.py b/test/test_prettyxml.py
index abaf9f39..a1455e98 100644
--- a/test/test_prettyxml.py
+++ b/test/test_prettyxml.py
@@ -1,15 +1,12 @@
# -*- coding: UTF-8 -*-
from rdflib.term import URIRef, BNode, Literal
from rdflib.namespace import RDF, RDFS
-from rdflib.py3compat import b
+from rdflib.py3compat import b, BytesIO
from rdflib.plugins.serializers.rdfxml import PrettyXMLSerializer
from rdflib.graph import ConjunctiveGraph
-try:
- from io import BytesIO
-except ImportError:
- from StringIO import StringIO as BytesIO
+
class SerializerTestBase(object):
diff --git a/test/test_rdf_lists.py b/test/test_rdf_lists.py
index b8286310..628d998c 100644
--- a/test/test_rdf_lists.py
+++ b/test/test_rdf_lists.py
@@ -39,7 +39,7 @@ 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#'))
- print g.serialize(format='pretty-xml')
+ print(g.serialize(format='pretty-xml'))
class ListTest(unittest.TestCase):
diff --git a/test/test_rdfxml.py b/test/test_rdfxml.py
index f8322b33..80977f9c 100644
--- a/test/test_rdfxml.py
+++ b/test/test_rdfxml.py
@@ -1,11 +1,11 @@
+from __future__ import print_function
+
import unittest
import os
import os.path
-from urllib import url2pathname
-from urllib2 import urlopen
+from rdflib.py3compat import url2pathname, urlopen
-import rdflib
from rdflib import RDF, RDFS, URIRef, BNode, Literal, Namespace, Graph
from rdflib.exceptions import ParserError
from rdflib.util import first
@@ -35,10 +35,11 @@ class TestStore(Graph):
super(TestStore, self).__init__()
self.expected = expected
- def add(self, (s, p, o)):
+ def add(self, spo):
+ (s, p, o) = spo
if not isinstance(s, BNode) and not isinstance(o, BNode):
if not (s, p, o) in self.expected:
- m = u"Triple not in expected result: %s, %s, %s" % (
+ m = "Triple not in expected result: %s, %s, %s" % (
s.n3(), p.n3(), o.n3())
if verbose:
write(m)
@@ -66,7 +67,7 @@ def cached_file(url):
fpath = os.path.join(CACHE_DIR, fname)
if not os.path.exists(fpath):
- print "%s does not exist, fetching from %s" % (fpath, url)
+ print("%s does not exist, fetching from %s" % (fpath, url))
folder = os.path.dirname(fpath)
if not os.path.exists(folder):
os.makedirs(folder)
@@ -109,7 +110,7 @@ def _testPositive(uri, manifest):
try:
store.parse(cached_file(inDoc), publicID=inDoc, format=format)
- except ParserError, pe:
+ except ParserError as pe:
write("Failed '")
write(inDoc)
write("' failed with")
@@ -233,7 +234,7 @@ if __name__ == "__main__":
import getopt
try:
optlist, args = getopt.getopt(sys.argv[1:], 'h:', ["help"])
- except getopt.GetoptError, msg:
+ except getopt.GetoptError as msg:
write(msg)
# usage()
diff --git a/test/test_roundtrip.py b/test/test_roundtrip.py
index a3889567..6d1ac3ee 100644
--- a/test/test_roundtrip.py
+++ b/test/test_roundtrip.py
@@ -3,7 +3,7 @@ import rdflib
import rdflib.compare
try:
- from test_nt_suite import all_nt_files
+ from .test_nt_suite import all_nt_files
assert all_nt_files
except:
from test.test_nt_suite import all_nt_files
@@ -40,28 +40,28 @@ def roundtrip(e, verbose=False):
s = g1.serialize(format=testfmt)
if verbose:
- print "S:"
- print s
+ print("S:")
+ print(s)
g2 = rdflib.ConjunctiveGraph()
g2.parse(data=s, format=testfmt)
if verbose:
both, first, second = rdflib.compare.graph_diff(g1,g2)
- print "Diff:"
- print "%d triples in both"%len(both)
- print "G1 Only:"
+ print("Diff:")
+ print("%d triples in both"%len(both))
+ print("G1 Only:")
for t in first:
- print t
+ print(t)
- print "--------------------"
- print "G2 Only"
+ print("--------------------")
+ print("G2 Only")
for t in second:
- print t
+ print(t)
assert rdflib.compare.isomorphic(g1, g2)
- if verbose: print "Ok!"
+ if verbose: print("Ok!")
formats = None
diff --git a/test/test_rules.py b/test/test_rules.py
index ec52e512..bd187b01 100644
--- a/test/test_rules.py
+++ b/test/test_rules.py
@@ -67,7 +67,7 @@ try:
interp.run()
#_logger.debug("inferred facts: %s" % interp.inferredFacts)
-except ImportError, e:
- print "Could not test Pychinko: %s" % e
+except ImportError as e:
+ print("Could not test Pychinko: %s" % e)
diff --git a/test/test_serializexml.py b/test/test_serializexml.py
index ec26a557..097e5f87 100644
--- a/test/test_serializexml.py
+++ b/test/test_serializexml.py
@@ -1,14 +1,10 @@
from rdflib.term import URIRef, BNode
from rdflib.namespace import RDFS
-from rdflib.py3compat import b
+from rdflib.py3compat import b, BytesIO
from rdflib.plugins.serializers.rdfxml import XMLSerializer
from rdflib.graph import ConjunctiveGraph
-try:
- from io import BytesIO
-except ImportError:
- from StringIO import StringIO as BytesIO
class SerializerTestBase(object):
diff --git a/test/test_sparql.py b/test/test_sparql.py
index 69a67c72..f6064c65 100644
--- a/test/test_sparql.py
+++ b/test/test_sparql.py
@@ -45,7 +45,7 @@ def test_variable_order():
res = g.query("SELECT (42 AS ?a) ?b { ?b ?c ?d }")
row = list(res)[0]
- print row
+ print(row)
assert len(row) == 2
assert row[0] == Literal(42)
assert row[1] == URIRef("http://foo")
diff --git a/test/test_sparql_agg_undef.py b/test/test_sparql_agg_undef.py
index dc9435d2..6786ab0c 100644
--- a/test/test_sparql_agg_undef.py
+++ b/test/test_sparql_agg_undef.py
@@ -17,7 +17,7 @@ def template_tst(agg_func, first, second):
g = Graph()
results = list(g.query(query_tpl % agg_func))
- print "===", results
+ print("===", results)
assert results[0][1] == first, (results[0][1], first)
assert results[1][1] == second, (results[1][1], second)
diff --git a/test/test_sparqlstore.py b/test/test_sparqlstore.py
index 5b0e7160..d5091e03 100644
--- a/test/test_sparqlstore.py
+++ b/test/test_sparqlstore.py
@@ -10,9 +10,9 @@ except ImportError:
if os.getenv("TRAVIS"):
raise SkipTest("Doesn't work in travis")
-import urllib2
+from rdflib.py3compat import urlopen
try:
- assert len(urllib2.urlopen("http://dbpedia.org/sparql").read()) > 0
+ assert len(urlopen("http://dbpedia.org/sparql").read()) > 0
except:
raise SkipTest("No HTTP connection.")
diff --git a/test/test_sparqlupdatestore.py b/test/test_sparqlupdatestore.py
index 152f4bb2..c286e0ae 100644
--- a/test/test_sparqlupdatestore.py
+++ b/test/test_sparqlupdatestore.py
@@ -1,9 +1,12 @@
# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+
import unittest
import re
from rdflib import ConjunctiveGraph, URIRef, Literal
-from rdflib.util import from_n3
+from rdflib.py3compat import text_type, urlopen
HOST = 'http://localhost:3031'
DB = '/db/'
@@ -214,19 +217,19 @@ class TestSparql11(unittest.TestCase):
# Complicated Strings
r4strings = []
- r4strings.append(ur'''"1: adfk { ' \\\" \" { "''')
- r4strings.append(ur'''"2: adfk } <foo> #éï \\"''')
+ r4strings.append(r'''"1: adfk { ' \\\" \" { "''')
+ r4strings.append(r'''"2: adfk } <foo> #éï \\"''')
- r4strings.append(ur"""'3: adfk { " \\\' \' { '""")
- r4strings.append(ur"""'4: adfk } <foo> #éï \\'""")
+ r4strings.append(r"""'3: adfk { " \\\' \' { '""")
+ r4strings.append(r"""'4: adfk } <foo> #éï \\'""")
- r4strings.append(ur'''"""5: adfk { ' \\\" \" { """''')
- r4strings.append(ur'''"""6: adfk } <foo> #éï \\"""''')
- r4strings.append(u'"""7: ad adsfj \n { \n sadfj"""')
+ r4strings.append(r'''"""5: adfk { ' \\\" \" { """''')
+ r4strings.append(r'''"""6: adfk } <foo> #éï \\"""''')
+ r4strings.append('"""7: ad adsfj \n { \n sadfj"""')
- r4strings.append(ur"""'''8: adfk { " \\\' \' { '''""")
- r4strings.append(ur"""'''9: adfk } <foo> #éï \\'''""")
- r4strings.append(u"'''10: ad adsfj \n { \n sadfj'''")
+ r4strings.append(r"""'''8: adfk { " \\\' \' { '''""")
+ r4strings.append(r"""'''9: adfk } <foo> #éï \\'''""")
+ r4strings.append("'''10: ad adsfj \n { \n sadfj'''")
r4 = "\n".join([
u'INSERT DATA { <urn:michel> <urn:says> %s } ;' % s
@@ -235,20 +238,20 @@ class TestSparql11(unittest.TestCase):
g.update(r4)
values = set()
for v in g.objects(michel, says):
- values.add(unicode(v))
- self.assertEqual(values, set([re.sub(ur"\\(.)", ur"\1", re.sub(ur"^'''|'''$|^'|'$|" + ur'^"""|"""$|^"|"$', ur"", s)) for s in r4strings]))
+ values.add(text_type(v))
+ self.assertEqual(values, set([re.sub(r"\\(.)", r"\1", re.sub(r"^'''|'''$|^'|'$|" + r'^"""|"""$|^"|"$', r"", s)) for s in r4strings]))
# IRI Containing ' or #
# The fragment identifier must not be misinterpreted as a comment
# (commenting out the end of the block).
# The ' must not be interpreted as the start of a string, causing the }
# in the literal to be identified as the end of the block.
- r5 = u"""INSERT DATA { <urn:michel> <urn:hates> <urn:foo'bar?baz;a=1&b=2#fragment>, "'}" }"""
+ r5 = """INSERT DATA { <urn:michel> <urn:hates> <urn:foo'bar?baz;a=1&b=2#fragment>, "'}" }"""
g.update(r5)
values = set()
for v in g.objects(michel, hates):
- values.add(unicode(v))
+ values.add(text_type(v))
self.assertEqual(values, set([u"urn:foo'bar?baz;a=1&b=2#fragment", u"'}"]))
# Comments
@@ -280,14 +283,14 @@ class TestSparql11(unittest.TestCase):
)
def testEmptyNamedGraph(self):
- empty_graph_iri = u"urn:empty-graph-1"
- self.graph.update(u"CREATE GRAPH <%s>" % empty_graph_iri)
- named_graphs = [unicode(r[0]) for r in self.graph.query(
+ empty_graph_iri = "urn:empty-graph-1"
+ self.graph.update("CREATE GRAPH <%s>" % empty_graph_iri)
+ named_graphs = [text_type(r[0]) for r in self.graph.query(
"SELECT ?name WHERE { GRAPH ?name {} }")]
# Some SPARQL endpoint backends (like TDB) are not able to find empty named graphs
# (at least with this query)
if empty_graph_iri in named_graphs:
- self.assertTrue(empty_graph_iri in [unicode(g.identifier)
+ self.assertTrue(empty_graph_iri in [text_type(g.identifier)
for g in self.graph.contexts()])
def testEmptyLiteral(self):
@@ -303,9 +306,9 @@ class TestSparql11(unittest.TestCase):
self.assertEqual(o, Literal(''), repr(o))
from nose import SkipTest
-import urllib2
+
try:
- assert len(urllib2.urlopen(HOST).read()) > 0
+ assert len(urlopen(HOST).read()) > 0
except:
raise SkipTest(HOST + " is unavailable.")
diff --git a/test/test_trig_w3c.py b/test/test_trig_w3c.py
index 8c164cde..1acaf4b5 100644
--- a/test/test_trig_w3c.py
+++ b/test/test_trig_w3c.py
@@ -6,8 +6,8 @@ from rdflib import ConjunctiveGraph
from rdflib.namespace import split_uri
from rdflib.compare import graph_diff, isomorphic
-from manifest import nose_tests, RDFT
-from testutils import nose_tst_earl_report
+from .manifest import nose_tests, RDFT
+from .testutils import nose_tst_earl_report
verbose = False
@@ -31,24 +31,24 @@ def trig(test):
both, first, second = graph_diff(g,res)
if not first and not second: return
- print '==============================='
- print 'TriG'
- print g.serialize(format='nquads')
- print '==============================='
- print 'NQuads'
- print res.serialize(format='nquads')
- print '==============================='
+ print('===============================')
+ print('TriG')
+ print(g.serialize(format='nquads'))
+ print('===============================')
+ print('NQuads')
+ print(res.serialize(format='nquads'))
+ print('===============================')
- print "Diff:"
+ print("Diff:")
#print "%d triples in both"%len(both)
- print "TriG Only:"
+ print("TriG Only:")
for t in first:
- print t
+ print(t)
- print "--------------------"
- print "NQuads Only"
+ print("--------------------")
+ print("NQuads Only")
for t in second:
- print t
+ print(t)
raise Exception('Graphs do not match!')
assert isomorphic(g, res), 'graphs must be the same'
diff --git a/test/test_trix_serialize.py b/test/test_trix_serialize.py
index f2d589b1..667eb044 100644
--- a/test/test_trix_serialize.py
+++ b/test/test_trix_serialize.py
@@ -5,12 +5,7 @@ import unittest
from rdflib.graph import ConjunctiveGraph
from rdflib.term import URIRef, Literal
from rdflib.graph import Graph
-
-try:
- from io import BytesIO
- assert BytesIO
-except ImportError:
- from StringIO import StringIO as BytesIO
+from rdflib.py3compat import BytesIO
class TestTrixSerialize(unittest.TestCase):
diff --git a/test/test_tsvresults.py b/test/test_tsvresults.py
index 3e746a65..8f05cc7c 100644
--- a/test/test_tsvresults.py
+++ b/test/test_tsvresults.py
@@ -1,5 +1,5 @@
import unittest
-from StringIO import StringIO
+from rdflib.py3compat import StringIO
from rdflib.plugins.sparql.results.tsvresults import TSVResultParser
diff --git a/test/test_turtle_serialize.py b/test/test_turtle_serialize.py
index 36a1214d..995b0066 100644
--- a/test/test_turtle_serialize.py
+++ b/test/test_turtle_serialize.py
@@ -4,7 +4,7 @@ from rdflib.plugins.serializers.turtle import TurtleSerializer
from rdflib.py3compat import b
-def testTurtleFinalDot():
+def testTurtleFinalDot():
"""
https://github.com/RDFLib/rdflib/issues/282
"""
@@ -49,7 +49,7 @@ def testUnicodeEscaping():
g.parse(data=turtle_string, format="turtle")
triples = sorted(list(g))
assert len(triples) == 3
- print triples
+ print(triples)
# Now check that was decoded into python values properly
assert triples[0][2] == URIRef(u'http://example.com/aaa\xf3bbbb')
assert triples[1][2] == URIRef(u'http://example.com/zzz\U00100000zzz')
diff --git a/test/test_turtle_w3c.py b/test/test_turtle_w3c.py
index 48c42b24..adeb0868 100644
--- a/test/test_turtle_w3c.py
+++ b/test/test_turtle_w3c.py
@@ -5,8 +5,8 @@ from rdflib import Graph
from rdflib.namespace import split_uri
from rdflib.compare import graph_diff, isomorphic
-from manifest import nose_tests, RDFT
-from testutils import nose_tst_earl_report
+from .manifest import nose_tests, RDFT
+from .testutils import nose_tst_earl_report
verbose = False
@@ -27,16 +27,16 @@ def turtle(test):
if verbose:
both, first, second = graph_diff(g,res)
if not first and not second: return
- print "Diff:"
+ print("Diff:")
#print "%d triples in both"%len(both)
- print "Turtle Only:"
+ print("Turtle Only:")
for t in first:
- print t
+ print(t)
- print "--------------------"
- print "NT Only"
+ print("--------------------")
+ print("NT Only")
for t in second:
- print t
+ print(t)
raise Exception('Graphs do not match!')
assert isomorphic(g, res), 'graphs must be the same'
diff --git a/test/testutils.py b/test/testutils.py
index 6f97ea9d..6e044e6c 100644
--- a/test/testutils.py
+++ b/test/testutils.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
import sys
import isodate
@@ -5,7 +6,7 @@ import datetime
from traceback import print_exc
from nose import SkipTest
-from earl import add_test, report
+from .earl import add_test, report
from rdflib import BNode, Graph, ConjunctiveGraph
@@ -22,7 +23,7 @@ def crapCompare(g1, g2):
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)
- raise Exception, e
+ raise Exception(e)
def _no_blank(node):
if isinstance(node, BNode): return None
if isinstance(node, Graph):
@@ -34,16 +35,16 @@ def check_serialize_parse(fpath, infmt, testfmt, verbose=False):
_parse_or_report(verbose, g, fpath, format=infmt)
if verbose:
for t in g:
- print t
- print "========================================"
- print "Parsed OK!"
+ print(t)
+ print("========================================")
+ print("Parsed OK!")
s = g.serialize(format=testfmt)
if verbose:
- print s
+ print(s)
g2 = ConjunctiveGraph()
_parse_or_report(verbose, g2, data=s, format=testfmt)
if verbose:
- print g2.serialize()
+ print(g2.serialize())
crapCompare(g,g2)
@@ -52,9 +53,9 @@ def _parse_or_report(verbose, graph, *args, **kwargs):
graph.parse(*args, **kwargs)
except:
if verbose:
- print "========================================"
- print "Error in parsing serialization:"
- print args, kwargs
+ print("========================================")
+ print("Error in parsing serialization:")
+ print(args, kwargs)
raise
@@ -69,14 +70,14 @@ def nose_tst_earl_report(generator, earl_report_name=None):
for t in generator(args):
tests += 1
- print 'Running ', t[1].uri
+ print('Running ', t[1].uri)
try:
t[0](t[1])
add_test(t[1].uri, "passed")
success += 1
- except SkipTest, e:
+ except SkipTest as e:
add_test(t[1].uri, "untested", e.message)
- print "skipping %s - %s" % (t[1].uri, e.message)
+ print("skipping %s - %s" % (t[1].uri, e.message))
skip += 1
except KeyboardInterrupt:
@@ -88,11 +89,11 @@ def nose_tst_earl_report(generator, earl_report_name=None):
print_exc()
sys.stderr.write("%s\n" % t[1].uri)
- print "Ran %d tests, %d skipped, %d failed. "%(tests, skip, tests-skip-success)
+ print("Ran %d tests, %d skipped, %d failed. "%(tests, skip, tests-skip-success))
if earl_report_name:
now = isodate.datetime_isoformat(datetime.datetime.utcnow())
earl_report = 'test_reports/%s-%s.ttl' % (earl_report_name, now)
report.serialize(earl_report, format='n3')
report.serialize('test_reports/%s-latest.ttl'%earl_report_name, format='n3')
- print "Wrote EARL-report to '%s'" % earl_report
+ print("Wrote EARL-report to '%s'" % earl_report)