Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix sonarcloud-reported bug in xmlwriter, add test #1951

Merged
merged 9 commits into from May 25, 2022
2 changes: 1 addition & 1 deletion rdflib/plugins/serializers/xmlwriter.py
Expand Up @@ -100,7 +100,7 @@ def qname(self, uri):
for pre, ns in self.extra_ns.items():
if uri.startswith(ns):
if pre != "":
return ":".join(pre, uri[len(ns) :])
return ":".join([pre, uri[len(ns) :]])
else:
return uri[len(ns) :]

Expand Down
79 changes: 79 additions & 0 deletions test/test_serializers/test_xmlwriter_qname.py
@@ -0,0 +1,79 @@
import tempfile

import pytest

import rdflib
from rdflib.plugins.serializers.xmlwriter import XMLWriter

EXNS = rdflib.Namespace("https://example.org/ns/")
TRIXNS = rdflib.Namespace("http://www.w3.org/2004/03/trix/trix-1/")


def test_xmlwriter_namespaces():

g = rdflib.Graph()

with tempfile.TemporaryFile() as fp:

xmlwr = XMLWriter(fp, g.namespace_manager, extra_ns={"": TRIXNS, "ex": EXNS})

xmlwr.namespaces()

fp.seek(0)

assert fp.readlines() == [
b'<?xml version="1.0" encoding="utf-8"?>\n',
b' xmlns:owl="http://www.w3.org/2002/07/owl#"\n',
b' xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"\n',
b' xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"\n',
b' xmlns:xsd="http://www.w3.org/2001/XMLSchema#"\n',
b' xmlns:xml="http://www.w3.org/XML/1998/namespace"\n',
b' xmlns="http://www.w3.org/2004/03/trix/trix-1/"\n',
b' xmlns:ex="https://example.org/ns/"\n',
]


def test_xmlwriter_decl():

g = rdflib.Graph()

with tempfile.TemporaryFile() as fp:

xmlwr = XMLWriter(fp, g.namespace_manager, decl=0, extra_ns={"": TRIXNS})

xmlwr.namespaces()

fp.seek(0)
assert fp.readlines() == [
b"\n",
b' xmlns:owl="http://www.w3.org/2002/07/owl#"\n',
b' xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"\n',
b' xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"\n',
b' xmlns:xsd="http://www.w3.org/2001/XMLSchema#"\n',
b' xmlns:xml="http://www.w3.org/XML/1998/namespace"\n',
b' xmlns="http://www.w3.org/2004/03/trix/trix-1/"\n',
]


@pytest.mark.parametrize(
"uri",
[
# NS bound to “ex”, so “ex:foo”
["https://example.org/ns/foo", "ex:foo"],
# NS bound to "", so “graph”
["http://www.w3.org/2004/03/trix/trix-1/graph", "graph"],
# NS not in extra_ns, use ns<int> idiom
["https://example.org/foo", "ns1:foo"],
],
)
def test_xmlwriter_qname(uri):

g = rdflib.Graph()
g.bind("", TRIXNS)
g.bind("ex", EXNS)

fp = tempfile.TemporaryFile()

xmlwr = XMLWriter(fp, g.namespace_manager, extra_ns={"": TRIXNS, "ex": EXNS})

assert xmlwr.qname(uri[0]) == uri[1]