summaryrefslogtreecommitdiff
path: root/test/test_serializers/test_serializer_trix.py
blob: 0f5ca5d7c278c8f7b8dd8e5261044e09b2690764 (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
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python

from io import BytesIO

from rdflib.graph import ConjunctiveGraph, Graph
from rdflib.term import Literal, URIRef


def test_serialize():

    s1 = URIRef("store:1")
    r1 = URIRef("resource:1")
    r2 = URIRef("resource:2")

    label = URIRef("predicate:label")

    g1 = Graph(identifier=s1)
    g1.add((r1, label, Literal("label 1", lang="en")))
    g1.add((r1, label, Literal("label 2")))

    s2 = URIRef("store:2")
    g2 = Graph(identifier=s2)
    g2.add((r2, label, Literal("label 3")))

    g = ConjunctiveGraph()
    for s, p, o in g1.triples((None, None, None)):
        g.addN([(s, p, o, g1)])
    for s, p, o in g2.triples((None, None, None)):
        g.addN([(s, p, o, g2)])
    r3 = URIRef("resource:3")
    g.add((r3, label, Literal(4)))

    r = g.serialize(format="trix", encoding="utf-8")
    g3 = ConjunctiveGraph()

    g3.parse(BytesIO(r), format="trix")

    for q in g3.quads((None, None, None)):
        # TODO: Fix once getGraph/getContext is in conjunctive graph
        if isinstance(q[3].identifier, URIRef):
            tg = Graph(store=g.store, identifier=q[3].identifier)
        else:
            # BNode, this is a bit ugly
            # we cannot match the bnode to the right graph automagically
            # here I know there is only one anonymous graph,
            # and that is the default one, but this is not always the case
            tg = g.default_context

        assert q[0:3] in tg


def test_issue_250():
    """

    https://github.com/RDFLib/rdflib/issues/250

    When I have a ConjunctiveGraph with the default namespace set,
    for example

    import rdflib
    g = rdflib.ConjunctiveGraph()
    g.bind(None, "http://defaultnamespace")

    then the Trix serializer binds the default namespace twice in its XML
    output, once for the Trix namespace and once for the namespace I used:

    print(g.serialize(format='trix').decode('UTF-8'))

    <?xml version="1.0" encoding="utf-8"?>
    <TriX
      xmlns:xml="http://www.w3.org/XML/1998/namespace"
      xmlns="http://defaultnamespace"
      xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
      xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
      xmlns="http://www.w3.org/2004/03/trix/trix-1/"
    />

    """

    graph = ConjunctiveGraph()
    graph.bind(None, "http://defaultnamespace")
    sg = graph.serialize(format="trix")
    assert 'xmlns="http://defaultnamespace"' not in sg, sg
    assert 'xmlns="http://www.w3.org/2004/03/trix/trix-1/' in sg, sg