Debian Codegraph @

tests/uitest.py

raw
1 """
2 Tests for event propagation and user interaction.
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 datetime
12 import os
13 import re
14 import shutil
15 import subprocess
16
17 from gavo.helpers import testhelpers
18
19 from gavo import base
20 from gavo import api
21 from gavo import rsc
22 from gavo import rscdesc
23 from gavo import utils
24 from gavo.helpers import testtricks
25 from gavo.user import cli
26
27 import tresc
28
29
30 def extractoutput(owd):
31 # an extractor function for utils.sandbox that preserves the outputs
32 # of tests run in sandboxes
33 for name in ["output.stderr", "output.stdout"]:
34 dest = os.path.join(owd, name)
35 if os.path.exists(dest):
36 os.unlink(dest)
37 if os.path.exists(name):
38 shutil.move(name, dest)
39
40
41 class MiscCLITest(testhelpers.VerboseTest):
42 resources = [("conn", tresc.dbConnection)]
43
44 def testUnhandledException(self):
45 self.assertOutput(cli.main, argList=["raise"],
46 expectedStderr=lambda msg: b"Unhandled exception" in msg,
47 expectedRetcode=1)
48
49 def testTopLevelHelp(self):
50 self.assertOutput(cli.main, argList=["--help"],
51 expectedStdout=["<func> is a unique"])
52
53 def testNonUniqueMatch(self):
54 self.assertOutput(cli.main, argList=["a"],
55 expectedRetcode=1,
56 expectedStderr=
57 lambda msg: msg.startswith(b"Multiple matches for function a"))
58
59 def testNoMatch(self):
60 self.assertOutput(cli.main, argList=["xyloph"],
61 expectedRetcode=1,
62 expectedStderr=
63 lambda msg: msg.startswith(b"No match for function xyloph"))
64
65 def testSubCmdHelp(self):
66 self.assertOutput(cli.main, argList=["publish", "--help"],
67 expectedStdout=lambda msg:
68 b"usage: dachs publish [-h] [-k] [-u] rd [rd ...]" in msg)
69
70 def testAProg(self):
71 self.assertOutput(cli.main, argList=["stc", "utypes", "Position ICRS"],
72 expectedStdout=["AstroCoordSystem.SpaceFrame.CoordRefFrame"])
73
74 def testCleanTAP(self):
75 self.conn.commit()
76 self.assertOutput(cli.main, argList=["admin", "cleantap"],
77 expectedRetcode=0)
78
79 def testExecute(self):
80 self.assertOutput(cli.main, argList=["admin", "exec",
81 "data/regtest#silly"],
82 expectedStdout="Silly\n",
83 expectedStderr="Spawning thread for cron job Do silly things\n")
84
85 def testCleanTAPPending(self):
86 self.conn.commit()
87 self.assertOutput(cli.main, argList=["admin", "cleantap", "-p"],
88 expectedRetcode=0, expectedStderr="")
89
90 def testDumpDFSuccess(self):
91 self.assertOutput(cli.main, argList=["adm", "dumpDF", "data/filters.txt"],
92 expectedRetcode=0,
93 expectedStdout=["# Bandpass names are typically common"])
94
95 def testDumpDFNotFound(self):
96 self.assertOutput(cli.main, argList=["adm", "dumpDF", "missing.dat"],
97 expectedRetcode=1,
98 expectedStderr="*** Error: No such distribution file: missing.dat\n\n")
99
100 def testDumpDFRD(self):
101 self.assertOutput(cli.main, argList=["adm", "dumpDF", "//scs"],
102 expectedRetcode=0,
103 expectedStdout=['<outputField id="distCol"'])
104
105 def testXSDValInvalid(self):
106 with testhelpers.testFile("bad.xml", "<ramsch/>") as p:
107 self.assertOutput(cli.main, argList=["adm", "xsd", p],
108 expectedRetcode=1,
109 expectedStdout=lambda txt: re.match(b".*/tmp/bad.xml --"
110 b' <string>:1:0:ERROR:SCHEMASV:SCHEMAV_CVC_ELT_1:'
111 b" Element 'ramsch': No matching global declaration available"
112 b' for the validation root.\n$', txt))
113
114 def testXSDValValid(self):
115 with testhelpers.testFile("bad.xml", '<VOTABLE'
116 ' xmlns="http://www.ivoa.net/xml/VOTable/v1.3"><RESOURCE/>'
117 '</VOTABLE>') as p:
118 self.assertOutput(cli.main, argList=["adm", "xsd", p],
119 expectedRetcode=0,
120 expectedStdout=lambda txt:
121 re.match(b'.*/tmp/bad.xml -- valid\n$', txt))
122
123 def testShowDDGood(self):
124 self.assertOutput(cli.main, argList=["show", "dds", "//tap"],
125 expectedStdout="importTablesFromRD\nimportDMsFromRD\nimportColumnsFromRD\nimportGroupsFromRD\nimportFkeysFromRD\ncreateSchema*\nrefresh\ncreateJobTable*\n")
126
127 def testShowDDBad(self):
128 self.assertOutput(cli.main, argList=["show", "dds", "//nonex"],
129 expectedRetcode=1,
130 expectedStderr=lambda msg:
131 b"Resource descriptor '__system__/nonex' could not be located" in msg)
132
133 def testVersion(self):
134 self.assertOutput(cli.main, argList=["--version"],
135 expectedRetcode=0,
136 expectedStdout=lambda msg: re.match(
137 rb"Software \(\d+\.\d+(\.\d+)?\)"
138 rb" Schema \(\d+/-?\d+\)" b"\n", msg))
139
140 def testDachsInitJustRuns(self):
141 from gavo.user import initdachs
142
143 self.assertOutput(initdachs.main, argList=["--nodb"],
144 expectedRetcode=0,
145 expectedStdout="",
146 expectedStderr="")
147
148 def testMkboost(self):
149 self.assertOutput(cli.main, argList=["mkboost", "data/dgs#col"],
150 expectedStdout=["#include <stdio.h>",
151 "fi_l, /* L, smallint */",
152 "void createDumpfile(int argc, char **argv)"])
153
154 def testADQL(self):
155 self.assertOutput(cli.main, argList=["adql", "select top 1 * from"
156 " tap_schema.tables"],
157 expectedStdout=[
158 '<DESCRIPTION>Tables available for ADQL querying.</DESCRIPTION>',
159 '<STREAM encoding="base64">'],
160 expectedStderr=["Sending to postgres:", "LIMIT 1"])
161
162 def testIndexStatements(self):
163 self.assertOutput(cli.main, argList=["adm", "indexS",
164 "//products#products"],
165 expectedStdout="CREATE INDEX products_sourceTable ON"
166 " dc.products (sourceTable)\n")
167
168 def testUpdateTAPSchema(self):
169 self.assertOutput(cli.main, argList=["adm", "updateTAP"],
170 expectedStdout="",
171 expectedStderr=lambda output: "Starting refresh\nDone refresh, read 0\n")
172
173
174 class _CatalogTestResource(tresc.FileResource):
175 path = "inputs/somecat/q.rd"
176 content = """<resource schema="somecat">
177 <meta name="creationDate">2000-01-01T00:00:00</meta>
178 <meta name="title">A test resource</meta>
179 <meta name="description">(for DaCHS)</meta>
180 <meta name="subject">Objectivity</meta>
181 <table onDisk="True" id="cat">
182 <column name="ra" ucd="pos.eq.ra;meta.main"/>
183 <column name="dec" ucd="pos.eq.dec;meta.main"/>
184 <column name="t_min" type="timestamp"/>
185 <column name="t_max" type="timestamp"/>
186 <publish/>
187 </table>
188 <coverage>
189 <updater sourceTable="cat"/>
190 </coverage>
191 <data id="import">
192 <sources><item>1</item><item>4</item><item>x</item></sources>
193 <embeddedGrammar>
194 <iterator><code>
195 seed = float(self.sourceToken)
196 yield {
197 "ra": seed+4,
198 "dec": 2-seed,
199 "t_min": datetime.datetime(int(2010+seed), int(seed)%12, 1, 6),
200 "t_max": datetime.datetime(int(2010+seed), int(seed)%12, 1, 12),
201 }
202 </code></iterator>
203 </embeddedGrammar>
204 <make table="cat"/>
205 </data>
206 </resource>"""
207
208
209 class ImportTest(testhelpers.VerboseTest):
210 resources = [("conn", tresc.dbConnection),
211 ("res", _CatalogTestResource()),
212 ("obscorePublished", tresc.ssaTestTable),
213 ("afits", tresc.fitsTable)]
214
215 def testLifecycle(self):
216 self.conn.commit()
217 with base.AdhocQuerier() as querier:
218 self.assertOutput(cli.main,
219 argList=["--suppress-log",
220 "imp", "-c", "somecat/q"],
221 expectedStderr=["Rows affected: 2"],
222 expectedRetcode=101)
223
224 self.assertFalse(querier.getTableType("somecat.cat") is None)
225 self.assertFalse(querier.getTableType("test.typesTable") is not None)
226
227 self.assertOutput(cli.main,
228 argList=["--disable-spew", "--suppress-log", "publish", "somecat/q"],
229 expectedRetcode=0, expectedStdout="")
230
231 self.assertTrue(list(querier.connection.query("SELECT * FROM dc.subjects"
232 " WHERE subject=%(s)s", {'s': "Objectivity"})))
233
234 self.assertOutput(cli.main,
235 argList=["--disable-spew", "--suppress-log", "limits", "somecat/q"],
236 expectedRetcode=0,
237 expectedStderr=lambda o: o.startswith(
238 b"Obtaining metadata for rd somecat"))
239
240 self.assertOutput(cli.main,
241 argList=["limits", "-d", "somecat/q"],
242 expectedStdout=lambda output: testtricks.assertHasStrings(output, [
243 "spatial converage 6/18064 18098",
244 "temporal converage [55562.25, 56748.5]",
245 "spectral converage <Unknown>",
246 "Statistics for somecat.cat",
247 "0.9", "…"]) or True)
248
249 base.caches.clearForName("somecat/q")
250 changedRd = base.caches.getRD("somecat/q")
251 self.assertEqual(changedRd.coverage.spatial, "6/18064 18098")
252 self.assertEqual(changedRd.coverage.spectral, [])
253 self.assertEqual(changedRd.coverage.temporal, [(55562.25, 56748.5)])
254
255 # drop it all, make sure all traces are gone
256 self.assertOutput(cli.main,
257 argList=["--ui", "semistingy", "--suppress-log",
258 "drop", "somecat/q"], expectedStdout="", expectedStderr="")
259 self.assertFalse(list(querier.connection.query("SELECT * FROM dc.subjects"
260 " WHERE subject=%(s)s", {'s': "Objectivity"})))
261 self.assertTrue(querier.getTableType("comecat.cat") is None)
262
263 def testImportDeniedForOffInputs(self):
264 destName = os.path.expanduser("~/foobar.rd")
265 with testhelpers.testFile(destName, '<resource schema="junk"/>'):
266 self.assertOutput(cli.main,
267 argList=["imp", destName],
268 expectedRetcode=1, expectedStderr=lambda tx:
269 re.match(rb"\*\*\* Error: .*/foobar.rd: Only RDs below inputsDir"
270 b"\n.*/inputs. are allowed.\n", tx) is not None)
271
272 def testMetaImportAndPurge(self):
273 self.assertOutput(cli.main, argList=["purge", "test.adql"])
274 # make sure the test schema exists before running the test
275 self.conn.commit()
276 self.assertOutput(cli.main,
277 argList=["imp", "data/test", "productimport-skip"],
278 expectedStderr=["Making data data/test#pro"])
279 try:
280 with base.getWritableAdminConn() as conn:
281 conn.execute("CREATE TABLE test.adql (erratic INTEGER)")
282 conn.execute("INSERT INTO test.adql VALUES (1)")
283
284 with base.getTableConn() as conn:
285 self.assertOutput(cli.main, argList=
286 ["imp", "-m", "data/test", "ADQLTest"],
287 expectedStderr=[
288 "Updating meta for ADQLTest\n"])
289 self.assertEqual(list(conn.query(
290 "select tablename, sourcerd, adql"
291 " from dc.tablemeta where tablename='test.adql'")),
292 [('test.adql', 'data/test', True)])
293
294 # make sure gavo imp didn't touch the table
295 self.assertEqual(list(conn.query("SELECT * FROM test.adql")),
296 [(1,)])
297 finally:
298 self.assertOutput(cli.main, argList=["purge", "test.adql"])
299
300 def testNonExistingDataImpError(self):
301 with testtricks.testFile(
302 os.path.join(base.getConfig("inputsDir"), "empty.rd"),
303 """<resource schema="test"><table id="foo"/></resource>"""):
304 self.assertOutput(cli.main, argList=["--hints", "imp", "empty", "foo"],
305 expectedRetcode=1, expectedStderr="*** Error: The DD 'foo'"
306 " you are trying to import is not defined within\nthe RD"
307 " 'empty'.\nHint: Data elements available in empty include (None)\n")
308
309 def testNoAutoDataImpError(self):
310 with testtricks.testFile(
311 os.path.join(base.getConfig("inputsDir"), "empty.rd"),
312 """<resource schema="test"><table id="foo"/>
313 <data auto="False" id="x"><make table="foo"/></data>
314 <data auto="False" id="y"><make table="foo"/></data>
315 </resource>"""):
316 self.assertOutput(cli.main, argList=["--hints", "imp", "empty"],
317 expectedRetcode=1, expectedStderr='*** Error: Neither automatic'
318 ' not manual data selected from RD empty\nHint: All data'
319 ' elements have auto=False. You have to explicitly name\none'
320 ' or more data to import (names available: x, y)\n')
321
322 def testMetaNotPropagatedMessage(self):
323 self.assertOutput(cli.main,
324 argList=["imp", "-m", "data/test", "recaftertest"],
325 expectedRetcode=0,
326 expectedStderr=["not rebuilding dependencies.",
327 ": data/test#import_pythonscript"])
328
329 def testPubUnpub(self):
330 self.assertOutput(cli.main,
331 argList=["--disable-spew", "--suppress-log", "publish", "somecat/q"],
332 expectedRetcode=0, expectedStdout="")
333 self.assertEqual(
334 list(self.conn.query("SELECT resid, deleted FROM dc.resources"
335 " WHERE sourcerd='somecat/q'")),
336 [('cat', False)])
337 self.assertOutput(cli.main,
338 argList=["--disable-spew", "--suppress-log", "publish", "-u",
339 "somecat/q"], expectedRetcode=0, expectedStdout="")
340 self.assertEqual(
341 list(self.conn.query("SELECT resid, deleted FROM dc.resources"
342 " WHERE sourcerd='somecat/q'")),
343 [('cat', True)])
344
345 def testCacheprev(self):
346 # we only see if this thing crashes; actually deleting and creating
347 # previews is too much hassle at this point.
348 self.assertOutput(cli.main,
349 argList=["adm", "cacheprev", "data/test#prodtest"],
350 expectedStdout="")
351
352 def testObscoreSurvivesReindex(self):
353 with base.getTableConn() as conn:
354 res = list(conn.query("SELECT obs_id FROM ivoa.obscore WHERE"
355 " source_table='test.hcdtest' and obs_id='data/spec1.ssatest'"))
356 self.assertEqual(len(res), 1)
357
358 self.assertOutput(cli.main,
359 argList=["--disable-spew", "--suppress-log", "import", "-I",
360 "data/ssatest", "test_import"],
361 expectedRetcode=0,
362 expectedStderr=lambda t: b"Create index hcdtest_ssa_pubDID" in t)
363
364 with base.getTableConn() as conn:
365 res = list(conn.query("SELECT obs_id FROM ivoa.obscore WHERE"
366 " source_table='test.hcdtest' and obs_id='data/spec1.ssatest'"))
367 self.assertEqual(len(res), 1)
368
369 def testObscoreLimits(self):
370 self.assertOutput(cli.main,
371 argList=["limits", "//obscore"],
372 expectedRetcode=0,
373 expectedStderr=lambda res:
374 b"Obtaining metadata for rd __system__/obs" in res)
375
376 def testDDReferencing(self):
377 self.assertOutput(cli.main,
378 argList=["imp", "-m", "data/test#recaftertest"],
379 expectedRetcode=0,
380 expectedStderr=["not rebuilding dependencies.",
381 ": data/test#import_pythonscript"])
382
383 def testDDReferencingExtraArgs(self):
384 self.assertOutput(cli.main,
385 argList=["imp", "-m", "data/test#recaftertest", "illegal", "args"],
386 expectedRetcode=1,
387 expectedStderr="*** Error: You cannot give additional identifiers when you import a\nsingle DD\n")
388
389
390 class _SysRDResource(tresc.FileResource):
391 path = "inputs/sysrd.rd"
392 content = """<resource schema="test">
393 <table onDisk="True" id="fromclitest" system="True">
394 <column name="x" type="integer"><values nullLiteral="0"/></column>
395 </table>
396 <data id="y"><make table="fromclitest"/></data>
397 </resource>"""
398
399
400 class SystemImportTest(testhelpers.VerboseTest):
401 resources = [("conn", tresc.dbConnection),
402 ("sysrdFile", _SysRDResource())]
403
404 def _fillTable(self):
405 rd = api.getRD("sysrd")
406 t = rsc.TableForDef(rd.getById("fromclitest"), connection=self.conn)
407 t.addRow({'x': 2})
408 self.conn.commit()
409
410 def testNoSystemImportDefault(self):
411 self.assertOutput(cli.main, argList=["imp", "--system", "sysrd"],
412 expectedRetcode=0,
413 expectedStderr=["Making data sysrd#y", "Rows affected: 0"])
414 # Write a 2 into the table that must survive the next imp
415 self._fillTable()
416
417 self.assertOutput(cli.main, argList=["imp", "sysrd"],
418 expectedRetcode=0,
419 expectedStderr=["Making data sysrd#y", "Rows affected: 0"])
420 self.assertEqual(
421 list(self.conn.query("select * from test.fromclitest")),
422 [(2,)])
423
424 def testSystemImport(self):
425 self.assertOutput(cli.main, argList=["imp", "--system", "sysrd"],
426 expectedRetcode=0, expectedStderr=["Making data sysrd#y"])
427 # Write a 2 into the table that must survive the next imp
428 self._fillTable()
429
430 self.assertOutput(cli.main, argList=["imp", "--system", "sysrd"],
431 expectedRetcode=0, expectedStderr=["Making data sysrd#y"])
432 self.assertEqual(
433 list(self.conn.query("select * from test.fromclitest")),
434 [])
435
436 def testSystemDropDrops(self):
437 self.assertOutput(cli.main, argList=[
438 "--ui", "stingy", "drop", "--system", "sysrd"],
439 expectedRetcode=0, expectedStderr="", expectedStdout="")
440 with base.AdhocQuerier() as q:
441 self.assertTrue(q.getTableType("test.fromclitest") is None)
442
443
444 class _FITSGeneratedRD(testhelpers.TestResource):
445 def make(self, ignored):
446 p = testhelpers.ForkingSubprocess(
447 ["test harness", "--debug", "--ui", "stingy", "mkrd", "-r",
448 str(os.path.join(base.getConfig("inputsDir"), "data")),
449 "test_data/ex.fits"],
450 executable=cli.main, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
451 stdin=subprocess.PIPE)
452 out, err = p.communicate(input=b"")
453 retcode = p.wait()
454
455 if retcode:
456 raise AssertionError("panic: generating RD failed, bailing out.\n%s\n"%
457 err)
458 return out
459
460
461 class MkRDTest(testhelpers.VerboseTest, testhelpers.XSDTestMixin):
462 resources = [("fitsrd", _FITSGeneratedRD()), ('oc', tresc.obscoreTable)]
463
464 def testFITSRDLooksOk(self):
465 for frag in [
466 '<column name="color" type="text"',
467 'description="Effective exposure time [seconds]"',
468 '<map key="exptime">EXPTIME</map>']:
469 self.assertTrue(utils.bytify(frag) in self.fitsrd, "%s missing"%frag)
470
471 def testRunImp(self):
472 with testhelpers.testFile(
473 os.path.join(base.getConfig("inputsDir"), "gen.rd"),
474 self.fitsrd.original):
475 self.assertOutput(cli.main, ["imp", "gen"],
476 expectedStderr=["Rows affected: 2"], expectedRetcode=0)
477 self.assertOutput(cli.main, ["--ui", "stingy", "drop", "gen"])
478
479 def testFITSRDMetaFirst(self):
480 self.assertTrue(self.fitsrd.split(b"\n")[1].strip().startswith(b"<meta"))
481
482 def testStartList(self):
483 self.assertOutput(cli.main, ["start", "list"],
484 expectedStdout=["scs -- Catalogs via SCS and TAP"])
485
486 def testStartBadCall(self):
487 self.assertOutput(cli.main, ["start", "knakurtt"],
488 expectedRetcode=1,
489 expectedStderr="*X*X* No template for knakurtt.\n")
490
491 def testStartSCS(self):
492 def makeAsserter(resdir):
493 def assertThings(output):
494 self.assertEqual(output, b"")
495 with open("q.rd") as f:
496 generated = f.read()
497
498 self.assertWellformed(generated)
499
500 self.assertTrue(
501 'schema="%s"'%resdir in generated)
502 self.assertTrue(
503 "%s-"%datetime.datetime.utcnow().year
504 in generated)
505 self.assertTrue(
506 '<meta name="creator">%authors' in generated)
507
508 return True
509 return assertThings
510
511 with utils.sandbox(
512 tmpdir=base.getConfig("inputsDir"),
513 extractfunc=extractoutput):
514 resdir = os.path.split(os.getcwd())[-1]
515 self.assertOutput(cli.main, ["start", "scs"],
516 expectedStdout=makeAsserter(resdir))
517
518 def testStartSIAP(self):
519 def makeAsserter(resdir):
520 def assertThings(output):
521 self.assertEqual(output, b"")
522 with open("q.rd", "r", encoding="utf-8") as f:
523 generated = f.read()
524
525 self.assertTrue(
526 'schema="%s"'%resdir in generated)
527 self.assertWellformed(generated)
528 self.assertTrue('//obscore#publishObscoreLike' in generated)
529 return True
530
531 return assertThings
532
533 with utils.sandbox(
534 tmpdir=base.getConfig("inputsDir"),
535 extractfunc=extractoutput):
536 resdir = os.path.split(os.getcwd())[-1]
537 self.assertOutput(cli.main, ["start", "siap"],
538 expectedStdout=makeAsserter(resdir))
539
540 def testStartSSAP(self):
541 def makeAsserter(resdir):
542 def assertThings(output):
543 self.assertEqual(output, b"")
544 with open("q.rd", "r", encoding="utf-8") as f:
545 generated = f.read()
546
547 self.assertTrue(
548 'schema="%s"'%resdir in generated)
549 self.assertWellformed(generated)
550 self.assertTrue('//obscore#publishSSAPMIXC' in generated)
551 return True
552
553 return assertThings
554
555 with utils.sandbox(
556 tmpdir=base.getConfig("inputsDir"),
557 extractfunc=extractoutput):
558 resdir = os.path.split(os.getcwd())[-1]
559 self.assertOutput(cli.main, ["start", "ssap+datalink"],
560 expectedStdout=makeAsserter(resdir))
561
562 def testStartEPNTAP(self):
563 def makeAsserter(resdir):
564 def assertThings(output):
565 self.assertEqual(output, b"")
566 with open("q.rd") as f:
567 generated = f.read()
568
569 self.assertTrue(
570 'schema="%s"'%resdir in generated)
571 self.assertWellformed(generated)
572 self.assertTrue('>//epntap2#localfile-2_0' in generated)
573 return True
574
575 return assertThings
576
577 with utils.sandbox(
578 tmpdir=base.getConfig("inputsDir"),
579 extractfunc=extractoutput):
580 resdir = os.path.split(os.getcwd())[-1]
581 self.assertOutput(cli.main, ["start", "epntap"],
582 expectedStdout=makeAsserter(resdir))
583
584
585 class _MyRDResource(tresc.FileResource):
586 path = "inputs/myrd.rd"
587 content = """<resource schema="test">
588 <table onDisk="True" id="autotable">
589 <column name="x" type="integer" required="True"/></table>
590 <table onDisk="True" id="noautotable">
591 <column name="x" type="integer" required="True"/></table>
592 <data id="y"><make table="autotable"/></data>
593 <data id="z" auto="False"><make table="noautotable"/></data>
594 </resource>"""
595
596
597 class DropTest(testhelpers.VerboseTest):
598 resources = [("myrdFile", _MyRDResource())]
599
600 def testAutoDropping(self):
601 self.assertOutput(cli.main, argList=["imp", "myrd", "y", "z"],
602 expectedRetcode=0, expectedStderr=lambda _: True)
603 self.assertOutput(cli.main, argList=["--ui", "stingy", "drop", "myrd"],
604 expectedRetcode=0, expectedStderr="")
605 with base.AdhocQuerier() as q:
606 self.assertTrue(q.getTableType("test.autotable") is None)
607 self.assertFalse(q.getTableType("test.noautotable") is None)
608
609 def testAllDropping(self):
610 self.assertOutput(cli.main, argList=["imp", "myrd", "y", "z"],
611 expectedRetcode=0, expectedStderr=lambda _: True)
612 self.assertOutput(cli.main, argList=["--ui", "stingy", "drop",
613 "myrd", "--all"],
614 expectedRetcode=0, expectedStderr="")
615 with base.AdhocQuerier() as q:
616 self.assertTrue(q.getTableType("test.autotable") is None)
617 self.assertTrue(q.getTableType("test.noautotable") is None)
618
619 def testNamedDropping(self):
620 self.assertOutput(cli.main, argList=["imp", "myrd", "y", "z"],
621 expectedRetcode=0, expectedStdout="", expectedStderr=lambda _: True)
622 self.assertOutput(cli.main, argList=["--ui", "stingy", "drop",
623 "myrd", "z"],
624 expectedRetcode=0, expectedStderr="", expectedStdout="")
625 with base.AdhocQuerier() as q:
626 self.assertFalse(q.getTableType("test.autotable") is None)
627 self.assertTrue(q.getTableType("test.noautotable") is None)
628
629 def testForcedDropping(self):
630 with base.getWritableAdminConn() as conn:
631 conn.execute("INSERT INTO dc.tablemeta (tablename, sourcerd, adql)"
632 " VALUES ('grabauski', 'no/nada/never', false)")
633
634 self.assertOutput(cli.main, argList=["--ui", "semistingy",
635 "drop", "-f", "no/nada/never"],
636 expectedStdout="", expectedRetcode=0)
637
638 with base.getTableConn() as conn:
639 res = list(conn.query(
640 "SELECT * from dc.tablemeta WHERE sourcerd='no/nada/never'"))
641 self.assertEqual(res, [])
642
643 def testMakeDelRecWorking(self):
644 try:
645 self.assertOutput(cli.main, argList=["adm", "makedelrec",
646 "ivo://x-testing/art/deadsvc"], expectedStdout="")
647 with base.getTableConn() as conn:
648 self.assertEqual(
649 list(conn.query("SELECT title, deleted FROM dc.resources"
650 " WHERE resId='deadsvc'")),
651 [('Ex ivo://x-testing/art/deadsvc', True)])
652 finally:
653 with base.getWritableAdminConn() as conn:
654 conn.execute("DELETE FROM dc.resources WHERE"
655 " resId='deadsvc'")
656 conn.execute("DELETE FROM dc.sets WHERE"
657 " resId='deadsvc'")
658
659 def testMakeDelRecRefusing(self):
660 self.assertOutput(cli.main, argList=["adm", "makedelrec",
661 "ivo://org.gavo.dc/art/deadsvc"],
662 expectedStderr="*** Error: You can only declare ivo ids"
663 " from your own authority as\ndeleted.\n",
664 expectedRetcode=1)
665
666
667 class ValidationTest(testhelpers.VerboseTest):
668 def testValidUserconfig(self):
669 base.caches.clearForName(str(rscdesc.USERCONFIG_RD_PATH))
670 with testtricks.testFile(rscdesc.USERCONFIG_RD_PATH.with_suffix(".rd"),
671 """<resource schema="test"><STREAM id="foo"><column name="abc"/>
672 </STREAM></resource>"""):
673 self.assertOutput(cli.main, argList=["val", "%"],
674 expectedRetcode=0, expectedStderr='',
675 expectedStdout='% -- OK\n')
676
677 def testInvalidUserconfig(self):
678 base.caches.clearForName(str(rscdesc.USERCONFIG_RD_PATH))
679 with testtricks.testFile(rscdesc.USERCONFIG_RD_PATH.with_suffix(".rd"),
680 """<resource schema="test"><STREAM id="foo"><column name="abc">
681 </STREAM></resource>"""):
682 self.assertOutput(cli.main, argList=["val", "%"],
683 expectedRetcode=0, expectedStderr='',
684 expectedStdout=lambda text: re.match(
685 rb'% -- \[ERROR\] %: Malformed RD input, message follows\s+'
686 rb"\*\*\* Error: .*etc/userconfig.rd"
687 rb"\s+mismatched\s+tag:\s+line\s+2,\s+column 6", text))
688
689 def testMiscValidation(self):
690 with testhelpers.testFile(name=None, inDir=base.getConfig("inputsDir"),
691 content="""<resource schema="notexistingXXX">
692 <meta>
693 title: Test resource
694 creationDate: 2000-01-01
695 description: no.
696 subject: even less
697 </meta>
698 <table id="t1"/>
699 <table id="t1"/>
700 </resource>""") as path:
701 rdId = path.split("/")[-1]
702
703 def doAssertions(output):
704 self.assertTrue(utils.bytify("[WARNING] %s: RD %s: resource directory"
705 " '%s/inputs/notexistingXXX' does not exist"%(
706 rdId, rdId, base.getConfig("rootDir")))
707 in output)
708
709 self.assertTrue(
710 utils.bytify("%s -- [WARNING] %s: Element with id t1 overwritten."%(
711 rdId, rdId)) in output)
712
713 self.assertTrue(output.endswith(b"OK\n"))
714 return True
715
716 self.assertOutput(cli.main, argList=["val", rdId],
717 expectedRetcode=0, expectedStderr='',
718 expectedStdout=doAssertions)
719
720 def testFileValidation(self):
721 self.assertOutput(cli.main, argList=["val", "-c", "data/test"],
722 expectedRetcode=0, expectedStderr='', expectedStdout="data/test -- OK\n")
723
724
725 class CLIReferenceTest(testhelpers.VerboseTest):
726 def testNonExRD(self):
727 self.assertRaisesWithMsg(base.RDNotFound,
728 "Resource descriptor 'i/do/not/exist' could not be located"
729 " in file system",
730 api.getReferencedElement,
731 ("i/do/not/exist",))
732
733 def testNoRDReference(self):
734 with testhelpers.testFile(os.path.join(base.getConfig("inputsDir"),
735 "nordref.rd"),
736 """<resource schema="__test"><table original="i/do/not#exist"/>
737 </resource>"""):
738 self.assertRaisesWithMsg(base.RDNotFound,
739 "Resource descriptor 'i/do/not' could not be located in file system",
740 api.getReferencedElement,
741 ("nordref",))
742
743 def testNoElDirectReference(self):
744 self.assertRaisesWithMsg(base.NotFoundError,
745 "Element with id 'justrandomjunk' could not be located in RD data/test",
746 api.getReferencedElement,
747 ("data/test#justrandomjunk",))
748
749 def testNoElIndirectReference(self):
750 with testhelpers.testFile(os.path.join(base.getConfig("inputsDir"),
751 "badref.rd"),
752 """<resource schema="__test">
753 <table original="data/test#justrandomjunk"/>
754 </resource>"""):
755 self.assertRaisesWithMsg(base.NotFoundError,
756 "Element with id 'justrandomjunk' could not be located"
757 " in RD data/test",
758 api.getReferencedElement,
759 ("badref",))
760
761 def testNoElIndirectReferenceInDir(self):
762 baseDir = os.path.join(base.getConfig("inputsDir"), "test")
763 with testhelpers.testFile(os.path.join(baseDir, "locbad.rd"),
764 """<resource schema="__test">
765 <table original="data/test#justrandomjunk"/>
766 </resource>"""):
767 with utils.in_dir(baseDir):
768 self.assertRaisesWithMsg(base.NotFoundError,
769 "Element with id 'justrandomjunk' could not be located"
770 " in RD data/test",
771 api.getReferencedElement,
772 ("locbad",))
773
774
775 class DumpingTest(testhelpers.VerboseTest):
776 resources = [("table", tresc.csTestTable)]
777
778 def testRestoreMultiOverwriting(self):
779 nrowsBefore = list(self.table.connection.query(
780 "select count(*) from dc.groups"))
781 self.table.connection.commit()
782
783 with utils.sandbox(extractfunc=extractoutput):
784 self.assertOutput(cli.main,
785 argList=["dump", "create", "tmp.ddump",
786 self.table.tableDef.getFullId(),
787 "//users#groups"],
788 expectedRetcode=0,
789 expectedStdout="")
790 self.assertOutput(cli.main,
791 argList=["dump", "load", "tmp.ddump"],
792 expectedRetcode=0,
793 expectedStdout="")
794
795 nrows = list(self.table.connection.query("select count(*) from %s"%
796 self.table.tableDef.getQName()))[0][0]
797 self.assertEqual(nrows, 1)
798 nrows = list(self.table.connection.query(
799 "select count(*) from dc.groups"))
800 self.assertEqual(nrows, nrowsBefore)
801
802 def testRestoreDeleted(self):
803 tableId = self.table.tableDef.getFullId()
804
805 with utils.sandbox(extractfunc=extractoutput):
806 self.assertOutput(cli.main,
807 argList=["dump", "create", "tmp.dump", tableId],
808 expectedRetcode=0,
809 expectedStdout="")
810
811 self.assertOutput(cli.main,
812 argList=["purge", self.table.tableDef.getQName()])
813 self.assertEqual(self.table.exists(), False)
814
815 self.assertOutput(cli.main,
816 argList=["dump", "load", "tmp.dump"],
817 expectedRetcode=0,
818 expectedStdout="")
819
820 nrows = list(self.table.connection.query("select count(*) from %s"%
821 self.table.tableDef.getQName()))[0][0]
822 self.assertEqual(nrows, 1)
823
824 def testLsDump(self):
825 with utils.sandbox(extractfunc=extractoutput):
826 self.assertOutput(cli.main,
827 argList=["dump", "create", "tmp.ddump",
828 self.table.tableDef.getFullId(),
829 "//tap"],
830 expectedRetcode=0,
831 expectedStdout="")
832 self.assertOutput(cli.main,
833 argList=["dump", "ls", "tmp.ddump"],
834 expectedRetcode=0,
835 expectedStdout=[
836 "data/test#csdata",
837 "__system__/tap#supportedmodels",
838 " probably ",
839 " 59"])
840
841
842 class ServerCallsTest(testhelpers.VerboseTest):
843 def testRunTAP(self):
844 from gavo.protocols import tap
845
846 jobId = tap.WORKER_SYSTEM.getNewJobId()
847 with tap.WORKER_SYSTEM.changeableJob(jobId) as wjob:
848 wjob.setPar("LANG", "ADQL")
849 wjob.setPar("QUERY",
850 "SELECT TOP 1 * FROM TAP_SCHEMA.tables")
851 try:
852 self.assertOutput(cli.main, argList=["taprun", jobId],
853 expectedStdout="", expectedRetcode=0, expectedStderr=[
854 "taprunner for %s finished"%jobId])
855 finally:
856 tap.WORKER_SYSTEM.destroy(jobId)
857
858 def testRunUWS(self):
859 worker = base.resolveCrossId("data/cores#pc").getUWS()
860 jobId = worker.getNewJobId()
861
862 with worker.changeableJob(jobId) as wjob:
863 wjob.setParamsFromRawDict(
864 {"opre": ["2.5"], "powers": ["1 2 3"]})
865 # this would normally happen when queuing, which we don't do here
866 # since we want to manually call uwsrun
867 wjob.completeParams()
868 try:
869 self.assertOutput(cli.main, argList=["uwsrun", jobId],
870 expectedStdout="", expectedRetcode=0, expectedStderr="")
871
872 job = worker.getJob(jobId)
873 fName, _ = job.getResult("result")
874 with open(fName, "r") as f:
875 res = f.read()
876 self.assertTrue("imaginary part" in res)
877 finally:
878 worker.destroy(jobId)
879
880
881 class UserManagementTest(testhelpers.VerboseTest):
882 def testAddtoGroupFailing(self):
883 self.assertOutput(cli.main, argList=["admin", "addtogroup",
884 "xxyz", "nogroup"],
885 expectedRetcode=1,
886 expectedStderr="*** Error: User xxyz does not exist.\n")
887
888 def testChangeUserFailing(self):
889 self.assertOutput(cli.main, argList=["admin", "changeuser",
890 "xxyz", "newpw"],
891 expectedRetcode=1,
892 expectedStderr="*** Error: User xxyz does not exist.\n")
893
894 def testDelFromGroupAndList(self):
895 try:
896 self.assertOutput(cli.main, argList=["admin", "adduser",
897 "henk", "platt", "soll nicht da sein"],
898 expectedStdout="")
899 self.assertOutput(cli.main, argList=["adm", "addtogroup",
900 "henk", "honk"], expectedStdout="")
901 self.assertOutput(cli.main, argList=["adm", "listusers"],
902 expectedStdout=[
903 "henk (soll nicht da sein) -- henk honk \n"])
904 self.assertOutput(cli.main, argList=["adm", "delfromgroup",
905 "henk", "honk"], expectedStdout="")
906 self.assertOutput(cli.main, argList=["adm", "listusers"],
907 expectedStdout=[
908 "henk (soll nicht da sein) -- henk \n"])
909 finally:
910 with base.getWritableAdminConn() as conn:
911 conn.execute(
912 "delete from dc.users where username='henk'")
913 conn.execute(
914 "delete from dc.groups where username='henk'")
915
916 def testHashPassword(self):
917 self.assertOutput(cli.main, argList=["admin", "hashP",
918 "gronk"],
919 expectedRetcode=0,
920 expectedStderr="",
921 expectedStdout=lambda s: re.match(rb"scrypt:[+/A-Za-z0-9]+=*\s*$", s))
922
923
924 if __name__=="__main__":
925 testhelpers.main(DropTest)