Debian Codegraph @

tests/taptest.py

raw
1 """
2 Simple tests for TAP.
3
4 All these tests really stink because TAP isn't really a good match for the
5 basically stateless unit tests that are executed in an arbitrary order.
6
7 There's more TAP/UWS related tests in test_tap.py; these require a
8 running reactor and are based on trial.
9 """
10
11 #c Copyright 2008-2025, the GAVO project <[email protected]>
12 #c
13 #c This program is free software, covered by the GNU GPL. See the
14 #c COPYING file in the source distribution.
15
16
17 import datetime
18 import io
19 import functools
20 import os
21 import time
22
23 from gavo.helpers import testhelpers
24 from gavo.helpers import trialhelpers
25
26 from gavo import base
27 from gavo import rsc
28 from gavo import rscdef
29 from gavo import rscdesc # uws needs getRD
30 from gavo import svcs
31 from gavo import utils
32 from gavo import votable
33 from gavo.helpers import testtricks
34 from gavo.protocols import adqlglue
35 from gavo.protocols import tap
36 from gavo.protocols import taprunner
37 from gavo.protocols import uws
38 from gavo.protocols import uwsactions
39 from gavo.registry import capabilities
40 from gavo.web import tap_uploads
41 from gavo.web import vosi
42
43 import adqltest
44 import tresc
45
46 @functools.lru_cache(None)
47 def _getTAPService():
48 return base.caches.getRD("//tap").getById("run")
49
50 @functools.lru_cache(None)
51 def _getTAPParGrammar():
52 return _getTAPService().getContextGrammarFor("sync", None)
53
54
55 class TAPFakeRequest(trialhelpers.FakeRequest):
56 def __init__(self, *posargs, **kwargs):
57 super().__init__(*posargs, **kwargs)
58 uws.prepareRequest(self, _getTAPService())
59 self.asyncGrammar = _getTAPParGrammar()
60
61 def _makeATAPJob(pars):
62 """returns a job id for a TAP job described by pars.
63
64 pars needs to be like request.strargs.
65 """
66 return tap.WORKER_SYSTEM.getNewJobId(
67 parameters=_getTAPParGrammar().parseStrargs(pars, ensureRequired=False))
68
69
70 class TestVersionParsing(testhelpers.VerboseTest):
71 def testSupportedLang(self):
72 self.assertEqual(
73 taprunner._assertSupportedLanguage(None, "ADQL"), None)
74
75 def testSupportedLangVersion(self):
76 self.assertEqual(
77 taprunner._assertSupportedLanguage(None, "ADQL-2.0"), None)
78
79 def testAnotherSupportedLangVersion(self):
80 self.assertEqual(
81 taprunner._assertSupportedLanguage(None, "ADQL-2.1"), None)
82
83 def testUnsupportedLang(self):
84 self.assertRaisesWithMsg(
85 uws.UWSError,
86 "This service does not support the query language ShittyQL",
87 taprunner._assertSupportedLanguage,
88 (None, "ShittyQL"))
89
90 def testUnsupportedVersion(self):
91 self.assertRaisesWithMsg(
92 uws.UWSError,
93 "This service does not support version 30.12-pre_foo of the query"
94 " language ADQL (but some other version; see capabilities).",
95 taprunner._assertSupportedLanguage,
96 (None, "ADQL-30.12-pre_foo"))
97
98
99 class TestResponseformat(testhelpers.VerboseTest):
100 def testRejection(self):
101 self.assertRaises(base.ValidationError,
102 _getTAPService().run,
103 "sync", {
104 "query": ["ignore"], "lang": ["ADQL"],
105 "responseformat": ["xls"]},
106 None)
107
108 def testAlias(self):
109 args = {"lang": ["ADQL"], "responseformat": ["votable/td"],
110 "query": ["SELECT TOP 1 * FROM tap_schema.tables"]}
111 f, mediaType = base.resolveCrossId("//tap#run").run("sync",
112 _getTAPParGrammar().parseStrargs(args),
113 svcs.QueryMeta(args))
114 self.assertEqual(mediaType,
115 "application/x-votable+xml;serialization=TABLEDATA")
116 self.assertEqual(f.read()[-50:],
117 b"R></TABLEDATA></DATA></TABLE></RESOURCE></VOTABLE>")
118 f.close()
119
120 def testPreservedMediaType(self):
121 args = {"lang": ["ADQL"], "responseformat": ["text/xml"],
122 "query": ["SELECT TOP 1 * FROM tap_schema.tables"]}
123 f, mediaType = base.resolveCrossId("//tap#run").run("sync",
124 _getTAPParGrammar().parseStrargs(args),
125 svcs.QueryMeta(args))
126 self.assertEqual(mediaType, "text/xml")
127 # I take it that text/xml ought to be formattable with XSLT, and
128 # hence we want tabledata.
129 self.assertEqual(f.read()[-50:],
130 b"R></TABLEDATA></DATA></TABLE></RESOURCE></VOTABLE>")
131 f.close()
132
133
134 class PlainJobCreationTest(testhelpers.VerboseTest):
135 """tests for working job creation and destruction.
136 """
137 resources = [("conn", tresc.dbConnection)]
138
139 def _createJob(self):
140 # pass in an invalid key so we can see that it's swallowed.
141 return _makeATAPJob({"foo": "bar"})
142
143 def _deleteJob(self, jobId):
144 return tap.WORKER_SYSTEM.destroy(jobId)
145
146 def _assertJobCreated(self, jobId):
147 res = list(self.conn.query(
148 "SELECT jobId FROM tap_schema.tapjobs WHERE"
149 " jobId=%(jobId)s", locals()))
150 self.assertEqual(len(res), 1)
151 job = tap.WORKER_SYSTEM.getJob(jobId)
152 self.assertFalse("foo" in job.parameters)
153 self.assertTrue(os.path.exists(job.getWD()))
154
155 def _assertJobDeleted(self, jobId):
156 res = list(self.conn.query(
157 "SELECT destructiontime FROM tap_schema.tapjobs"
158 " WHERE jobId=%(jobId)s", locals()))
159 self.assertEqual(len(res), 0)
160 self.assertRaises(base.NotFoundError, tap.WORKER_SYSTEM.getJob, jobId)
161 self.assertFalse(
162 os.path.exists(
163 os.path.join(base.getConfig("uwsWD"), jobId)))
164
165 def _assertUnqueueable(self, jobId):
166 # we're missing all the relevant parameters, and hence the
167 # this needs to blow up when we try to queue the job
168 tap.WORKER_SYSTEM.changeToPhase(jobId, uws.QUEUED)
169 job = tap.WORKER_SYSTEM.getJob(jobId)
170 self.assertEqual(job.phase, uws.ERROR)
171 self.assertEqual(job.error["msg"],
172 "Field lang: Required parameter 'lang' missing.")
173
174 def testBigAndUgly(self):
175 # this may leave its job behind if the assertions fail. They'll
176 # eventually be garbage-collected by DaCHS, so I don't worry too much.
177 jobId = self._createJob()
178 self._assertJobCreated(jobId)
179 self._assertUnqueueable(jobId)
180 self._deleteJob(jobId)
181 self._assertJobDeleted(jobId)
182
183
184 class _UWSJobResource(testhelpers.TestResource):
185 # just a UWS job. Don't manipulate it. Too badly.
186 def make(self, ignored):
187 return tap.WORKER_SYSTEM.getNewJobId()
188
189 def clean(self, jobId):
190 tap.WORKER_SYSTEM.destroy(jobId.original)
191
192 _uwsJobResource = _UWSJobResource()
193
194
195 class TAPParametersTest(testhelpers.VerboseTest):
196 resources = [("jobIdResource", _uwsJobResource)]
197
198 def setUp(self):
199 testhelpers.VerboseTest.setUp(self)
200 self.jobId = self.jobIdResource.original
201
202 def testRepeatedSetting(self):
203 with tap.WORKER_SYSTEM.changeableJob(self.jobId) as job:
204 job.setParamsFromDict({"a": ["ob"], "b": ["knapp"]})
205 self.assertEqual(job.parameters["a"], ["ob"])
206 job.setParamsFromDict({"a": ["ja"], "b": []})
207 self.assertEqual(job.parameters["a"], ["ob", "ja"])
208 self.assertEqual(job.parameters["b"], ["knapp"])
209
210
211 class UWSResponsesValidTest(testhelpers.VerboseTest, testtricks.XSDTestMixin):
212 resources = [("jobIdResource", _uwsJobResource)]
213
214 def setUp(self):
215 testhelpers.VerboseTest.setUp(self)
216 self.jobId = self.jobIdResource.original
217
218 def testJobRes(self):
219 job = tap.WORKER_SYSTEM.getJob(self.jobId)
220 self.assertValidates(uwsactions.RootAction().doGET(
221 job, TAPFakeRequest()),
222 leaveOffending=True)
223
224 def testJobList(self):
225 self.assertValidates(uwsactions.getJobList(tap.WORKER_SYSTEM),
226 leaveOffending=True)
227
228
229 class BlockingTest(testhelpers.VerboseTest):
230 """tests for working impicit uws locking.
231 """
232 resources = [("jobIdResource", _uwsJobResource)]
233
234 def setUp(self):
235 testhelpers.VerboseTest.setUp(self)
236 self.jobId = self.jobIdResource.original
237
238 def testIndexDoesNotBlock(self):
239 with tap.WORKER_SYSTEM.changeableJob(self.jobId):
240 self.assertTrue(b"uws:jobs" in uwsactions.getJobList(tap.WORKER_SYSTEM))
241
242 def testGetPhaseDoesNotBlock(self):
243 req = TAPFakeRequest()
244 with tap.WORKER_SYSTEM.changeableJob(self.jobId):
245 self.assertEqual(
246 uwsactions.doJobAction(tap.WORKER_SYSTEM, req, (self.jobId, "phase")),
247 "PENDING")
248
249 def testPostPhaseDoesBlock(self):
250 req = TAPFakeRequest(args={"PHASE": ["RUN"]})
251 req.method = b"POST"
252 uwsactions.PhaseAction.timeout = 0.05
253 with tap.WORKER_SYSTEM.changeableJob(self.jobId):
254 self.assertRaisesWithMsg(base.ReportableError,
255 "Could not access the jobs table. This probably means"
256 " there is a stale lock on it. Please notify the service operators.",
257 uwsactions.doJobAction,
258 (tap.WORKER_SYSTEM, req, (self.jobId, "phase")))
259
260
261 class QueueTest(testhelpers.VerboseTest):
262 def testQuote(self):
263 now = datetime.datetime.utcnow()
264 tick = datetime.timedelta(minutes=15)
265 jobs = []
266 try:
267 jobId = tap.WORKER_SYSTEM.getNewJobId()
268 with tap.WORKER_SYSTEM.changeableJob(jobId) as wjob:
269 wjob.change(phase=uws.QUEUED, destructionTime=now+10*tick)
270 jobs.append(jobId)
271
272 testJob = tap.WORKER_SYSTEM.getJob(jobId)
273 # don't fail just because jobs are left in the queue
274 baseDelay = testJob.quote-now
275
276 jobId = tap.WORKER_SYSTEM.getNewJobId()
277 with tap.WORKER_SYSTEM.changeableJob(jobId) as wjob:
278 wjob.change(phase=uws.QUEUED, destructionTime=now+9*tick)
279 jobs.append(jobId)
280
281 # our quote must now be roughly 10 minutes (as configured in
282 # tap.EST_TIME_PER_JOB) later
283 self.assertEqual((testJob.quote-now-baseDelay).seconds/10,
284 tap.EST_TIME_PER_JOB.seconds/10)
285
286 jobId = tap.WORKER_SYSTEM.getNewJobId()
287 with tap.WORKER_SYSTEM.changeableJob(jobId) as wjob:
288 wjob.change(phase=uws.QUEUED, destructionTime=now+11*tick)
289 jobs.append(jobId)
290
291 # the new job will run later then our test job, so no change
292 # expected
293 self.assertEqual((testJob.quote-now-baseDelay).seconds/10,
294 tap.EST_TIME_PER_JOB.seconds/10)
295
296 finally:
297 for jobId in jobs:
298 tap.WORKER_SYSTEM.destroy(jobId)
299
300
301 class TAPTransitionsTest(testhelpers.VerboseTest):
302 def testAbortPending(self):
303 jobId = None
304 try:
305 jobId = tap.WORKER_SYSTEM.getNewJobId(
306 parameters={"query": "bogus", "request": "doQuery",
307 "LANG": "ADQL-2.0"})
308 tap.WORKER_SYSTEM.changeToPhase(jobId, uws.ABORTED)
309 self.assertEqual(tap.WORKER_SYSTEM.getJob(jobId).phase,
310 uws.ABORTED)
311 finally:
312 tap.WORKER_SYSTEM.destroy(jobId)
313
314
315 class UploadSyntaxOKTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
316 def _runTest(self, sample):
317 s, e = sample
318 self.assertEqual(tap.parseUploadString(s), e)
319
320 samples = [
321 ('a,b', [('a', 'b'),]),
322 ('a5_ug,http://knatter?RA=99&DEC=1.54',
323 [('a5_ug', 'http://knatter?RA=99&DEC=1.54'),]),
324 ('a5_ug,http://knatter?RA=99&DEC=1.54;a,b',
325 [('a5_ug', 'http://knatter?RA=99&DEC=1.54'), ('a', 'b')]),]
326
327
328 class UploadSyntaxNotOKTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
329 def _runTest(self, sample):
330 self.assertRaises(base.ValidationError, tap.parseUploadString,
331 sample)
332
333 samples = [
334 'a,',
335 ',http://wahn',
336 'a,b;',
337 'a,b;whacky/name,b',]
338
339
340 class _TAPCapDocument(testhelpers.TestResource):
341 def make(self, ignored):
342 pub = base.caches.getRD("//tap").getById("run").publications[0]
343 doc = vosi.CAP.capabilities[capabilities.getCapabilityElement(pub)
344 ].render()
345 return doc, testhelpers.getXMLTree(doc, debug=False)
346
347
348 class CapabilitiesTest(testhelpers.VerboseTest, testtricks.XSDTestMixin):
349 resources = [("dt", _TAPCapDocument())]
350
351 def testValid(self):
352 self.assertValidates(self.dt[0], leaveOffending=True)
353
354 def testFunctionsSorted(self):
355 funcs = [n.text for n in
356 self.dt[1].xpath("//languageFeatures[@type='ivo://ivoa.net/std/"
357 "TAPRegExt#features-udf']/feature/form")]
358 self.assertEqual(list(sorted(funcs)), funcs)
359
360 def testUploadMethods(self):
361 ums = set(n.get("ivo-id") for n in self.dt[1].xpath("//uploadMethod"))
362 self.assertEqual(set(ums),
363 set("ivo://ivoa.net/std/TAPRegExt#upload-"+s
364 for s in ("inline", "http", "https", "ftp")))
365
366 def testType(self):
367 self.assertEqual(self.dt[1].xpath("capability[1]")[0].get(
368 "{http://www.w3.org/2001/XMLSchema-instance}type"),
369 "tr:TableAccess")
370
371 def testInterface(self):
372 intfs = self.dt[1].xpath("capability[1]/interface")
373 self.assertEqual(len(intfs), 2)
374 intf = intfs[0]
375 self.assertEqual(
376 intf.get("{http://www.w3.org/2001/XMLSchema-instance}type"),
377 "vs:ParamHTTP")
378
379 def testAccessURL(self):
380 self.assertEqual([n.text for n in
381 self.dt[1].xpath("capability/interface/accessURL")],
382 ["http://localhost:8080/tap", "http://localhost:8080/tap"])
383
384 def testForMode(self):
385 asyncLimit = testhelpers.pickSingle(self.dt[1].xpath(
386 "capability/uploadLimit[@forMode='async']/hard"))
387 self.assertEqual(asyncLimit.text, "20000000")
388 self.assertEqual(asyncLimit.get("unit"), "byte")
389
390
391 class TAPSchemaQueryTest(testhelpers.VerboseTest):
392 def setUp(self):
393 self.jobId = _makeATAPJob({
394 "query": ["SELECT TOP 1 * FROM TAP_SCHEMA.tables"],
395 "request": ["doQuery"],
396 "lang": ["ADQL-2.1"]})
397
398 def tearDown(self):
399 tap.WORKER_SYSTEM.destroy(self.jobId)
400
401 def testTAP_tables(self):
402 taprunner.runSyncTAPJob(self.jobId)
403 job = tap.WORKER_SYSTEM.getJob(self.jobId)
404 self.assertEqual(job.phase, uws.COMPLETED)
405 with open(job.getResult("result")[0]) as f:
406 res = f.read()
407 self.assertTrue('<RESOURCE type="results">' in res)
408
409
410 class _TAPSchemaContent(testhelpers.TestResource):
411 def make(self, deps):
412 rd = base.parseFromString(rscdesc.RD, """
413 <resource schema="schm" resdir="data">
414 <meta name="schema-rank">4000</meta>
415 <meta name="utype">ivo://ivoa.net/std/cool-model</meta>
416 <meta name="description">We actually don't test for empty
417 schema descriptions yet</meta>
418
419 <table id="nontap" onDisk="True">
420 <column name="col1" description="A column that should not appear
421 in tap_schema because its table isn't ADQL-visible"/>
422 </table>
423
424 <table id="boring" adql="True">
425 <column name="col1" type="spoly"/>
426 <column name="quoted/select" type="integer[20]"
427 utype="omg:array"/>
428 <viewStatement>
429 (it's fake)
430 </viewStatement>
431 </table>
432
433 <table id="tbl" adql="True" nrows="27">
434 <meta name="table-rank">1</meta>
435 <meta name="utype">adhoc:an.example.table</meta>
436 <meta name="description">An example table</meta>
437 <foreignKey source="col1,ivoa" inTable="boring" dest="col1,select"/>
438 <column name="col1" ucd="src.sample" utype="adhoc:tbl.col1"
439 description="A column with a UCD of src.sample"
440 unit="km/s"/>
441 <column name="ivoa">
442 <property name="std">1</property>
443 </column>
444 </table>
445 </resource>""")
446
447 rows = {}
448 tapRD = base.caches.getRD("//tap")
449
450 # tables is a dispatching grammar
451 dd = tapRD.getById("importTablesFromRD")
452 for dest, row in dd.grammar.parse(rd):
453 del row["parser_"]
454 rows.setdefault(dest, []).append(row)
455
456 for ddId in ["importDMsFromRD", "importColumnsFromRD",
457 "importFkeysFromRD", "importGroupsFromRD"]:
458 dd = tapRD.getById(ddId)
459 rows[dd.makes[0].table.id
460 ] = list(dd.grammar.parse(rd))
461
462 return rows
463
464
465 class TAPSchemaCreationTest(testhelpers.VerboseTest):
466 resources = [("rows", _TAPSchemaContent())]
467
468 def testSchemaRow(self):
469 row = testhelpers.pickSingle(self.rows["schemas"])
470 self.assertEqual(row, {
471 'schema_description': "We actually don't test for"
472 " empty schema descriptions yet",
473 'schema_index': '4000',
474 'schema_name': 'schm',
475 'schema_utype': 'ivo://ivoa.net/std/cool-model'})
476
477 def testRankedTable(self):
478 rows = [r for r in self.rows["tables"] if r["table_name"]=="schm.tbl"]
479 self.assertEqual(testhelpers.pickSingle(rows), {'nrows': 27,
480 'schema_name': 'schm',
481 'sourceRD': 'temporary',
482 'table_description': 'An example table',
483 'table_index': '1',
484 'table_name': 'schm.tbl',
485 'table_type': 'table',
486 'table_utype': 'adhoc:an.example.table'})
487
488 def testNonADQLTable(self):
489 for r in self.rows["tables"]:
490 if "nontap" in r["table_name"]:
491 raise AssertionError("non-ADQL table in tap_schema?")
492
493 def testPlainTable(self):
494 row = testhelpers.pickSingle(
495 [r for r in self.rows["tables"] if r["table_name"]=="schm.boring"])
496 self.assertEqual(row, {'nrows': None,
497 'schema_name': 'schm',
498 'sourceRD': 'temporary',
499 'table_description': "We actually don't test for empty schema"
500 " descriptions yet",
501 'table_index': None,
502 'table_name': 'schm.boring',
503 'table_type': 'view',
504 'table_utype': None})
505
506 def testColumnUtype(self):
507 row = testhelpers.pickSingle([r for r in self.rows["columns"]
508 if r["utype"]=="adhoc:tbl.col1"])
509 self.assertEqual(row["datatype"], "float")
510 self.assertEqual(row["column_name"], "col1")
511 self.assertEqual(row["ucd"], "src.sample")
512 self.assertEqual(row["utype"], "adhoc:tbl.col1")
513 self.assertEqual(row["unit"], "km/s")
514 self.assertEqual(row["description"],
515 "A column with a UCD of src.sample")
516
517 def testXtype(self):
518 row = testhelpers.pickSingle([r for r in self.rows["columns"]
519 if r["xtype"]=="polygon"])
520 self.assertEqual(row["column_name"], "col1")
521 self.assertEqual(row["xtype"], "polygon")
522 self.assertEqual(row["datatype"], "double")
523 self.assertEqual(row["arraysize"], "*")
524
525 def testQuotedColname(self):
526 row = testhelpers.pickSingle([r for r in self.rows["columns"]
527 if r["utype"]=="omg:array"])
528 self.assertEqual(str(row["column_name"]), '"select"')
529
530 def testSizedArray(self):
531 row = testhelpers.pickSingle([r for r in self.rows["columns"]
532 if r["utype"]=="omg:array"])
533 self.assertEqual(row["arraysize"], '20')
534 self.assertEqual(row["datatype"], "int")
535 self.assertEqual(row["size"], 20)
536
537 def testStd(self):
538 row = testhelpers.pickSingle([r for r in self.rows["columns"]
539 if r["column_name"]=="ivoa"])
540 self.assertEqual(row["std"], 1)
541
542 def testKeys(self):
543 # Update the grammar to be dispatching and then this test, too
544 rows = self.rows["keys"]
545 self.assertEqual(len(rows), 3)
546 self.assertEqual(rows[0]["from_table"], "schm.tbl")
547 self.assertEqual(rows[0]["target_table"], "schm.boring")
548
549 self.assertEqual(rows[1]["from_column"], "col1")
550 self.assertEqual(rows[1]["target_column"], "col1")
551
552 self.assertEqual(rows[2]["from_column"], "ivoa")
553 # TODO: select should probably be quoted here.
554 self.assertEqual(rows[2]["target_column"], "select")
555
556 self.assertEqual(len(set(r["key_id"] for r in rows)), 1)
557
558 # todo?: groups (but then it's been ages since we've last heard of it)
559
560 class EvilUploadTest(testhelpers.VerboseTest):
561 def _runWithUpload(self, query, uploadContent):
562 jobId = _makeATAPJob({
563 "query": [query],
564 "request": ["doQuery"],
565 "lang": ["ADQL"],
566 "responseformat": ["votable/td"],
567 "upload": [("t1", "file://evil.vot")]})
568
569 job = tap.WORKER_SYSTEM.getJob(jobId)
570 with testhelpers.testFile("evil.vot", uploadContent,
571 inDir=job.getWD()):
572 try:
573 taprunner.runSyncTAPJob(jobId)
574 job = tap.WORKER_SYSTEM.getJob(jobId)
575 self.assertEqual(job.phase, uws.COMPLETED)
576 with open(job.getResult("result")[0]) as f:
577 return f.read()
578 finally:
579 tap.WORKER_SYSTEM.destroy(jobId)
580
581 def testEvilColnameAndXtype(self):
582 # because running these tests is expensive, I'm abusing this
583 # to also test for fantasy xtype roundtripping.
584 result = self._runWithUpload(
585 "SELECT * FROM TAP_SCHEMA.tables join TAP_UPLOAD.t1 ON oid=table_index",
586 """<VOTABLE version="1.2"
587 xmlns="http://www.ivoa.net/xml/VOTable/v1.2">
588 <RESOURCE>
589 <TABLE name="holler" nrows="1">
590 <FIELD datatype="long" name="oid" ucd="meta.record;meta.id"
591 xtype="magic:oid"/>
592 <DATA><TABLEDATA><TR><TD>1</TD></TR></TABLEDATA></DATA>
593 </TABLE>
594 </RESOURCE>
595 </VOTABLE>""")
596 self.assertTrue('name="oid"' in result)
597 self.assertTrue('xtype="magic:oid"' in result)
598
599 def testArrayWithNaN(self):
600 result = self._runWithUpload(
601 "SELECT column_index FROM TAP_SCHEMA.columns join TAP_UPLOAD.t1 ON"
602 " column_index between intv[1] and intv[2]",
603 """<VOTABLE xmlns="http://www.ivoa.net/xml/VOTable/v1.3">
604 <RESOURCE><TABLE>
605 <FIELD datatype="float" arraysize="2" name="intv"/>
606 <DATA><TABLEDATA>
607 <TR><TD>1.5 2.5</TD></TR>
608 <TR><TD>4.9 NaN</TD></TR>
609 <TR><TD>NaN NaN</TD></TR>
610 </TABLEDATA></DATA>
611 </TABLE></RESOURCE></VOTABLE>""")
612 self.assertTrue("<TD>2</TD>" in result)
613 self.assertFalse("<TD>5</TD>" in result)
614
615
616 def _getUnparsedQueryResult(query):
617 jobId = _makeATAPJob({
618 "query": [query],
619 "request": ["doQuery"],
620 "lang": ["ADQL"]})
621 try:
622 taprunner.runSyncTAPJob(jobId)
623 job = tap.WORKER_SYSTEM.getJob(jobId)
624 if job.phase==uws.ERROR:
625 raise Exception("Job died with msg %s"%job.error)
626 name, mime = job.getResult("result")
627 with open(name, "rb") as f:
628 res = f.read()
629 finally:
630 tap.WORKER_SYSTEM.destroy(jobId)
631 return res
632
633
634 def _getQueryResult(query):
635 # returns a votable.simple result for query.
636 vot = _getUnparsedQueryResult(query)
637 res = votable.load(io.BytesIO(vot))
638 return res
639
640
641 class SimpleRunnerTest(testhelpers.VerboseTest):
642 """tests various taprunner scenarios.
643 """
644 resources = [("ds", adqltest.adqlTestTable)]
645
646 def setUp(self):
647 testhelpers.VerboseTest.setUp(self)
648 self.tableName = self.ds.tables["adql"].tableDef.getQName()
649
650 def testSimpleJob(self):
651 jobId = _makeATAPJob({
652 "query": ["SELECT * FROM %s"%self.tableName],
653 "request": ["doQuery"],
654 "lang": ["ADQL"]})
655 try:
656 job = tap.WORKER_SYSTEM.getJob(jobId)
657 self.assertEqual(job.phase, uws.PENDING)
658 tap.WORKER_SYSTEM.changeToPhase(jobId, uws.QUEUED, None)
659
660 runningPhases = set([uws.QUEUED, uws.UNKNOWN, uws.EXECUTING])
661 # let things run, but bail out if nothing happens
662 for i in range(200):
663 time.sleep(0.1)
664 job.update()
665 if job.phase not in runningPhases:
666 break
667 else:
668 raise AssertionError("Job does not finish. Your machine cannot be"
669 " *that* slow?")
670
671 self.assertEqual(job.phase, uws.COMPLETED)
672 with open(os.path.join(job.getWD(),
673 job.getResults()[0]["resultName"]), "rb") as f:
674 result = f.read()
675 self.assertTrue((datetime.datetime.utcnow()-job.endTime).seconds<1)
676
677 finally:
678 job = tap.WORKER_SYSTEM.destroy(jobId)
679 self.assertTrue(b'xmlns="http://www.ivoa.net/xml/VOTable/' in result)
680
681 def testColumnNames(self):
682 table, meta = _getQueryResult(
683 'SELECT cos(delta) as frob, alpha as "AlPhA", delta, "delta",'
684 ' 20+30, 20+30 AS constant, rv as "AS"'
685 ' from %s'%self.tableName)
686 fields = meta.getFields()
687 self.assertEqual(fields[0].name, "frob")
688 self.assertEqual(fields[0].getDescription(), "A sample Dec --"
689 " *TAINTED*: the value was operated on in a way that unit and"
690 " ucd may be severely wrong")
691 self.assertEqual(fields[1].name, "AlPhA")
692 self.assertEqual(fields[2].name, "delta")
693 # the next line tests for a documented violation of the spec.
694 self.assertEqual(fields[3].name, "delta_")
695 self.assertTrue(isinstance(fields[4].name, str))
696 self.assertEqual(fields[5].name, "constant")
697 self.assertEqual(fields[6].name, "AS")
698
699 def testColumnTypes(self):
700 table, meta = _getQueryResult(
701 "SELECT rv, point('icrs', alpha, delta), PI() from %s"%self.tableName)
702 fields = meta.getFields()
703 self.assertEqual(fields[0].datatype, "double")
704 self.assertEqual(fields[1].datatype, "double")
705 self.assertEqual(fields[1].xtype, "point")
706 self.assertEqual(fields[2].datatype, "double")
707
708
709 class _RoundtrippedData(testhelpers.TestResource):
710 resources = [("conn", tresc.dbConnection)]
711
712 def make(self, deps):
713 conn = deps["conn"]
714 data = rsc.makeData(
715 base.resolveCrossId("data/test#import_for_roundtrip"),
716 connection=conn)
717 try:
718 return _getQueryResult("SELECT * FROM test.typestable")[0]
719 finally:
720 data.drop(data.dd, connection=conn)
721
722
723 class TAPRoundTripTest(testhelpers.VerboseTest):
724 resources = [("data", _RoundtrippedData())]
725
726 def testIntegers(self):
727 self.assertEqual(self.data[0][0], None)
728 self.assertEqual(self.data[1][0], 121)
729
730 def testReals(self):
731 self.assertEqual(self.data[0][1], None)
732 # todo: can we do better and keep this at an actual float32?
733 self.assertAlmostEqual(self.data[1][1], 121.12100219726562)
734 self.assertEqual(self.data[0][2], None)
735 self.assertAlmostEqual(self.data[1][2], 121.121)
736
737 def testText(self):
738 # VOTable doesn't know None from ''
739 self.assertEqual(self.data[0][3], "")
740 self.assertEqual(self.data[1][3], "hundertEinundzwanzig")
741
742 def testDate(self):
743 self.assertEqual(self.data[0][4], None)
744 self.assertEqual(self.data[1][4], datetime.datetime(1969, 12, 24, 0, 0))
745
746 def testJSON(self):
747 # for now, our VOTable parser doesn't know the json xtype; we
748 # way want to change this, in which case this test would need to
749 # change.
750 # Oh: and VOTable doesn't know None from ''; if we do treat the xtype
751 # one day, the "" in the next line ought to become a None.
752 self.assertEqual(self.data[0][5], "")
753 self.assertEqual(self.data[1][5], '{"testing": true}')
754
755
756 class _TAPResultTable(testhelpers.TestResource):
757 resources = [("ds", adqltest.adqlTestTable)]
758
759 def make(self, deps):
760 return testhelpers.getXMLTree(
761 _getUnparsedQueryResult(
762 "SELECT rv, PI(), alpha, delta from %s"%
763 deps["ds"].tables["adql"].tableDef.getQName()), debug=False)
764
765
766 class VOTableMetaTest(testhelpers.VerboseTest):
767 resources = [("tree", _TAPResultTable())]
768
769 def testTranslatedQueryPresent(self):
770 self.assertEqualIgnoringAliases(
771 self.tree.xpath("//INFO[@name='sql_query']")[0].get("value"),
772 "SELECT rv, PI() ASWHATEVER, alpha, delta FROM test.adql LIMIT 20000")
773
774 def testADQLPresent(self):
775 self.assertEqualIgnoringAliases(
776 self.tree.xpath("//INFO[@name='query']")[0].get("value"),
777 "SELECT rv, PI(), alpha, delta from test.adql")
778
779 def testParamCopied(self):
780 pNode = self.tree.xpath("//PARAM[@name='fib']")[0]
781 self.assertEqual(pNode.get("utype"), "math:series.fibonacci")
782 self.assertEqual(pNode.get("value"), "1 1 2")
783
784 def testSourcesUniqued(self):
785 self.assertEqual(len(self.tree.xpath("//INFO[@ucd='meta.bib.bibcode']")), 1)
786
787 def testCitationInfo(self):
788 info = self.tree.xpath("//INFO[@name='citation']")[0]
789 self.assertEqual(info.get("value"),
790 "http://localhost:8080/tableinfo/test.adql#ti-citing")
791 self.assertTrue("Advice " in info.text)
792
793 def testFullCoosys(self):
794 coosysEl = self.tree.xpath("//COOSYS")[0]
795 self.assertEqual(coosysEl.get("epoch"), "J2015.0")
796 self.assertEqual(coosysEl.get("system"), "ICRS")
797 self.assertEqual(coosysEl.get("ID"), "system")
798 self.assertEqual(
799 self.tree.xpath("//FIELD[@name='alpha']")[0].get("ref"),
800 "system")
801 self.assertEqual(
802 self.tree.xpath("//FIELD[@name='rV']")[0].get("ref"),
803 "system")
804
805
806 class _TAPJoinResultTable(testhelpers.TestResource):
807 resources = [("ds", adqltest.adqlTestTable),
808 ("ssa", tresc.ssaTestTable)]
809
810 def make(self, deps):
811 return testhelpers.getXMLTree(
812 _getUnparsedQueryResult(
813 "SELECT delta, ssa_pubdid"
814 " from test.adql join test.hcdtest on (alpha=ssa_length)"),
815 debug=False)
816
817 TAP_JOIN_RESULT_TABLE = _TAPJoinResultTable()
818
819
820 class JoinMetaTest(testhelpers.VerboseTest):
821 resources = [("tree", TAP_JOIN_RESULT_TABLE)]
822
823 def testDatalinkServiceMentioned(self):
824 svcDefinition = self.tree.xpath("//RESOURCE[@type='meta']")
825 idid = testhelpers.pickSingle(svcDefinition
826 ).xpath("GROUP/PARAM[@name='ID']")[0].get("ref")
827 self.assertEqual(
828 self.tree.xpath("//FIELD[@ID='%s']"%idid)[0].get("name"),
829 "ssa_pubDID")
830
831 def testDatalinkServiceSkippedWithoutColumn(self):
832 tree = testhelpers.getXMLTree(
833 _getUnparsedQueryResult(
834 "SELECT delta"
835 " from test.adql join test.hcdtest on (alpha=ssa_length)"),
836 debug=False)
837 self.assertEqual(len(tree.xpath("//RESOURCE[@type='meta']")), 0)
838
839 def testParamCopied(self):
840 pNode = self.tree.xpath("//PARAM[@name='fib']")[0]
841 self.assertEqual(pNode.get("utype"), "math:series.fibonacci")
842 self.assertEqual(pNode.get("value"), "1 1 2")
843
844 pNode = self.tree.xpath("//PARAM[@name='fab']")[0]
845 self.assertEqual(pNode.get("value"), "four")
846
847
848 class DataOriginTest(testhelpers.VerboseTest):
849 resources = [("tree", TAP_JOIN_RESULT_TABLE)]
850
851 def _getINFO(self, key):
852 matches = self.tree.xpath(f"//INFO[@name='{key}']")
853 assert len(matches)==1
854 return matches[0].get("value")
855
856 def _getINFOs(self, key):
857 return set(m.get("value")
858 for m in self.tree.xpath(f"//INFO[@name='{key}']"))
859
860 # Keep the sequence of tests in sync with the sequence of items in
861 # the data origin paper so it's easy to see whether we're covering
862 # them all.
863
864 def testAllIVOIDsPresent(self):
865 self.assertEqual(self._getINFOs("ivoid"), set([
866 'ivo://x-testing/data/ssatest/c',
867 'ivo://x-testing/data/ssatest/s',
868 "ivo://x-testing/data/ssatest/hcdtest"]))
869
870 self.assertEqual(self._getINFOs("ivoid_service"), set([
871 'ivo://x-testing/tap']))
872
873 def testPublisher(self):
874 self.assertEqual(
875 self._getINFO("publisher"),
876 "Your organisation's name")
877
878 def testServerSoftware(self):
879 self.assertEqual(self._getINFO("server_software"),
880 base.SERVER_SOFTWARE)
881
882 # We don't do request and request_post in TAP for now; the core
883 # doesn't have a request object, and the renderer sees pre-rendered
884 # data and can't put it in any more.
885
886 def testRequestDate(self):
887 self.assertTrue(self._getINFO("request_date").startswith("20"))
888
889 def testContact(self):
890 self.assertEqual(
891 self._getINFOs("contact"),
892 set(['[email protected]', '[email protected]']))
893
894 def testReferenceURL(self):
895 self.assertEqual(
896 self._getINFOs("reference_url"),
897 set([
898 'http://localhost:8080/tableinfo/test.adql',
899 'http://localhost:8080/tableinfo/test.hcdtest',
900 'http://localhost:8080/__system__/tap/run/info']))
901
902 def testAllSourcesPresent(self):
903 self.assertEqual(
904 self._getINFOs("publication_id"),
905 set(["1635QB41.G135......", "2015ivoa.spec.0617D"]))
906
907 def testResourceVersion(self):
908 self.assertEqual(
909 self._getINFOs("resource_version"),
910 set(["3.2.1-testing"]))
911
912 def testRights(self):
913 self.assertEqual(
914 self._getINFOs("rights"),
915 set(['Everything in here is pure fantasy (distributed under the GNU GPL)']))
916
917 def testRightsURI(self):
918 self.assertEqual(
919 self._getINFOs("rights_uri"),
920 set(["http://too-lazy-to/loop/up/spdx"]))
921
922 def testCreator(self):
923 self.assertEqual(
924 self._getINFOs("creator"),
925 set([
926 'John C. Testwriter',
927 'The Master Tester',
928 'Could be same as contact.name',
929 'Hendrix, J.; Page, J; et al.']))
930
931 # the rest is non-data origin so far
932
933 def testSQLQuery(self):
934 self.assertEqual(
935 self._getINFO("sql_query"),
936 "SELECT delta, ssa_pubdid FROM test.adql JOIN test.hcdtest ON ( alpha = ssa_length ) LIMIT 20000")
937
938 def testADQLQuery(self):
939 self.assertEqual(
940 self._getINFO("query"),
941 "SELECT delta, ssa_pubdid from test.adql join test.hcdtest on (alpha=ssa_length)")
942
943 def testAllCitationsPresent(self):
944 self.assertEqual(
945 self._getINFOs("citation"),
946 set(['http://localhost:8080/tableinfo/test.adql#ti-citing',
947 'http://localhost:8080/tableinfo/test.hcdtest#ti-citing',
948 'http://localhost:8080/__system__/tap/run/howtocite']))
949
950
951 class TAPTableMetaTest(testhelpers.VerboseTest):
952 resources = [("conn", tresc.dbConnection), ("ot", tresc.obscoreTable),
953 ("ssa", tresc.ssaTestTable)]
954
955 def testSingleSourceTableMetadataCopied(self):
956 res = adqlglue.runTAPQuery(
957 "SELECT TOP 1 * FROM ivoa.obscore", 1, self.conn, [], 1,
958 autoClose=False)
959 list(res) # exhaust the cursor
960 self.assertEqual(
961 base.getMetaText(res, "description"),
962 "The IVOA-defined obscore table, containing generic metadata for\n"
963 "datasets within this data centre.")
964
965 def testSingleSourceTableParamsCopied(self):
966 res = adqlglue.runTAPQuery(
967 "SELECT TOP 1 * FROM test.hcdtest", 1, self.conn, [], 1,
968 autoClose=False)
969 list(res) # exhaust the cursor
970 self.assertEqual(res.getParam("ssa_model"), "Spectrum-1.0")
971 self.assertEqual(res.getParam("ssa_specres"), 1e-10)
972
973 def testNoMetadataOnComplexQuery(self):
974 res = adqlglue.runTAPQuery(
975 "SELECT TOP 1 * FROM (SELECT * from ivoa.obscore) as q",
976 1, self.conn, [], 1, autoClose=False)
977 self.assertEqual(
978 base.getMetaText(res, "description"), None)
979 list(res)
980
981 def testNoMetadataOnJoin(self):
982 res = adqlglue.runTAPQuery(
983 "SELECT TOP 1 * FROM ivoa.obscore as a join ivoa.obscore as b"
984 " ON (a.obs_collection=b.dataproduct_subtype)",
985 1, self.conn, [], 1, autoClose=False)
986 self.assertEqual(
987 base.getMetaText(res, "description"), None)
988 list(res)
989
990 def testCasePreserved(self):
991 res = adqlglue.runTAPQuery(
992 "SELECT TOP 1 ssa_pubDID FROM %s"%self.ssa.tableDef.getQName(),
993 1, self.conn, [], 1, autoClose=False)
994 list(res)
995 self.assertEqual(res.tableDef.columns[0].name, "ssa_pubDID")
996
997
998 class JobMetaTest(testhelpers.VerboseTest):
999 def setUp(self):
1000 self.jobId = tap.WORKER_SYSTEM.getNewJobId()
1001
1002 def tearDown(self):
1003 tap.WORKER_SYSTEM.destroy(self.jobId)
1004
1005 def _postRedirectCheck(self, req, segments, method=b"POST"):
1006 req.method = method
1007 try:
1008 return uwsactions.doJobAction(tap.WORKER_SYSTEM, req,
1009 segments=(self.jobId,)+segments)
1010 except svcs.SeeOther:
1011 pass # that's the 303 expected
1012 else:
1013 self.fail("POSTing didn't redirect")
1014
1015 def testExecD(self):
1016 res = uwsactions.doJobAction(tap.WORKER_SYSTEM,
1017 TAPFakeRequest(),
1018 segments=(self.jobId, "executionduration"))
1019 self.assertEqual(res, "3600")
1020
1021 def testSetExecD(self):
1022 self._postRedirectCheck(
1023 TAPFakeRequest(args={"EXECUTIONDURATION": ["300"]}),
1024 ("executionduration",))
1025 res = uwsactions.doJobAction(tap.WORKER_SYSTEM,
1026 TAPFakeRequest(),
1027 segments=(self.jobId, "executionduration"))
1028 self.assertEqual(res, "300")
1029
1030 def testDestruction(self):
1031 self._postRedirectCheck(
1032 TAPFakeRequest(
1033 args={"DESTRuction": ["2000-10-10T10:12:13"]}),
1034 ("destruction",))
1035 res = uwsactions.doJobAction(tap.WORKER_SYSTEM,
1036 TAPFakeRequest(),
1037 segments=(self.jobId, "destruction"))
1038 self.assertEqual(res, "2000-10-10T10:12:13Z")
1039
1040 def testQuote(self):
1041 res = uwsactions.doJobAction(tap.WORKER_SYSTEM,
1042 TAPFakeRequest(),
1043 segments=(self.jobId, "quote"))
1044 # just make sure it's an iso date
1045 utils.parseISODT(res)
1046
1047 def testNullError(self):
1048 res = uwsactions.doJobAction(tap.WORKER_SYSTEM, TAPFakeRequest(),
1049 segments=(self.jobId, "error"))
1050 self.assertEqual(res, b"")
1051
1052 def testParametersPostAll(self):
1053 self._postRedirectCheck(
1054 TAPFakeRequest(args={"QUERY": ["Nicenice"]}),
1055 ("parameters",))
1056
1057 res = uwsactions.doJobAction(tap.WORKER_SYSTEM, TAPFakeRequest(),
1058 segments=(self.jobId, "parameters"))
1059 self.assertTrue(b"Nicenice" in res.render())
1060
1061 def testOwner(self):
1062 res = uwsactions.doJobAction(tap.WORKER_SYSTEM, TAPFakeRequest(),
1063 segments=(self.jobId, "owner"))
1064 self.assertEqual(res, b"")
1065
1066
1067 class TAPPublicationTest(testhelpers.VerboseTest):
1068 resources = [("table", tresc.tapPublishedADQLTable),
1069 ("conn", tresc.dbConnection)]
1070
1071 def testSchemaPublished(self):
1072 res = list(self.conn.queryToDicts(
1073 "select * from tap_schema.schemas where schema_name='test'"))[0]
1074 self.assertEqual(res["description"],
1075 "Sundry test tables and other fancy stuff")
1076 self.assertEqual(res["utype"],
1077 "http://www.g-vo.org/DaCHS")
1078 self.assertEqual(res["schema_index"], 100)
1079
1080 def testTablesPublished(self):
1081 res = list(self.conn.queryToDicts(
1082 "select * from tap_schema.tables where table_name='test.csdata'"))
1083 row = testhelpers.pickSingle(res)
1084 self.assertEqual(row["table_type"], "table")
1085 # I suppose we ought to create some way (properties?) to set table_index
1086 self.assertEqual(row["table_index"], None)
1087 self.assertEqual(row["nrows"], 10)
1088
1089 def testColumnsPublished(self):
1090 res = list(self.conn.query(
1091 "select column_name, unit, datatype, arraysize, description"
1092 " from tap_schema.columns where table_name='test.csdata'"))
1093 self.assertTrue(("alpha", "deg", "float", None, "A sample RA") in res)
1094 self.assertEqual(len(res), 5)
1095
1096 def testModelsSupportedPresent(self):
1097 res = list(self.conn.query(
1098 "select * from tap_schema.supportedmodels where sourcerd='data/test'"))
1099 self.assertEqual(len(res), 2)
1100 self.assertEqual(set(r[1] for r in res),
1101 set(['Fantasy-1.0', 'Fantasy-1.1']))
1102
1103 def testSTCGroupPresent(self):
1104 res = set(list(self.conn.query(
1105 "select * from tap_schema.groups")))
1106 self.assertTrue(
1107 ('test.adql', 'alpha', 'col:weird.reason',
1108 'weird_columns', 'col:weird.name', "data/test") in res)
1109 self.assertTrue(
1110 ('test.adql', 'rv', None, 'nice_columns', 'col:nice.name', "data/test")
1111 in res)
1112
1113
1114 class _RenderedTAPExample(testhelpers.TestResource):
1115 def make(self, ignored):
1116 from gavo.web import examplesrender
1117
1118 rd = base.parseFromString(rscdesc.RD,
1119 """<resource schema="test"><meta name="_example"
1120 title="Query against boolean columns">
1121 Some tables this
1122 service exposes to TAP -- e.g., :taptable:`amanda.nucand`.
1123 To query those, you cannot say ``WHERE boolCol`` but have to compare
1124 ``'True'`` or ``'False'`` as in
1125
1126 .. tapquery::
1127
1128 SELECT *
1129 FROM amanda.nucand
1130 WHERE atmonusubset='True' and foo&lt;20
1131
1132 (nothing else will work).</meta></resource>""")
1133 return testhelpers.getXMLTree(
1134 examplesrender.Example(
1135 rd.getMeta("_example"))._getTranslatedHTML(), debug=False)
1136
1137
1138 class TAPExampleTest(testhelpers.VerboseTest):
1139 resources = [("tree", _RenderedTAPExample())]
1140
1141 def testContainerDeclared(self):
1142 root = self.tree.xpath('/div[@typeof="example"]')[0]
1143 self.assertEqual(root.get("id"), "Queryagainstbooleancolumns")
1144 self.assertEqual(root.get("resource"), "#Queryagainstbooleancolumns")
1145
1146 def testTitleMarkedUp(self):
1147 title = self.tree.xpath("h2")[0]
1148 self.assertEqual(title.get("property"), "name")
1149 self.assertEqual(title.text, "Query against boolean columns")
1150
1151 def testPlainText(self):
1152 para = self.tree.xpath("p")[0]
1153 self.assertTrue(para.text.startswith("Some tables"))
1154
1155 def testTableLink(self):
1156 tableAnchor = self.tree.xpath("//*[@property='table']")[0]
1157 self.assertEqual(len(tableAnchor), 0) # no children
1158 self.assertEqual(tableAnchor.text, "amanda.nucand")
1159 tableLink = self.tree.xpath("//a")[0]
1160 self.assertEqual(tableLink.get("href"), "/tableinfo/amanda.nucand")
1161
1162 def testQueryPresent(self):
1163 queryEl = self.tree.xpath("//*[@property='query']")[0]
1164 self.assertEqual(queryEl.text.strip(),
1165 "SELECT *\n FROM amanda.nucand\nWHERE atmonusubset='True' and foo<20")
1166 self.assertEqual(queryEl.attrib["class"],
1167 'dachs-ex-tapquery literal-block')
1168
1169
1170 class _WeirdTypesTAPResult(testhelpers.TestResource):
1171 resources = [("table", tresc.weirdTypesTable)]
1172
1173 def make(self, ignored):
1174 data, metadata = _getQueryResult(
1175 "select textarr from test.weirdtypes")
1176 return list(metadata.iterDicts(data)), metadata
1177
1178
1179 class WeirdTypesTAPTest(testhelpers.VerboseTest):
1180 resources = [("res", _WeirdTypesTAPResult())]
1181
1182 def testStringArrayValue(self):
1183 self.assertEqual(self.res[0][0]['textarr'],
1184 ['ein ', 'walde ', 'viel zu la'])
1185
1186 def testStringArrayMeta(self):
1187 self.assertEqual(
1188 self.res[1].votTable.getChildDict()["FIELD"][0].arraysize,
1189 "10x*")
1190
1191
1192 class UserUploadCleanupTest(testhelpers.VerboseTest):
1193 def testCleanup(self):
1194 with base.getWritableAdminConn() as conn:
1195 with open(base.getConfig("inputsDir") / "data" / "vizier_votable.vot",
1196 "rb") as f:
1197 tap_uploads.uploadUserTable(
1198 conn, "glue", f, "testuser")
1199 f.seek(0)
1200 tap_uploads.uploadUserTable(
1201 conn, "flu", f, "testuser")
1202 conn.execute("UPDATE tap_user.tables SET expiry=CURRENT_TIMESTAMP"
1203 " WHERE user_name='testuser' AND table_name='flu'")
1204
1205 try:
1206 cleanup = base.resolveCrossId("//tap_user#expire")
1207 cleanup.runImmediate()
1208 with base.getTableConn() as conn:
1209 still_there = [r[0] for r in
1210 conn.query("select table_name from tap_user.tables"
1211 " where user_name='testuser'")]
1212 self.assertEqual(still_there, ["glue"])
1213
1214 q = base.UnmanagedQuerier(conn)
1215 self.assertEqual(
1216 q.getTableType("tap_user._testuser_glue"), "BASE TABLE")
1217 self.assertEqual(q.getTableType("tap_user._testuser_flu"), None)
1218 finally:
1219 with base.getWritableAdminConn() as conn:
1220 conn.execute("DROP TABLE IF EXISTS tap_user._testuser_glue")
1221 conn.execute("DROP TABLE IF EXISTS tap_user._testuser_flu")
1222 conn.execute("DELETE FROM tap_user.tables WHERE user_name='testuser'")
1223
1224
1225 class _UploadedTables(testhelpers.TestResource):
1226 resources = [("conn", tresc.dbConnection)]
1227
1228 def make(self, deps):
1229 conn = deps["conn"]
1230 with open(base.getConfig("inputsDir") / "data" / "vizier_votable.vot",
1231 "rb") as f:
1232 tap_uploads.uploadUserTable(
1233 conn, "glue", f, "anonymous")
1234 conn.commit()
1235 return conn
1236
1237 def clean(self, conn):
1238 createdTables = ['_anonymous_glue']
1239 conn.execute("DELETE FROM tap_user.tables WHERE"
1240 " physical_name in ({})".format(",".join(repr(t) for t in createdTables)))
1241 for t in createdTables:
1242 conn.execute(f"DROP TABLE tap_user.{t}")
1243 conn.commit()
1244
1245
1246 class _TestWithIndexCreation:
1247 def _assertIndexCreation(self,
1248 postArgs,
1249 tableName,
1250 indexFragment,
1251 indexName,
1252 userName="anonymous"):
1253 req = trialhelpers.FakeRequest("", args=postArgs)
1254 try:
1255 res = tap_uploads.PersistentUploadRenderer(req, TAP_SERVICE
1256 ).getChild(tableName.encode("ascii"), req
1257 ).getChild(b"index", req).render_POST(req)
1258 except svcs.SeeOther as ex:
1259 redirection = ex
1260 else:
1261 self.fail("No redirection raised out of the persistent upload indexer"
1262 f" (got {res} instead)")
1263
1264 with base.getTableConn() as conn:
1265 metadata, physicalName = list(conn.query("select metadata, physical_name"
1266 " from tap_user.tables"
1267 " where table_name=%(tableName)s and user_name=%(userName)s",
1268 locals()))[0]
1269 self.assertTrue(indexFragment in metadata)
1270
1271 # now wait until the index is created and see if it's actually there.
1272 workers = tap_uploads.getIndexerUWS()
1273 job = workers.getJob(redirection.rawDest.split("/")[-1])
1274 for retry in range(100):
1275 job.update()
1276 if job.phase==uws.COMPLETED:
1277 break
1278 time.sleep(0.05)
1279 else:
1280 self.fail("Indexer job did not complete within 5 seconds")
1281 workers.destroy(job.jobId)
1282
1283 self.assertTrue(
1284 base.UnmanagedQuerier(conn).hasIndex(physicalName, indexName),
1285 f"user upload index {indexFragment} has not showed up")
1286
1287
1288 class UserUploadCustomIndexTest(testhelpers.VerboseTest,
1289 metaclass=testhelpers.SamplesBasedAutoTest):
1290 def _runTest(self, sample):
1291 cols = [base.parseFromString(rscdef.Column, lit)
1292 for lit in sample[0]]
1293 index = base.makeStruct(rscdef.DBIndex,
1294 columns=[c.name for c in cols],
1295 **tap_uploads._customizeIndex(cols))
1296 indexLiteral = base.structToXML(index)
1297 self.assertEqual(indexLiteral, sample[1])
1298
1299 samples = [
1300 (['<column name="foo"/>'], '<index columns="foo" name="foo">foo</index>'),
1301 (['<column name="dec" ucd="pos.eq.dec"/>',
1302 '<column name="bar" ucd="pos.eq.dec"/>'],
1303 '<index columns="dec, bar" name="dec_bar">dec,bar</index>'),
1304 # The following depends on the config item [db]splitSpatialIndex
1305 (['<column name="dec" ucd="pos.eq.ra;meta.main" unit="deg"/>',
1306 '<column name="bar" ucd="pos.eq.dec" unit="deg"/>'],
1307 '<index cluster="True" columns="dec, bar" kind="spoint" method="GIST"'
1308 ' name="dec_bar">spoint(radians(dec),radians(bar))</index>'),
1309 (['<column name="pos" type="spoint"/>'],
1310 '<index cluster="True" columns="pos" kind="spoint"'
1311 ' method="GIST" name="pos">pos</index>'),
1312 (['<column name="dec" ucd="pos.eq.ra;meta.main" unit="deg"/>',
1313 '<column name="bar" ucd="pos.galactic.long" unit="deg"/>'],
1314 '<index columns="dec, bar" name="dec_bar">dec,bar</index>'),
1315 (['<column name="foo"/>', '<column name="quoted/messy stuff"/>'],
1316 '<index columns="foo, quoted/messy stuff" name="foo__messy_stuff_">foo,"messy stuff"</index>'),
1317 ]
1318
1319
1320 class UserUploadAnonTest(testhelpers.VerboseTest, _TestWithIndexCreation):
1321 resources = [("uploaded", _UploadedTables()),
1322 ("conn", tresc.dbConnection)]
1323
1324 def testInfoGetterSuccess(self):
1325 getter = adqlglue.DaCHSFieldInfoGetter(forUser="anonymous")
1326 infos = getter.getInfosFor("tap_user.glue")
1327 col = infos[1]
1328 self.assertEqual(col[0].name, "_RAJ2000")
1329 self.assertEqual(col[1].ucd, "pos.eq.ra;meta.main")
1330
1331 def testInfoGetterWrongUser(self):
1332 getter = adqlglue.DaCHSFieldInfoGetter(forUser="testing")
1333 self.assertRaisesWithMsg(utils.NotFoundError,
1334 "table 'tap_user.glue' could not be located in your uploaded tables",
1335 getter.getInfosFor,
1336 ("tap_user.glue",))
1337
1338 def testADQLMorphing(self):
1339 res = list(
1340 adqlglue.runTAPQuery("WITH a AS"
1341 " (SELECT * from tap_user.glue where mag<1)"
1342 " SELECT b.tyc2 from tap_user.glue as b join a using (iras)",
1343 2, self.conn, [], 20, False))
1344 self.assertEqual(res, [{'TYC2': '1266-01416-1'}])
1345
1346 def testIndexBadColumn(self):
1347 req = trialhelpers.FakeRequest("", args={"INDEX": ["notexisting"]})
1348 self.assertRaisesWithMsg(svcs.BadRequest,
1349 "No such column: notexisting",
1350 tap_uploads.PersistentUploadRenderer(req, TAP_SERVICE
1351 ).getChild(b"glue", req).getChild(b"index", req).render_POST,
1352 (req,))
1353
1354 def testIndexSingleColumn(self):
1355 self._assertIndexCreation(
1356 {"INDEX": ["IRAS"]},
1357 "glue",
1358 '<index columns="IRAS" name="IRAS">IRAS</index>',
1359 "_anonymous_glue_IRAS")
1360
1361 def testIndexTwoColumns(self):
1362 self._assertIndexCreation(
1363 {"INDEX": ["pmRA", "pmDE"]},
1364 "glue",
1365 '<index columns="pmRA, pmDE" name="pmRA_pmDE">pmRA,pmDE</index>',
1366 "_anonymous_glue_pmRA_pmDE")
1367
1368 def testIndexSpatialColumns(self):
1369 self._assertIndexCreation(
1370 {"INDEX": ["_RAJ2000", "_DEJ2000"]},
1371 "glue",
1372 '<index cluster="True" columns="_RAJ2000, _DEJ2000" kind="spoint" method="GIST" name="_RAJ2000__DEJ2000">spoint(radians("_RAJ2000"),radians("_DEJ2000"))</index>',
1373 "_anonymous_glue__RAJ2000__DEJ2000")
1374
1375 req = trialhelpers.FakeRequest("")
1376 res = tap_uploads.PersistentUploadRenderer(req, TAP_SERVICE
1377 ).getChild(b"glue", req
1378 ).getChild(b"index", req).render_GET(req).decode("utf-8")
1379
1380 self.assertTrue("Indexes on table tap_user.glue\n\n" in res)
1381 self.assertTrue('CREATE INDEX glue__RAJ2000__DEJ2000 ON tap_user.glue USING GIST (spoint(radians("_RAJ2000"),radians("_DEJ2000")))\n' in res)
1382 self.assertTrue("CLUSTER glue__RAJ2000__DEJ2000 ON tap_user.glue\n" in res)
1383
1384
1385 class _UploadedTablesUsers(testhelpers.TestResource):
1386 resources = [("conn", tresc.dbConnection)]
1387
1388 def make(self, deps):
1389 conn = deps["conn"]
1390 with open(base.getConfig("inputsDir") / "data" / "vizier_votable.vot",
1391 "rb") as f:
1392 tap_uploads.uploadUserTable(
1393 conn, "glue", f, "anonymous")
1394
1395 with open(base.getConfig("inputsDir") / "data" / "vizier_votable.vot",
1396 "rb") as f:
1397 tap_uploads.uploadUserTable(
1398 conn, "honk", f, "testing")
1399
1400 with open(base.getConfig("inputsDir") / "data" / "vizier_votable.vot",
1401 "rb") as f:
1402 tap_uploads.uploadUserTable(
1403 conn, "glue", f, "george")
1404
1405 with open(base.getConfig("inputsDir") / "data" / "vizier_votable.vot",
1406 "rb") as f:
1407 tap_uploads.uploadUserTable(
1408 conn, "flu", f, "testing")
1409
1410 return conn
1411
1412 def clean(self, conn):
1413 createdTables = [
1414 '_anonymous_glue', "_testing_honk", "_george_glue", "_testing_flu"]
1415 conn.execute("DELETE FROM tap_user.tables WHERE"
1416 " physical_name in ({})".format(",".join(repr(t) for t in createdTables)))
1417 for t in createdTables:
1418 conn.execute(f"DROP TABLE tap_user.{t}")
1419
1420 _uploadedTablesUsers = _UploadedTablesUsers()
1421
1422
1423 class UploadedSerialisationTest(testhelpers.VerboseTest):
1424 resources = [("tables", _uploadedTablesUsers)]
1425
1426 def testDeserialisation(self):
1427 td, physName = tap_uploads.getUploadedTableDef("george", "glue")
1428 self.assertEqual(td.id, "glue")
1429 self.assertEqual(physName, "tap_user._george_glue")
1430 self.assertEqual(len(td.columns), 11)
1431
1432
1433 TAP_SERVICE = base.resolveCrossId("//tap#run")
1434
1435 class TableListingTest(testhelpers.VerboseTest):
1436 resources = [("tables", _uploadedTablesUsers)]
1437
1438 def getForUser(self, username="testting", password="testing"):
1439 req = trialhelpers.FakeRequest("")
1440 req.user, req.password = username, password
1441 tap_uploads.PersistentUploadRenderer(req, TAP_SERVICE
1442 ).render(req)
1443 return testhelpers.getXMLTree(req.accumulator, debug=False)
1444
1445 def testTablesListingAnonymous(self):
1446 self.assertEqual(
1447 self.getForUser("").xpath("//INFO[@name='QUERY_STATUS']")[0].text,
1448 "No persistent tables listing for anonymous users.")
1449
1450 def testTablesListingAuthUser(self):
1451 tree = self.getForUser("testing")
1452 self.assertEqual(tree.xpath("schema/name")[0].text, "tap_user")
1453 tables = tree.xpath("schema/table")
1454 # this asserts there's no tables from george or from anonymous
1455 self.assertEqual(len(tables), 2)
1456
1457 table_names = {t.xpath("name")[0].text for t in tables}
1458 self.assertEqual(table_names, {"tap_user.honk", "tap_user.flu"})
1459
1460 ucds = set(n.text for n in tree.xpath("//ucd"))
1461 self.assertEqual(ucds, {'pos.eq.ra;meta.main', 'meta.id;meta.main',
1462 'pos.eq.dec;meta.main', 'pos.angDistance', 'phot.color',
1463 'pos.pm;pos.eq.ra', 'pos.eq.dec', 'meta.id;src', 'pos.eq.ra',
1464 'phot.mag;em.opt.V', 'pos.pm;pos.eq.dec'})
1465
1466
1467 if __name__=="__main__":
1468 testhelpers.main(JobMetaTest)