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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
|
from __future__ import annotations
import logging
import re
from http.server import BaseHTTPRequestHandler
from urllib.error import HTTPError
import pytest
from rdflib import Graph
from test.data import TEST_DATA_DIR
from test.utils import GraphHelper
from test.utils.graph import cached_graph
from test.utils.http import (
MOCK_HTTP_REQUEST_WILDCARD,
MethodName,
MockHTTPRequest,
MockHTTPResponse,
ctx_http_handler,
)
from test.utils.httpservermock import ServedBaseHTTPServerMock
from test.utils.namespace import EGDO
from test.utils.wildcard import URL_PARSE_RESULT_WILDCARD
"""
Test that correct content negotiation headers are passed
by graph.parse
"""
xmltestdoc = """<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns="http://example.org/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
>
<rdf:Description rdf:about="http://example.org/a">
<b rdf:resource="http://example.org/c"/>
</rdf:Description>
</rdf:RDF>
"""
n3testdoc = """@prefix : <http://example.org/> .
:a :b :c .
"""
nttestdoc = "<http://example.org/a> <http://example.org/b> <http://example.org/c> .\n"
ttltestdoc = """@prefix : <http://example.org/> .
:a :b :c .
"""
jsonldtestdoc = """
[
{
"@id": "http://example.org/a",
"http://example.org/b": [
{
"@id": "http://example.org/c"
}
]
}
]
"""
class ContentNegotiationHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200, "OK")
# fun fun fun parsing accept header.
acs = self.headers["Accept"].split(",")
acq = [x.split(";") for x in acs if ";" in x]
acn = [(x, "q=1") for x in acs if ";" not in x]
acs = [(x[0].strip(), float(x[1].strip()[2:])) for x in acq + acn]
ac = sorted(acs, key=lambda x: x[1])
ct = ac[-1]
if "application/rdf+xml" in ct:
rct = "application/rdf+xml"
content = xmltestdoc
elif "text/n3" in ct:
rct = "text/n3"
content = n3testdoc
elif "application/trig" in ct:
rct = "application/trig"
content = ttltestdoc
elif "text/plain" in ct or "application/n-triples" in ct:
rct = "text/plain"
content = nttestdoc
elif "application/ld+json" in ct:
rct = "application/ld+json"
content = jsonldtestdoc
else: # "text/turtle" in ct:
rct = "text/turtle"
content = ttltestdoc
self.send_header("Content-type", rct)
self.end_headers()
self.wfile.write(content.encode("utf-8"))
def log_message(self, *args):
pass
class TestGraphHTTP:
def test_content_negotiation(self) -> None:
expected = Graph()
expected.add((EGDO.a, EGDO.b, EGDO.c))
expected_triples = GraphHelper.triple_set(expected)
with ctx_http_handler(ContentNegotiationHandler) as server:
(host, port) = server.server_address
if isinstance(host, (bytes, bytearray)):
host = host.decode("utf-8")
url = f"http://{host}:{port}/foo"
for format in ("xml", "n3", "nt"):
graph = Graph()
graph.parse(url, format=format)
assert expected_triples == GraphHelper.triple_set(graph)
def test_content_negotiation_no_format(self) -> None:
expected = Graph()
expected.add((EGDO.a, EGDO.b, EGDO.c))
expected_triples = GraphHelper.triple_set(expected)
with ctx_http_handler(ContentNegotiationHandler) as server:
(host, port) = server.server_address
if isinstance(host, (bytes, bytearray)):
host = host.decode("utf-8")
url = f"http://{host}:{port}/foo"
graph = Graph()
graph.parse(url)
assert expected_triples == GraphHelper.triple_set(graph)
def test_source(self) -> None:
expected = Graph()
expected.add((EGDO["a"], EGDO["b"], EGDO["c"]))
expected_triples = GraphHelper.triple_set(expected)
with ServedBaseHTTPServerMock() as httpmock:
url = httpmock.url
httpmock.responses[MethodName.GET].append(
MockHTTPResponse(
200,
"OK",
f"<{EGDO['a']}> <{EGDO['b']}> <{EGDO['c']}>.".encode(),
{"Content-Type": ["text/turtle"]},
)
)
graph = Graph()
graph.parse(source=url)
assert expected_triples == GraphHelper.triple_set(graph)
def test_3xx(self) -> None:
expected = Graph()
expected.add((EGDO["a"], EGDO["b"], EGDO["c"]))
expected_triples = GraphHelper.triple_set(expected)
with ServedBaseHTTPServerMock() as httpmock:
url = httpmock.url
for idx in range(3):
httpmock.responses[MethodName.GET].append(
MockHTTPResponse(
302,
"FOUND",
b"",
{"Location": [f"{url}/loc/302/{idx}"]},
)
)
for idx in range(3):
httpmock.responses[MethodName.GET].append(
MockHTTPResponse(
303,
"See Other",
b"",
{"Location": [f"{url}/loc/303/{idx}"]},
)
)
for idx in range(3):
httpmock.responses[MethodName.GET].append(
MockHTTPResponse(
308,
"Permanent Redirect",
b"",
{"Location": [f"{url}/loc/308/{idx}"]},
)
)
httpmock.responses[MethodName.GET].append(
MockHTTPResponse(
200,
"OK",
f"<{EGDO['a']}> <{EGDO['b']}> <{EGDO['c']}>.".encode(),
{"Content-Type": ["text/turtle"]},
)
)
graph = Graph()
graph.parse(location=url, format="turtle")
assert expected_triples == GraphHelper.triple_set(graph)
httpmock.mocks[MethodName.GET].assert_called()
assert len(httpmock.requests[MethodName.GET]) == 10
for request in httpmock.requests[MethodName.GET]:
# type error: Argument 2 to "match" has incompatible type "Optional[Any]"; expected "str"
assert re.match(r"text/turtle", request.headers.get("Accept")) # type: ignore[arg-type]
request_paths = [
request.path for request in httpmock.requests[MethodName.GET]
]
assert request_paths == [
"/",
"/loc/302/0",
"/loc/302/1",
"/loc/302/2",
"/loc/303/0",
"/loc/303/1",
"/loc/303/2",
"/loc/308/0",
"/loc/308/1",
"/loc/308/2",
]
def test_5xx(self):
with ServedBaseHTTPServerMock() as httpmock:
url = httpmock.url
httpmock.responses[MethodName.GET].append(
MockHTTPResponse(500, "Internal Server Error", b"", {})
)
graph = Graph()
with pytest.raises(HTTPError) as raised:
graph.parse(location=url, format="turtle")
assert raised.value.code == 500
@pytest.mark.parametrize(
["url_suffix", "expected_request"],
[
(
"/resource/Almería",
MOCK_HTTP_REQUEST_WILDCARD._replace(
path="/resource/Almer%C3%ADa",
parsed_path=URL_PARSE_RESULT_WILDCARD._replace(
path="/resource/Almer%C3%ADa"
),
),
),
(
"/resource/Almería?foo=bar",
MOCK_HTTP_REQUEST_WILDCARD._replace(
parsed_path=URL_PARSE_RESULT_WILDCARD._replace(
path="/resource/Almer%C3%ADa"
),
path_query={"foo": ["bar"]},
),
),
],
)
def test_iri_source(
url_suffix: str,
expected_request: MockHTTPRequest,
function_httpmock: ServedBaseHTTPServerMock,
) -> None:
diverse_triples_path = TEST_DATA_DIR / "variants/diverse_triples.ttl"
function_httpmock.responses[MethodName.GET].append(
MockHTTPResponse(
200,
"OK",
diverse_triples_path.read_bytes(),
{"Content-Type": ["text/turtle"]},
)
)
g = Graph()
g.parse(f"{function_httpmock.url}{url_suffix}")
assert function_httpmock.call_count == 1
GraphHelper.assert_triple_sets_equals(cached_graph((diverse_triples_path,)), g)
assert len(g) > 1
req = function_httpmock.requests[MethodName.GET].pop(0)
logging.debug("req = %s", req)
assert expected_request == req
|