summaryrefslogtreecommitdiff
path: root/test/test_serializers/test_xmlwriter_qname.py
blob: 13ee84a0fd6e75c1965585dc363512822b032356 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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(bind_namespaces="core")

    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(bind_namespaces="core")

    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]