Debian Codegraph @

tests/test_rdflib_endpoint.py

raw
1 import pytest
2 from example.main import custom_concat
3 from fastapi.testclient import TestClient
4 from rdflib import RDFS, Graph, Literal, URIRef
5
6 from rdflib_endpoint import SparqlEndpoint
7 from rdflib_endpoint.sparql_router import SD
8
9 # graph = Dataset(default_union=False)
10 graph = Graph()
11
12
13 @pytest.fixture(autouse=True)
14 def clear_graph():
15 # Workaround to clear graph without putting
16 # graph, app and endpoint into a fixture
17 # and modifying the test fixture usage.
18 for triple in graph:
19 graph.remove(triple)
20
21
22 app = SparqlEndpoint(
23 graph=graph,
24 functions={
25 "https://w3id.org/sparql-functions/custom_concat": custom_concat,
26 },
27 enable_update=True,
28 )
29
30 endpoint = TestClient(app)
31
32
33 def test_service_description():
34 # Check GET turtle
35 response = endpoint.get("/", headers={"accept": "text/turtle"})
36 assert response.status_code == 200
37 g = Graph()
38 g.parse(data=response.text, format="turtle")
39 assert any(g.triples((None, SD.endpoint, None))), "Missing sd:endpoint in service description"
40 assert any(g.triples((None, SD.extensionFunction, None))), "Missing sd:extensionFunction in service description"
41 assert len(list(g.triples((None, SD.extensionFunction, None)))) == 1, "Expected exactly 1 extension function"
42
43 # Check POST XML
44 response = endpoint.post("/", headers={"accept": "application/xml"})
45 assert response.status_code == 200
46 g = Graph()
47 g.parse(data=response.text, format="xml")
48 assert any(g.triples((None, SD.endpoint, None))), "Missing sd:endpoint in service description"
49 assert any(g.triples((None, SD.extensionFunction, None))), "Missing sd:extensionFunction in service description"
50 assert len(list(g.triples((None, SD.extensionFunction, None)))) == 1, "Expected exactly 1 extension function"
51
52
53 def test_custom_concat_json():
54 response = endpoint.get("/", params={"query": concat_select}, headers={"accept": "application/json"})
55 # print(response.json())
56 assert response.status_code == 200
57 assert response.json()["results"]["bindings"][0]["concat"]["value"] == "Firstlast"
58
59 response = endpoint.post("/", data={"query": concat_select}, headers={"accept": "application/json"})
60 assert response.status_code == 200
61 assert response.json()["results"]["bindings"][0]["concat"]["value"] == "Firstlast"
62
63 response = endpoint.post(
64 "/", data=concat_select, headers={"accept": "application/json", "content-type": "application/sparql-query"}
65 )
66 assert response.status_code == 200
67 assert response.json()["results"]["bindings"][0]["concat"]["value"] == "Firstlast"
68
69
70 def test_select_noaccept_xml():
71 response = endpoint.post("/", data={"query": concat_select})
72 assert response.status_code == 200
73 assert response.text.startswith("<?xml ")
74
75
76 def test_select_csv():
77 response = endpoint.post("/", data={"query": concat_select}, headers={"accept": "text/csv"})
78 assert response.status_code == 200
79
80
81 label_patch = """
82 PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
83 DELETE { ?subject rdfs:label "foo" }
84 INSERT { ?subject rdfs:label "bar" }
85 WHERE { ?subject rdfs:label "foo" }
86 """
87
88
89 @pytest.mark.parametrize(
90 "api_key,key_provided,param_method",
91 [
92 (api_key, key_provided, param_method)
93 for api_key in [None, "key"]
94 for key_provided in [True, False]
95 for param_method in ["body_form", "body_direct"]
96 ],
97 )
98 def test_sparql_update(api_key, key_provided, param_method, monkeypatch):
99 if api_key:
100 monkeypatch.setenv("RDFLIB_APIKEY", api_key)
101 subject = URIRef("http://server.test/subject")
102 headers = {}
103 if key_provided:
104 headers["Authorization"] = "Bearer key"
105 graph.add((subject, RDFS.label, Literal("foo")))
106 if param_method == "body_form":
107 request_args = {"data": {"update": label_patch}}
108 else:
109 # direct
110 headers["content-type"] = "application/sparql-update"
111 request_args = {"data": label_patch}
112 response = endpoint.post("/", headers=headers, **request_args)
113 if api_key is None or key_provided:
114 assert response.status_code == 204
115 assert (subject, RDFS.label, Literal("foo")) not in graph
116 assert (subject, RDFS.label, Literal("bar")) in graph
117 else:
118 assert response.status_code == 403
119 assert (subject, RDFS.label, Literal("foo")) in graph
120 assert (subject, RDFS.label, Literal("bar")) not in graph
121
122
123 def test_sparql_query_update_fail():
124 response = endpoint.post("/", data={"update": label_patch, "query": label_patch})
125 assert response.status_code == 400
126
127
128 def test_multiple_accept_return_json():
129 response = endpoint.get(
130 "/",
131 params={"query": concat_select},
132 headers={"accept": "text/html;q=0.3, application/xml;q=0.9, application/json, */*;q=0.8"},
133 )
134 assert response.status_code == 200
135 assert response.json()["results"]["bindings"][0]["concat"]["value"] == "Firstlast"
136
137
138 def test_multiple_accept_return_json2():
139 response = endpoint.get(
140 "/",
141 params={"query": concat_select},
142 headers={"accept": "text/html;q=0.3, application/json, application/xml;q=0.9, */*;q=0.8"},
143 )
144 assert response.status_code == 200
145 assert response.json()["results"]["bindings"][0]["concat"]["value"] == "Firstlast"
146
147
148 def test_select_turtle():
149 response = endpoint.post("/", data={"query": concat_select}, headers={"accept": "text/turtle"})
150 assert response.status_code == 200
151 assert response.headers["content-type"] == "application/sparql-results+xml"
152
153
154 def test_concat_construct_turtle():
155 response = endpoint.post(
156 "/",
157 data={"query": custom_concat_construct},
158 headers={"accept": "text/turtle"},
159 )
160 assert response.status_code == 200
161 assert response.text.startswith("@prefix ")
162
163
164 def test_concat_construct_csv():
165 response = endpoint.post(
166 "/",
167 data={"query": custom_concat_construct},
168 headers={"accept": "text/csv"},
169 )
170 assert response.status_code == 200
171 assert response.text.startswith("@prefix ")
172
173
174 def test_concat_construct_jsonld():
175 response = endpoint.post(
176 "/",
177 data={"query": custom_concat_construct},
178 headers={"accept": "application/json"},
179 )
180 assert response.status_code == 200
181 assert response.json()[0]["@id"] == "http://example.com/test"
182
183
184 def test_concat_construct_xml():
185 # expected to return turtle
186 response = endpoint.post(
187 "/",
188 data={"query": custom_concat_construct},
189 headers={"accept": "application/xml"},
190 )
191 assert response.status_code == 200
192 assert response.text.startswith("<?xml ")
193
194
195 def test_concat_construct_rdf_xml_with_two_accept_options():
196 response = endpoint.post(
197 "/",
198 data={"query": custom_concat_construct},
199 headers={"accept": "application/sparql-results+xml, application/rdf+xml"},
200 )
201 assert response.status_code == 200
202 assert response.headers["content-type"] == "application/rdf+xml"
203 assert response.text.startswith("<?xml ")
204 assert "<rdf:RDF" in response.text
205
206
207 def test_yasgui():
208 # expected to return turtle
209 response = endpoint.get(
210 "/",
211 headers={"accept": "text/html"},
212 )
213 assert response.status_code == 200
214
215
216 def test_bad_request():
217 response = endpoint.get("/?query=figarofigarofigaro", headers={"accept": "application/json"})
218 assert response.status_code == 400
219
220
221 concat_select = """PREFIX myfunctions: <https://w3id.org/sparql-functions/>
222 SELECT ?concat ?concatLength WHERE {
223 BIND("First" AS ?first)
224 BIND(myfunctions:custom_concat(?first, "last") AS ?concat)
225 }"""
226
227 custom_concat_construct = """PREFIX myfunctions: <https://w3id.org/sparql-functions/>
228 CONSTRUCT {
229 <http://example.com/test> <http://example.com/concat> ?concat, ?concatLength .
230 } WHERE {
231 BIND("First" AS ?first)
232 BIND(myfunctions:custom_concat(?first, "last") AS ?concat)
233 }"""