summaryrefslogtreecommitdiff
path: root/test/test_turtle_quoting.py
blob: bdafd07138e3264a79042cd01727cae4cd3110ab (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""
This module is intended for tests related to unquoting/unescaping in various
formats that are related to turtle, such as ntriples, nquads, trig and n3.
"""

import itertools
import logging
from typing import Callable, Dict, Iterable, List, Tuple

import pytest

from rdflib import Namespace
from rdflib.graph import ConjunctiveGraph, Graph
from rdflib.plugins.parsers import ntriples
from rdflib.term import Literal, URIRef

from .utils import GraphHelper

# https://www.w3.org/TR/turtle/#string
string_escape_map = {
    "t": "\t",
    "b": "\b",
    "n": "\n",
    "r": "\r",
    "f": "\f",
    '"': '"',
    "'": "'",
    "\\": "\\",
}

import re


def make_unquote_correctness_pairs() -> List[Tuple[str, str]]:
    """
    Creates pairs of quoted and unquoted strings.
    """
    result = []

    def add_pair(escape: str, unescaped: str) -> None:
        result.append((f"\\{escape}", unescaped))
        result.append((f"\\\\{escape}", f"\\{escape}"))
        result.append((f"\\\\\\{escape}", f"\\{unescaped}"))

    chars = "A1a\\\nøæå"
    for char in chars:
        code_point = ord(char)
        add_pair(f"u{code_point:04x}", char)
        add_pair(f"u{code_point:04X}", char)
        add_pair(f"U{code_point:08x}", char)
        add_pair(f"U{code_point:08X}", char)

    string_escapes = "tbnrf'"
    for char in string_escapes:
        add_pair(f"{char}", string_escape_map[char])

    # special handling because «"» should not appear in string, and add_pair
    # will add it.
    result.append(('\\"', '"'))
    result.append(('\\\\\\"', '\\"'))

    # special handling because «\» should not appear in string, and add_pair
    # will add it.
    result.append(("\\\\", "\\"))
    result.append(("\\\\\\\\", "\\\\"))

    return result


UNQUOTE_CORRECTNESS_PAIRS = make_unquote_correctness_pairs()


def ntriples_unquote_validate(input: str) -> str:
    """
    This function wraps `ntriples.unquote` in a way that ensures that `ntriples.validate` is always ``True`` when it runs.
    """
    old_validate = ntriples.validate
    try:
        ntriples.validate = True
        return ntriples.unquote(input)
    finally:
        ntriples.validate = old_validate


def ntriples_unquote(input: str) -> str:
    """
    This function wraps `ntriples.unquote` in a way that ensures that `ntriples.validate` is always ``False`` when it runs.
    """
    old_validate = ntriples.validate
    try:
        ntriples.validate = False
        return ntriples.unquote(input)
    finally:
        ntriples.validate = old_validate


unquoters: Dict[str, Callable[[str], str]] = {
    "ntriples_unquote": ntriples_unquote,
    "ntriples_unquote_validate": ntriples_unquote_validate,
}


def make_unquote_correctness_tests(
    selectors: Iterable[str],
) -> Iterable[Tuple[str, str, str]]:
    """
    This function creates a cartesian product of the selectors and
    `CORRECTNESS_PAIRS` that is suitable for use as pytest parameters.
    """
    for selector in selectors:
        for quoted, unquoted in UNQUOTE_CORRECTNESS_PAIRS:
            yield selector, quoted, unquoted


@pytest.mark.parametrize(
    "unquoter_key, quoted, unquoted", make_unquote_correctness_tests(unquoters.keys())
)
def test_unquote_correctness(
    unquoter_key: str,
    quoted: str,
    unquoted: str,
) -> None:
    """
    Various unquote functions work correctly.
    """
    unquoter = unquoters[unquoter_key]
    assert unquoted == unquoter(quoted)


QUAD_FORMATS = {"nquads"}


@pytest.mark.parametrize(
    "format, quoted, unquoted",
    make_unquote_correctness_tests(["turtle", "ntriples", "nquads"]),
)
def test_parse_correctness(
    format: str,
    quoted: str,
    unquoted: str,
) -> None:
    """
    Quoted strings parse correctly
    """
    if format in QUAD_FORMATS:
        data = f'<example:Subject> <example:Predicate> "{quoted}" <example:Graph>.'
    else:
        data = f'<example:Subject> <example:Predicate> "{quoted}".'
    graph = ConjunctiveGraph()
    graph.parse(data=data, format=format)
    objs = list(graph.objects())
    assert len(objs) == 1
    obj = objs[0]
    assert isinstance(obj, Literal)
    assert isinstance(obj.value, str)
    assert obj.value == unquoted


EGNS = Namespace("http://example.com/")


@pytest.mark.parametrize(
    "format, char, escaped",
    [
        (format, char, escaped)
        for format, (char, escaped) in itertools.product(
            ["turtle"],
            [
                (r"x", r"x"),
                (r"(", r"\("),
                (r")", r"\)"),
            ],
        )
    ],
)
def test_pname_escaping(format: str, char: str, escaped: str) -> None:
    graph = Graph()
    triple = (
        URIRef(EGNS["prefix/John_Doe"]),
        URIRef(EGNS[f"prefix/prop{char}"]),
        Literal("foo", lang="en"),
    )
    graph.bind("egns", EGNS["prefix/"])
    graph.add(triple)
    data = graph.serialize(format=format)
    pattern = re.compile(f"\\segns:prop{re.escape(escaped)}\\s")
    logging.debug(
        "format = %s, char = %r, escaped = %r, pattern = %r, data = %s",
        format,
        char,
        escaped,
        pattern,
        data,
    )
    assert re.search(pattern, data) is not None


# https://www.w3.org/TR/turtle/#grammar-production-PN_LOCAL_ESC
# Not including %, as % should be used for percent encoding.
PN_LOCAL_ESC_CHARS = r"_~.-!$&'()*+,;=/?#@"


@pytest.mark.parametrize(
    "format, char",
    itertools.product(["turtle", "ntriples"], "A2c" + PN_LOCAL_ESC_CHARS),
)
def test_serialize_roundtrip(format: str, char: str) -> None:
    graph = Graph()
    triple = (
        URIRef(EGNS["prefix/John_Doe"]),
        URIRef(EGNS[f"prefix/prop{char}"]),
        Literal("foo", lang="en"),
    )
    graph.add(triple)
    graph.bind("egns", EGNS["prefix/"])
    data = graph.serialize(format=format)
    logging.debug("format = %s, char = %s, data = %s", format, char, data)
    parsed_graph = Graph()
    parsed_graph.parse(data=data, format=format)
    GraphHelper.assert_sets_equals(graph, parsed_graph)