summaryrefslogtreecommitdiff
path: root/test/test_parsers/test_parser_turtlelike.py
blob: e74a55e783bd10cb7e45a63c7127b5f1ecc1946c (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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""
This module contains tests for the parsing of the turtle family of formats: N3,
Turtle, NTriples, NQauds and TriG.
"""

import enum
import itertools
from dataclasses import dataclass, field
from typing import Callable, Dict, Iterator, List, Set, Tuple, Union

import pytest
from _pytest.mark.structures import Mark, MarkDecorator, ParameterSet

from rdflib import XSD, Graph, Literal, Namespace
from rdflib.term import Identifier
from rdflib.util import from_n3

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


class FormatTrait(enum.Enum):
    shorthand_literals = enum.auto()
    prefixes = enum.auto()
    extended_quoting = enum.auto()  # supports additional quoting styles


@dataclass
class Format:
    name: str
    traits: Set[FormatTrait]


FORMATS = [
    Format("ntriples", set()),
    Format("nquads", set()),
    Format(
        "turtle",
        {
            FormatTrait.shorthand_literals,
            FormatTrait.prefixes,
            FormatTrait.extended_quoting,
        },
    ),
    Format(
        "trig",
        {
            FormatTrait.shorthand_literals,
            FormatTrait.prefixes,
            FormatTrait.extended_quoting,
        },
    ),
    Format(
        "n3",
        {
            FormatTrait.shorthand_literals,
            FormatTrait.prefixes,
            # NOTE: it is not clear from n3 "spec" if it supports extended
            # quoting, but the spec is not that well fleshed out. RDFLib n3
            # does not support extended quoting.
        },
    ),
]


def parse_identifier(identifier_string: str, format: str) -> Identifier:
    g = Graph()
    g.parse(
        data=f"""<{EGNS.subject}> <{EGNS.predicate}> {identifier_string} .""",
        format=format,
    )
    triples = list(g.triples((None, None, None)))
    assert len(triples) == 1
    (subj, pred, obj) = triples[0]
    assert subj == EGNS.subject
    assert pred == EGNS.predicate
    assert isinstance(obj, Identifier)
    return obj


def parse_n3_identifier(identifier_string: str, format: str) -> Identifier:
    # type error: Incompatible return value type (got "Union[Node, str, None]", expected "Identifier")
    return from_n3(identifier_string)  # type: ignore[return-value]


ParseFunction = Callable[[str, str], Identifier]


def make_literal_tests() -> Iterator[ParameterSet]:
    @dataclass
    class Case:
        expected_literal: Literal
        quoted_strings: List[str]
        shorthand_strings: List[str] = field(default_factory=list)
        xquoted_strings: List[str] = field(
            default_factory=list
        )  # strings using extended quoting styles

    cases = [
        Case(
            Literal("-5", None, XSD.integer),
            [f'"-5"^^<{XSD}integer>'],
            ["-5"],
        ),
        Case(
            Literal("-5.0", None, XSD.decimal),
            [f'"-5.0"^^<{XSD}decimal>'],
            ["-5.0"],
        ),
        Case(
            Literal("-5.5", None, XSD.decimal),
            [f'"-5.5"^^<{XSD}decimal>'],
            ["-5.5"],
        ),
        Case(
            Literal("4.2E9", None, XSD.double),
            [f'"4.2E9"^^<{XSD}double>', f'"4.2e9"^^<{XSD}double>'],
            ["4.2E9", "4.2e9"],
        ),
        Case(
            Literal("1.23E-7", None, XSD.double),
            [f'"1.23E-7"^^<{XSD}double>', f'"1.23e-7"^^<{XSD}double>'],
            ["1.23E-7", "1.23e-7"],
        ),
        Case(
            Literal("-4.1E-7", None, XSD.double),
            [f'"-4.1E-7"^^<{XSD}double>', f'"-4.1e-7"^^<{XSD}double>'],
            ["-4.1E-7", "-4.1e-7"],
        ),
        Case(
            Literal("false", None, XSD.boolean),
            [f'"false"^^<{XSD}boolean>'],
            ["false"],
        ),
        Case(
            Literal("true", None, XSD.boolean),
            [f'"true"^^<{XSD}boolean>'],
            ["true"],
        ),
        Case(
            Literal("true", None, XSD.boolean),
            [f'"true"^^<{XSD}boolean>'],
            ["true"],
        ),
        Case(
            Literal("example"),
            ['"example"'],
            [],
            ["'example'", "'''example'''", '"""example"""'],
        ),
    ]

    escapes: Dict[str, str] = {
        "\t": "\\t",
        "\b": "\\b",
        "\n": "\\n",
        "\r": "\\r",
        "\f": "\\f",
        '"': '\\"',
        "'": "\\'",
        "\\": "\\\\",
    }

    for literal, escaped in escapes.items():
        cases.append(
            Case(
                Literal(f"prefix {literal} suffix"),
                [],
                [f'"prefix {escaped} suffix"'],
                [
                    f"'prefix {escaped} suffix'",
                    f"'''prefix {escaped} suffix'''",
                    f'"""prefix {escaped} suffix"""',
                ],
            )
        )

    xfails: Dict[
        Tuple[str, Literal, str, Callable[[str, str], Identifier]],
        Union[MarkDecorator, Mark],
    ] = {
        (
            "n3",
            Literal("-4.1E-7", None, XSD.double),
            "-4.1E-7",
            parse_n3_identifier,
        ): pytest.mark.xfail(reason="bug in from_n3", raises=AssertionError),
        (
            "n3",
            Literal("-4.1E-7", None, XSD.double),
            "-4.1e-7",
            parse_n3_identifier,
        ): pytest.mark.xfail(reason="bug in from_n3", raises=AssertionError),
    }

    for case in cases:
        for format in FORMATS:
            parse_functions: List[ParseFunction] = [parse_identifier]
            literal_strings = [*case.quoted_strings]
            if FormatTrait.shorthand_literals in format.traits:
                literal_strings.extend(case.shorthand_strings)
            if FormatTrait.extended_quoting in format.traits:
                literal_strings.extend(case.xquoted_strings)

            if format.name == "n3":
                parse_functions.append(parse_n3_identifier)

            parse_function: ParseFunction
            literal_string: str
            for literal_string, parse_function in itertools.product(
                literal_strings, parse_functions
            ):
                args = (
                    format.name,
                    case.expected_literal,
                    literal_string,
                    parse_function,
                )
                xfail = xfails.get(args)
                marks = [xfail] if xfail is not None else ()
                yield pytest.param(
                    *args,
                    marks=marks,
                )


@pytest.mark.parametrize(
    ["format_name", "expected_literal", "literal_string", "parse_function"],
    make_literal_tests(),
)
def test_literals(
    format_name: str,
    expected_literal: Literal,
    literal_string: str,
    parse_function: Callable[[str, str], Identifier],
) -> None:
    """
    Literal strings parse to the expected literal.
    """
    identifier = parse_function(literal_string, format_name)
    assert expected_literal == identifier