Debian Codegraph @

tests/test_datalink.py

raw
1 """
2 Tests for the datalink subsystem and (potentially) special data tricks.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import atexit
12 import glob
13 import os
14 import time
15
16 from twisted.internet import reactor
17 from twisted.python import threadable
18 threadable.init()
19
20 from gavo.helpers import trialhelpers
21
22 from gavo import api
23
24
25 class SyncTest(trialhelpers.ArchiveTest):
26 def testInfoWorks(self):
27 return self.assertGETHasStrings("/data/cores/dl/info", {}, [
28 '<h2 id="svci-inputs" class="section">Input Fields</h2>',
29 "<td>The publisher DID of the dataset of interest</td>"])
30
31 def testErrorDocumentMetaGeneral(self):
32 return self.assertGETHasStrings("/data/cores/dl/dlmeta",
33 {"iD": "broken"},
34 ["<TD>Fault: name 'ddt' is not defined</TD>"])
35
36 def testErrorDocumentMetaNotFound(self):
37 return self.assertGETHasStrings("/data/cores/dl/dlmeta",
38 {"ID": "ivo://not.here"},
39 ["<TD>NotFoundFault: The authority in the dataset identifier 'ivo://not.here' could not be located in the authorities managed here</TD>"])
40
41 def testErrorDocumentAccess(self):
42 return self.assertGETHasStrings("/data/cores/dl/dlget",
43 {"id": "broken"},
44 ["name 'ddt' is not defined"])
45
46 def testErrorStatus(self):
47 return self.assertStatus("/data/cores/dl/dlget", 422)
48
49 def testWithoutId(self):
50 return self.assertGETHasStrings("/data/cores/dl/dlmeta", {}, [
51 "<TABLEDATA></TABLEDATA>",
52 "<FIELD",
53 'name="service_def"'])
54
55 def testMetadata(self):
56 return self.assertGETHasStrings("/data/cores/dl/dlmeta",
57 {"ID": "ivo://x-testing/~?data/excube.fits"}, [
58 'latitude coordinate</DESCRIPTION><VALUES><MIN value="30.98318158',
59 '</MIN><MAX value="30.98484850',
60 'xtype="interval"',
61 'name="QUERY_STATUS"',
62 'value="OK"'])
63
64 def testRespformat1(self):
65 return self.assertGETHasStrings("/data/cores/dl/dlmeta", {
66 "ID": "ivo://x-testing/~?data/excube.fits",
67 "RESPONSEFORMAT": "votable",
68 },
69 ['<DESCRIPTION>The latitude coordinate</DESCRIPTION>'
70 '<VALUES><MIN value="30.983181587',])
71
72 def testRespformat2(self):
73 return self.assertGETHasStrings("/data/cores/dl/dlmeta", {
74 "ID": "ivo://x-testing/~?data/excube.fits",
75 "RESPONSEFORMAT": "application/x-votable+xml",
76 },
77 ['<DESCRIPTION>The latitude coordinate</DESCRIPTION>'
78 '<VALUES><MIN value="30.983181587',])
79
80 def testServerSideRendering(self):
81 def makeMozillaRequest(request):
82 request.requestHeaders.setRawHeaders("user-agent", ["Mozilla"])
83
84 return self.assertGETHasStrings("/data/cores/dl/dlmeta", {
85 "ID": "ivo://x-testing/~?data/excube.fits",
86 }, [
87 'xmlns="http://www.w3.org/1999/xhtml"',
88 '<span class="low-limit">3.749e-07</span>',
89 'Broadcast dataset via SAMP</button>'],
90 rm=makeMozillaRequest)
91
92 def testInvalidRespformat(self):
93 def assertStatus422(res):
94 self.assertEqual(res[1].code, 422)
95
96 return self.assertGETHasStrings("/data/cores/dl/dlmeta", {
97 "ID": "ivo://x-testing/~?data/excube.fits",
98 "RESPONSEFORMAT": "vnd-microsoft/xls"
99 },
100 ["UsageError: Field responseformat: Value 'vnd-microsoft/xls' is not consistent with legal values ("]
101 ).addCallback(
102 assertStatus422)
103
104 def testRedirection(self):
105 def assertStatus301(res):
106 self.assertEqual(res[1].code, 301)
107
108 return self.assertGETHasStrings("/data/cores/dl/dlget", {
109 "ID": "somewhereelse",
110 },
111 ['<a href="http://some.whereel.se/there">different URL']).addCallback(
112 assertStatus301)
113
114 def testMetadataError(self):
115 return self.assertGETHasStrings("/data/cores/dl/dlmeta",
116 {"ID": "ivo://x-testing/~?data/excube.fit"},
117 ["TR><TD>ivo://x-testing/~?data/excube.fit</TD><TD></TD><TD></TD><TD>"
118 "NotFoundFault: accref 'data/excube.fit' could not be located"
119 " in product table</TD>"])
120
121 def testCubeCutout(self):
122 def assertNameGiven(res):
123 self.assertEqual(res[1].responseHeaders.getRawHeaders(
124 "content-disposition")[0],
125 "attachment; filename=data_excube_proc.fits")
126
127 return self.assertGETHasStrings("/data/cores/dl/dlget", {
128 "ID": "ivo://x-testing/~?data/excube.fits",
129 "BAND": "375.4e-9 +Inf"}, [
130 "NAXIS3 = 2",
131 "CRPIX3 = -1.0"]
132 ).addCallback(assertNameGiven)
133
134 def testVODMLSpectrum(self):
135 def assertMediatype(res):
136 self.assertEqual(
137 res[1].responseHeaders.getRawHeaders("content-type")[0],
138 "application/x-votable+xml;serialization=TABLEDATA;version=1.6")
139 self.assertEqual(
140 res[1].responseHeaders.getRawHeaders("content-disposition")[0],
141 "attachment; filename=test2_proc.vot6")
142
143 return self.assertGETHasStrings("/data/ssatest/dl/dlget", {
144 "FORMAT": "application/x-votable+xml;serialization=TABLEDATA;version=1.6",
145 "ID": "ivo://test.inv/test2"}, [
146 'dmtype="dachstoy:Location"',
147 '<mivot:ATTRIBUTE dmrole="y" ref="flux"/>',
148 "1755.0"]
149 ).addCallback(assertMediatype)
150
151 def testNoMultiArguments(self):
152 def assertErrorResponse(res):
153 self.assertEqual(res[1].code, 422)
154
155 return self.assertGETHasStrings("/data/cores/dl/dlget", {
156 "CIRCLE": ["10 10 5", "14 13 2"],
157 "ID": "ivo://x-testing/~?data/excube.fits"},
158 ["MultiValuedParamNotSupported: Field CIRCLE"]
159 ).addCallback(assertErrorResponse)
160
161 def testAvailability(self):
162 return self.assertGETHasStrings("/data/cores/dl/availability", {},
163 ["<avl:available>true</avl:available>"])
164
165 def testCapabilities(self):
166 return self.assertGETHasStrings("/data/cores/dl/capabilities", {}, [
167 'standardID="ivo://ivoa.net/std/DataLink#links-1.1"',
168 '/data/cores/dl/dlmeta</accessURL>',
169 '<ucd>meta.id;meta.main</ucd>'])
170
171 def testNoExtraSegments(self):
172 return self.assertGETHasStrings("/data/ssatest/dl/dlget/inv.test2", {
173 "ID": "ivo://test.inv/test2"},
174 ["Not Found (404)",
175 "dlget has no child resources</"])
176
177 def testCleanedup(self):
178 # this doesn't do any queries, it just makes sure that
179 # the datalink services above cleaned up after themselves
180 # (of course, we might see crap from the last run rather than
181 # from this, but statistically it should catch trouble.
182 pooLeft = glob.glob(
183 os.path.join(api.getConfig("tempDir"), "fitstable*"))
184 self.assertFalse(pooLeft, "Something left fitstable temporaries"
185 " in tempDir %s"%api.getConfig("tempDir"))
186
187 def testDECandPOS(self):
188 return self.assertGETHasStrings("/data/cores/dl/dlget", {
189 "ID": "ivo://x-testing/~?data/excube.fits",
190 "DEC": "30.9832 30.9834",
191 "POS": "CIRCLE 359.36 30.985 0.0004"},[
192 "UsageError: Field DEC: Attempt to cut out along axis 2"
193 " that has been modified before."])
194
195 def testPOSandPIXEL(self):
196 return self.assertGETHasStrings("/data/cores/dl/dlget", {
197 "ID": "ivo://x-testing/~?data/excube.fits",
198 "PIXEL_1": "1 3",
199 "POS": "CIRCLE 359.36 30.985 0.0004"},[
200 "UsageError: Field PIXEL_1: Attempt to cut out along axis 1"
201 " that has been modified before."])
202
203 def testEmptyResponse(self):
204 def assertResponseCode(res):
205 self.assertEqual(res[0], b"")
206 self.assertEqual(res[1].code, 204)
207
208 return self.assertGETLacksStrings("/data/cores/dl/dlget", {
209 "ID": "ivo://x-testing/~?data/excube.fits",
210 "POS": "CIRCLE 10 10 0.0001"},
211 [" "]).addCallback(
212 assertResponseCode)
213
214 def testMaxrecHonored(self):
215 def assertFullRows(res):
216 data, metadata = api.votable.loads(res[0])
217 rows = list(metadata.iterDicts(data))
218 # 10+10 rows from our meta maker, plus the #this links for them
219 self.assertEqual(set(r["ID"] for r in rows), {'p0', 'p1'})
220 self.assertEqual(len(rows), 22)
221 return res
222
223 return self.assertGETHasStrings("/data/cores/maxrecdl/dlmeta", {
224 "ID": ["p"+str(i) for i in range(10)],
225 "MAXREC": "15"}, [
226 'name="QUERY_STATUS"',
227 'value="OVERFLOW"']).addCallback(
228 assertFullRows)
229
230
231 def killLocalhost(url):
232 """should delete the host part from url.
233
234 Well, this only works for a very special case and is easy to improve :-)
235 """
236 return url[21:]
237
238
239 # workaround for 2019 trial failure to have the reactor running in
240 # time.
241 from gavo.protocols.uws import ProcessBasedUWSTransitions
242 ProcessBasedUWSTransitions.trial_forceTwisted = True
243
244 class AsyncTest(trialhelpers.ArchiveTest):
245 def testNonExistingJobMessage(self):
246 return self.assertGETHasStrings("/data/cores/dl/dlasync/thisjobidisbad",
247 {}, [
248 'name="QUERY_STATUS"',
249 'value="ERROR"',
250 "UWS job 'thisjobidisbad' could not be located in jobs table"])
251
252 def testNonExistingJobStatus(self):
253 return self.assertStatus("/data/cores/dl/dlasync/thisjobidisbad",
254 404)
255
256 def testJoblist(self):
257 return self.assertGETHasStrings("/data/cores/dl/dlasync",
258 {}, [
259 "/static/xsl/dlasync-joblist-to-html.xsl",
260 "<uws:jobs"])
261
262 def testBasicCutout(self):
263 # this is a pretty close clone of testLifeCycle in test_tap, and
264 # whatever's said there applies here, too.
265 def assertDeleted(result, jobURL):
266 self.assertEqual(result[1].code, 303)
267 next = killLocalhost(result[1].getLocationValue())
268 jobId = jobURL.split("/")[-1]
269 return self.assertGETLacksStrings(next, {}, ['jobref id="%s"'%jobId]
270 ).addCallback(lambda res: reactor.disconnectAll())
271
272 def deleteJob(jobURL):
273 return trialhelpers.runQuery(self.renderer, "DELETE",
274 jobURL, {}
275 ).addCallback(assertDeleted, jobURL)
276
277 def checkResult(result, jobURL):
278 self.assertEqual(
279 result[1].responseHeaders.getRawHeaders("content-type")[0],
280 "application/fits")
281 self.assertTrue(b"NAXIS1 = 11" in result[0])
282 return deleteJob(jobURL)
283
284 def waitForResult(result, jobURL, retry):
285 if retry>300:
286 raise AssertionError("Datalink job at jobURL %s didn't finish."
287 " Leaving it for inspection."%jobURL)
288 if result[0].startswith(b"COMPLETED"):
289 return trialhelpers.runQuery(self.renderer, "GET",
290 jobURL+"/results/result", {}
291 ).addCallback(checkResult, jobURL)
292 if result[0].startswith(b"ERROR"):
293 raise AssertionError(f"Datalink job at {jobURL} errored out.")
294
295 time.sleep(0.1)
296 return trialhelpers.runQuery(self.renderer, "GET",
297 jobURL+"/phase", {}
298 ).addCallback(waitForResult, jobURL, retry+1)
299
300 def assertStarted(result, jobURL):
301 req = result[1]
302 self.assertEqual(req.code, 303)
303 self.assertEqual(killLocalhost(req.getLocationValue()), jobURL)
304 return waitForResult((b"", None), jobURL, 0)
305
306 def startJob(jobURL):
307 return trialhelpers.runQuery(self.renderer, "POST",
308 jobURL+"/phase", {"PHASE": "RUN"}
309 ).addCallback(assertStarted, jobURL)
310
311 def checkPosted(result):
312 request = result[1]
313 self.assertEqual(request.code, 303)
314 jobURL = request.getLocationValue()
315 self.assertTrue(jobURL.startswith(
316 "http://localhost:8080/data/cores/dl/dlasync/"),
317 "Bad service URL on redirect")
318 return startJob(killLocalhost(jobURL))
319
320 return trialhelpers.runQuery(self.renderer, "POST",
321 "/data/cores/dl/dlasync", {
322 "ID": "ivo://x-testing/~?data/excube.fits",
323 "BAND": "375.4e-9 +Inf"}
324 ).addCallback(checkPosted)
325
326
327 class FromtableTest(trialhelpers.ArchiveTest):
328 def testBasic(self):
329 return self.assertGETHasStrings("/data/ssatest/fdbdl/dlmeta",
330 {"ID": "data/spec1.ssatest"}, [
331 "<TD>big fart nebula</TD>",
332 "<TD>Preview image</TD>",
333 "<TD>http://localhost:8080/data/spec1.ssatest</TD>",
334 "<TD>#this</TD>"
335 ])
336
337 def testNotFound(self):
338 return self.assertGETHasStrings("/data/ssatest/fdbdl/dlmeta",
339 {"ID": "duff_id"}, [
340 "<TD>NotFoundFault: No dataset with id duff_id known here</TD>"
341 ])
342
343 def testDLGet(self):
344 def assertRedirects(res):
345 self.assertEqual(res[1].code, 301)
346 self.assertEqual(
347 res[1].getLocationValue(),
348 "http://localhost:8080/data/spec1.ssatest")
349 return res
350
351 return self.assertGETHasStrings("/data/ssatest/fdbdl/dlget",
352 {"ID": "data/spec1.ssatest"}, [
353 "title>Unittest Suite -- Moved Permanently</title>"]
354 ).addCallback(assertRedirects)
355
356
357 class GetTarTest(trialhelpers.ArchiveTest):
358 # admittedly, this is not datalink, but while we have a non-trivial
359 # product table, try this, too
360
361 def assertMediaType(self, result):
362 self.assertEqual(
363 result[1].responseHeaders.getRawHeaders("content-type")[0],
364 "application/x-tar")
365 return result
366
367 def testTarDelivered(self):
368 return self.assertGETHasStrings("/__system__/products/getTar/get",
369 {"accref": ["data/ex.fits", "data/spec1.ssatest"]}, [
370 "\0\0\0\0\0\0\0", # tars have lots of 0-runs
371 "dc_data/ex.fits", # tar header one
372 "166.912408", # from ex.fits
373 "dc_data/spec1.ssatest", # second tar header
374 "alpha: 10.1", # content of spec1
375 ]).addCallback(self.assertMediaType)
376
377
378 atexit.register(trialhelpers.provideRDData("test", "import_fitsprod"))
379 atexit.register(trialhelpers.provideRDData("ssatest", "test_import"))