Debian Codegraph @

tests/misctest.py

raw
1 """
2 Some unit tests not yet fitting anywhere else.
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 contextlib
12 import datetime
13 import http.client
14 import io
15 import os
16 import pathlib
17 import re
18 import shutil
19 import sys
20 import tempfile
21 import unittest
22 from urllib import parse
23
24 import numpy
25
26 from gavo.helpers import testhelpers
27
28 from gavo import api
29 from gavo import base
30 from gavo import rscdesc
31 from gavo import votable
32 from gavo import stc
33 from gavo import utils
34 from gavo.user import upgrade
35 from gavo.helpers import filestuff
36 from gavo.helpers import processing
37 from gavo.utils import pyfits
38 from gavo.votable import tapquery
39
40 import tresc
41
42
43 class RenamerDryTest(unittest.TestCase):
44 """tests for some aspects of the file renamer without touching the file system.
45 """
46 def testSerialization(self):
47 """tests for correct serialization of clobbering renames.
48 """
49 f = filestuff.FileRenamer({})
50 fileMap = {'a': 'b', 'b': 'c', '2': '3', '1': '2'}
51 self.assertEqual(f.makeRenameProc(fileMap),
52 [('2', '3'), ('1', '2'), ('b', 'c'), ('a', 'b')])
53
54 def testCycleDetection(self):
55 """tests for cycle detection in renaming recipies.
56 """
57 f = filestuff.FileRenamer({})
58 fileMap = {'a': 'b', 'b': 'c', 'c': 'a'}
59 self.assertRaises(filestuff.Error, f.makeRenameProc, fileMap)
60
61
62 class RenamerWetTest(unittest.TestCase):
63 """tests for behaviour of the file renamer on the file system.
64 """
65 def setUp(self):
66 def touch(name):
67 f = open(name, "w")
68 f.close()
69 self.testDir = tempfile.mkdtemp("testrun")
70 for fName in ["a.fits", "a.txt", "b.txt", "b.jpeg", "foo"]:
71 touch(os.path.join(self.testDir, fName))
72
73 def tearDown(self):
74 shutil.rmtree(self.testDir, onerror=lambda exc: None)
75
76 def testOperation(self):
77 """tests an almost-realistic application
78 """
79 f = filestuff.FileRenamer.loadFromFile(
80 io.StringIO("a->b \nb->c\n 2->3\n1 ->2\n\n# a comment\n"
81 "foo-> bar\n"))
82 f.renameInPath(self.testDir)
83 found = set(os.listdir(self.testDir))
84 expected = set(["b.fits", "b.txt", "c.txt", "c.jpeg", "bar"])
85 self.assertEqual(found, expected)
86
87 def testNoClobber(self):
88 """tests for effects of repeated application.
89 """
90 f = filestuff.FileRenamer.loadFromFile(
91 io.StringIO("a->b \nb->c\n 2->3\n1 ->2\n\n# a comment\n"
92 "foo-> bar\n"))
93 f.renameInPath(self.testDir)
94 self.assertRaises(filestuff.Error, f.renameInPath, self.testDir)
95
96
97 class TimeCalcTest(testhelpers.VerboseTest):
98 """tests for time transformations.
99 """
100 def testJYears(self):
101 self.assertEqual(stc.jYearToDateTime(1991.25),
102 datetime.datetime(1991, 0o4, 0o2, 13, 30, 00))
103 self.assertEqual(stc.jYearToDateTime(2005.0),
104 datetime.datetime(2004, 12, 31, 18, 0))
105
106 def testRoundtrip(self):
107 for yr in range(2000):
108 self.assertAlmostEqual(2010+yr/1000., stc.dateTimeToJYear(
109 stc.jYearToDateTime(2010+yr/1000.)), 7,
110 "Botched %f"%(2010+yr/1000.))
111
112 def testBYears(self):
113 self.assertEqual(stc.bYearToDateTime(1950.0),
114 datetime.datetime(1949, 12, 31, 22, 9, 46, 861900))
115
116 def testBRoundtrip(self):
117 for yr in range(2000):
118 self.assertAlmostEqual(1950+yr/1000., stc.dateTimeToBYear(
119 stc.bYearToDateTime(1950+yr/1000.)), 7,
120 "Botched %f"%(1950+yr/1000.))
121
122 def testBesselLieske(self):
123 """check examples from Lieske, A&A 73, 282.
124 """
125 for bessel, julian in [
126 (1899.999142, 1900),
127 (1900., 1900.000858),
128 (1950., 1949.999790),
129 (1950.000210, 1950.0),
130 (2000.0, 1999.998722),
131 (2000.001278, 2000.0)]:
132 self.assertAlmostEqual(stc.dateTimeToJYear(stc.bYearToDateTime(bessel)),
133 julian, places=5)
134
135 def testJDDateTime(self):
136 self.assertEqual(utils.formatISODT(stc.jdnToDateTime(2458383.5)),
137 "2018-09-22T00:00:00Z")
138
139
140 class FITSProcessorTest(testhelpers.VerboseTest):
141 """tests for some aspects of helper file processors.
142
143 Unfortunately, sequencing is important here, so we do it all in
144 one test. I guess one should rethink things here, but for now let's
145 keep things simple.
146 """
147 _rdText = """<resource schema="filetest"><data id="import">
148 <sources pattern="*.fits"/><fitsProdGrammar/>
149 </data></resource>"""
150
151 def _writeFITS(self, destPath, seed):
152 hdu = pyfits.PrimaryHDU(numpy.zeros((2,seed+1), 'i2'))
153 hdu.header.set("SEED", seed, "initial number")
154 hdu.header.set("WEIRD", "W"*seed)
155 hdu.header.set("RECIP", 1./(1+seed))
156 hdu.writeto(destPath)
157
158 def setUp(self):
159 self.resdir = os.path.join(base.getConfig("tempDir"), "filetest")
160 self.origInputs = base.getConfig("inputsDir")
161 base.setConfig("inputsDir", base.getConfig("tempDir"))
162 if os.path.exists(self.resdir): # Leftover from previous run?
163 return
164 os.mkdir(self.resdir)
165 for i in range(10):
166 self._writeFITS(os.path.join(self.resdir, "src%d.fits"%i), i)
167 f = open(os.path.join(self.resdir, "filetest.rd"), "w")
168 f.write(self._rdText)
169 f.close()
170
171 def tearDown(self):
172 base.setConfig("inputsDir", self.origInputs)
173 shutil.rmtree(self.resdir, True)
174
175 class SimpleProcessor(processing.HeaderProcessor):
176 def __init__(self, *args, **kwargs):
177 processing.HeaderProcessor.__init__(self, *args, **kwargs)
178 self.headersBuilt = 0
179
180 def _isProcessed(self, srcName):
181 return "SQUARE" in self.getPrimaryHeader(srcName)
182
183 def _getHeader(self, srcName):
184 hdr = self.getPrimaryHeader(srcName)
185 hdr.set("SQUARE", hdr["SEED"]**2)
186 self.headersBuilt += 1
187 return hdr
188
189 def _getHeader(self, srcName):
190 hdus = pyfits.open(os.path.join(self.resdir, srcName))
191 hdr = hdus[0].header
192 hdus.close()
193 return hdr
194
195 def _testPlainRun(self):
196 # procmain reads argv, don't confuse it
197 sys.argv = ["test", "--bail"]
198 # Normal run, no headers present yet
199 proc, stdout, errs = testhelpers.captureOutput(processing.procmain,
200 (self.SimpleProcessor, "filetest/filetest", "import"))
201 self.assertEqual(errs, "")
202 self.assertEqual(stdout.split('\r')[-1].strip(),
203 "10 files processed, 0 files with errors")
204 self.assertEqual(proc.headersBuilt, 10)
205 self.assertTrue(os.path.exists(
206 os.path.join(self.resdir, "src9.fits.hdr")))
207 self.assertTrue("SQUARE" in self._getHeader("src9.fits.hdr"))
208 # we don't run with applyHeaders here
209 self.assertFalse("SQUARE" in self._getHeader("src9.fits"))
210
211 def _testRespectCaches(self):
212 """tests that no processing is done when cached headers are there.
213
214 This needs to run after _testPlainRun.
215 """
216 proc, stdout, _ = testhelpers.captureOutput(processing.procmain,
217 (self.SimpleProcessor, "filetest/filetest", "import"))
218 self.assertEqual(stdout.split('\r')[-1].strip(),
219 "10 files processed, 0 files with errors")
220 self.assertEqual(proc.headersBuilt, 0)
221
222 def _testNoCompute(self):
223 """tests that no computations take place with --no-compute.
224 """
225 sys.argv = ["misctest.py", "--no-compute"]
226 os.unlink(os.path.join(self.resdir, "src4.fits.hdr"))
227 proc, stdout, _ = testhelpers.captureOutput(processing.procmain,
228 (self.SimpleProcessor, "filetest/filetest", "import"))
229 self.assertEqual(proc.headersBuilt, 0)
230
231 def _testRecompute(self):
232 """tests that missing headers are recomputed.
233
234 This needs to run before _testApplyCaches and after _testNoCompute.
235 """
236 sys.argv = ["misctest.py"]
237 proc, stdout, _ = testhelpers.captureOutput(processing.procmain,
238 (self.SimpleProcessor, "filetest/filetest", "import"))
239 self.assertEqual(stdout.split('\r')[-1].strip(),
240 "10 files processed, 0 files with errors")
241 self.assertEqual(proc.headersBuilt, 1)
242
243 def _testApplyCaches(self):
244 """tests the application of headers to sources.
245
246 This needs to run after _testPlainRun
247 """
248 sys.argv = ["misctest.py", "--apply"]
249 proc, stdout, _ = testhelpers.captureOutput(processing.procmain,
250 (self.SimpleProcessor, "filetest/filetest", "import"))
251 self.assertEqual(stdout.split('\r')[-1].strip(),
252 "10 files processed, 0 files with errors")
253 self.assertEqual(proc.headersBuilt, 0)
254 self.assertTrue("SQUARE" in self._getHeader("src9.fits"))
255 # see if data survived
256 hdus = pyfits.open(os.path.join(self.resdir, "src9.fits"))
257 na = hdus[0].data
258 self.assertEqual(na.shape, (2, 10))
259
260 def _testForcedRecompute(self):
261 """tests for working --reprocess.
262 """
263 sys.argv = ["misctest.py", "--reprocess"]
264 proc, stdout, _ = testhelpers.captureOutput(processing.procmain,
265 (self.SimpleProcessor, "filetest/filetest", "import"))
266 self.assertEqual(proc.headersBuilt, 10)
267
268 def _testBugfix(self):
269 """tests for working --reprocess --apply.
270
271 This must run last since we're monkeypatching SimpleProcessor.
272 """
273 def newGetHeader(self, srcName):
274 hdr = self.getPrimaryHeader(srcName)
275 hdr.set("SQUARE", hdr["SEED"]**3)
276 self.headersBuilt += 1
277 return hdr
278 sys.argv = ["misctest.py", "--reprocess", "--apply"]
279 self.SimpleProcessor._getHeader = newGetHeader
280 sys.argv = ["misctest.py", "--reprocess"]
281 proc, stdout, _ = testhelpers.captureOutput(processing.procmain,
282 (self.SimpleProcessor, "filetest/filetest", "import"))
283 self.assertEqual(self._getHeader("src6.fits.hdr")["SQUARE"], 216)
284
285 def testAll(self):
286 self._testPlainRun()
287 self._testRespectCaches()
288 self._testNoCompute()
289 self._testRecompute()
290 self._testForcedRecompute()
291 self._testApplyCaches()
292 self._testForcedRecompute()
293 self._testBugfix()
294
295
296 class SpectrumPreviewTest(testhelpers.VerboseTest):
297 def testBuildSpectrum(self):
298 destPath = os.path.join(
299 api.getConfig("inputsDir"),
300 "ssa-nopreviews",
301 "fake-preview")
302 if os.path.exists(destPath):
303 os.unlink(destPath)
304
305 class PreviewMaker(api.SpectralPreviewMaker):
306 sdmId = "datamaker"
307
308 def iterIdentifiers(self):
309 yield "this is not actually an identifer, just unit test stuff"
310
311 def getPreviewPath(self, accref):
312 return destPath
313
314 class opts:
315 nParallel = 1
316 doReport = False
317 force = True
318 bailOnError = True
319 requireFrag = None
320
321 proc = PreviewMaker(opts, api.resolveCrossId("data/ssatest#test_import"))
322 rtval, stdout, stderr = testhelpers.captureOutput(proc.processAll)
323
324 self.assertEqual(rtval, (1, 0))
325 self.assertEqual(stderr, "")
326
327 with open(destPath, "rb") as f:
328 prevData = f.read()
329
330 self.assertTrue(b"IDATx\x9c\xed\xda\xbb\r\x83@\x10\x84" in prevData,
331 "Generated spectrum preview doesn't contain expected data")
332
333
334 @contextlib.contextmanager
335 def _fakeHTTPLib(respData="", respStatus=200,
336 mime="application/x-votable", exception=None):
337 """runs a test with a fake httplib connection maker.
338
339 This is for TapquerySyncTest and similar.
340 """
341 class FakeResult(object):
342 status = respStatus
343
344 def getheader(self, key):
345 if key.lower()=='content-type':
346 return mime
347 else:
348 self.fail()
349
350 def read(self):
351 return respData
352
353 class FakeInfo(object):
354 pass
355
356 class FakeConnection(object):
357 def __init__(self, *args, **kwargs):
358 pass
359
360 def request(self, method, path, data, headers):
361 FakeInfo.lastData = data
362 if exception is not None:
363 raise exception
364
365 def getresponse(self, *args, **kwargs):
366 return FakeResult()
367
368 def close(self):
369 pass
370
371 origConn = http.client.HTTPConnection
372 http.client.HTTPConnection = FakeConnection
373 try:
374 yield FakeInfo
375 finally:
376 http.client.HTTPConnection = origConn
377
378
379 class TapquerySyncTest(testhelpers.VerboseTest):
380 # Tests for the tapquery sync object; since TAP queries are expensive,
381 # we only test things that don't actually run a query. For more extensive
382 # exercising, see the taptest RD at the GAVO DC.
383 endpoint = "http://dachstest"
384
385 def testNoResult(self):
386 job = votable.ADQLSyncJob(self.endpoint,
387 "select * from tap_schema.tables")
388 self.assertRaisesWithMsg(tapquery.Error,
389 "No result in so far",
390 job.openResult,
391 ())
392
393 def testWrongStatus(self):
394 with _fakeHTTPLib(respData=b"oops", respStatus=404):
395 job = votable.ADQLSyncJob(self.endpoint,
396 "select * from tap_schema.tables")
397 self.assertRaises(tapquery.WrongStatus, job.start)
398 self.assertEqual(job.getErrorFromServer(), "oops")
399
400 def testHTTPError(self):
401 import socket
402 with _fakeHTTPLib(respData="oops", exception=socket.error("timeout")):
403 job = votable.ADQLSyncJob(self.endpoint,
404 "select * from tap_schema.tables")
405 self.assertRaises(tapquery.NetworkError, job.start)
406 self.assertEqual(job.getErrorFromServer(),
407 'Problem connecting to dachstest (timeout)')
408
409 def testTAPError(self):
410 with _fakeHTTPLib(respData="""<VOTABLE version="1.2" xmlns:vot="http://www.ivoa.net/xml/VOTable/v1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ivoa.net/xml/VOTable/v1.2 http://vo.ari.uni-heidelberg.de/docs/schemata/VOTable-1.2.xsd"><RESOURCE type="results"><INFO name="QUERY_STATUS" value="ERROR">Could not parse your query: Expected "SELECT" (at char 0), (line:1, col:1)</INFO></RESOURCE></VOTABLE>""", respStatus=400):
411 job = votable.ADQLSyncJob(self.endpoint,
412 "selct * from tap_schema.tables")
413 self.assertRaises(tapquery.WrongStatus, job.start)
414 self.assertEqual(job.getErrorFromServer(),
415 'Could not parse your query: Expected "SELECT" (at char 0),'
416 ' (line:1, col:1)')
417
418 def testConstructionParameters(self):
419 with _fakeHTTPLib(respData=b"ok") as fakeInfo:
420 job = votable.ADQLSyncJob(self.endpoint,
421 "select * from tap_schema.tables", userParams={"MAXREC": 0})
422 job.start()
423 self.assertEqual(parse.parse_qs(fakeInfo.lastData)["MAXREC"], ["0"])
424
425 def testLaterParameters(self):
426 with _fakeHTTPLib(respData=b"ok") as fakeInfo:
427 job = votable.ADQLSyncJob(self.endpoint,
428 "select * from tap_schema.tables")
429 job.setParameter("MAXREC", 0)
430 job.start()
431 self.assertEqual(parse.parse_qs(fakeInfo.lastData)["MAXREC"], ["0"])
432
433
434 class KVLParseTest(testhelpers.VerboseTest):
435 # Tests for our key-value line format (as in postgres)
436 def testNoQuote(self):
437 self.assertEqual(utils.parseKVLine("anz=29"), {"anz": "29"})
438
439 def testWhitespaceAroundEqual(self):
440 self.assertEqual(utils.parseKVLine("a =29 bo= orz Unt = Lopt"),
441 {"a": "29", "bo": "orz", "Unt": "Lopt"})
442
443 def testQuotedString(self):
444 self.assertEqual(utils.parseKVLine(
445 "simp='abc' a ='29' bo= 'orz' Unt = 'Lopt'"),
446 {"simp": "abc", "a": "29", "bo": "orz", "Unt": "Lopt"})
447
448 def testWithBlanks(self):
449 self.assertEqual(utils.parseKVLine(
450 "name='Virtual Astrophysical' a=' 29'"),
451 {"name": 'Virtual Astrophysical', "a": ' 29'})
452
453 def testEscaping(self):
454 self.assertEqual(utils.parseKVLine(
455 r"form='f\'(x) = 2x^3' escChar='\\'"),
456 {"form": "f'(x) = 2x^3", "escChar": '\\'})
457
458 def testEmpty(self):
459 self.assertEqual(utils.parseKVLine(
460 "kram='' prokto=logic"),
461 {"kram": "", "prokto": 'logic'})
462
463 def testBadKey(self):
464 self.assertRaisesWithMsg(utils.ParseException,
465 utils.EqualingRE(r"Expected Keyword, found '7(ana)?' \(at char 0\), \(line:1, col:1\)"),
466 utils.parseKVLine,
467 ("7ana=kram",))
468
469 def testMissingEqual(self):
470 self.assertRaisesWithMsg(utils.ParseException,
471 utils.EqualingRE('Expected [\'"]=[\'"], found end of text \\(at char 7\\), \\(line:1, col:8\\)'),
472 utils.parseKVLine,
473 ("yvakram",))
474
475 def testBadValue(self):
476 self.assertRaisesWithMsg(utils.ParseException,
477 "Expected end of text, found \"'\" (at char 7), (line:1, col:8)",
478 utils.parseKVLine,
479 ("borken='novalue",))
480
481 def testTooManyEquals(self):
482 self.assertRaisesWithMsg(utils.ParseException,
483 'Expected end of text, found \'=\' (at char 14), (line:1, col:15)',
484 utils.parseKVLine,
485 ("borken=novalue=ab",))
486
487
488 class KVLMakeTest(testhelpers.VerboseTest):
489 def testWithKeywords(self):
490 self.assertEqual(utils.makeKVLine({"ab": "cd", "honk": "foo"}),
491 "ab=cd honk=foo")
492
493 def testWithWeird(self):
494 self.assertEqual(utils.makeKVLine({"ab": "c d", "honk": "foo=?"}),
495 "ab='c d' honk='foo=?'")
496
497 def testWithEscaping(self):
498 self.assertEqual(
499 utils.makeKVLine({"form": "f'(x) = 2x^3", "escChar": '\\'}),
500 "escChar='\\\\' form='f\\'(x) = 2x^3'")
501
502 def testFailsWithBadKey(self):
503 self.assertRaisesWithMsg(ValueError,
504 "'a form' not allowed as a key in key-value lines",
505 utils.makeKVLine,
506 ({"a form": "f'(x) = 2x^3"},))
507
508
509 import grp
510 from gavo.base import osinter
511
512 class OSInterTest(testhelpers.VerboseTest):
513 def testMakeSharedDir(self):
514 path = os.path.join(base.getConfig("inputsDir"), "_dir_form_unit_test_")
515 try:
516 osinter.makeSharedDir(path, writable=True)
517 stats = os.stat(path)
518 self.assertEqual(stats.st_mode&0o060, 0o60)
519 self.assertEqual(grp.getgrgid(stats.st_gid).gr_name, "gavo")
520
521 os.chown(path, -1, os.getgid())
522 osinter.makeSharedDir(path, writable=True)
523 self.assertEqual(grp.getgrgid(stats.st_gid).gr_name, "gavo")
524 finally:
525 os.rmdir(path)
526
527 def testSwitchHTTP(self):
528 self.assertEqual(
529 osinter.switchProtocol("http://localhost:8080/bar/romp?hook#dork"),
530 "https://localhost/bar/romp?hook#dork")
531
532 def testSwitchHTTPS(self):
533 self.assertEqual(
534 osinter.switchProtocol("https://localhost/bar/romp?hook#dork"),
535 "http://localhost:8080/bar/romp?hook#dork")
536
537 def testSwitchOtherURL(self):
538 self.assertRaises(ValueError,
539 osinter.switchProtocol,
540 "http://ivoa.net/documents")
541
542 def testMailFormat(self):
543 res = osinter.formatMail("""From: "Foo Bar\xdf" <[email protected]>
544 To: [email protected]
545 Subject: Test Mail
546 X-Testing: Yes
547
548 This is normal text with shitty characters: '\xdf\xe4i\xdf\xe4'.
549
550 Send it, anyway.
551
552 Cheers,
553
554 Foo.
555 """)
556 self.assertTrue(isinstance(res, str))
557 self.assertTrue("MIME-Version: 1.0" in res)
558 self.assertTrue(" characters: '=C3=9F=" in res)
559 self.assertTrue("From: =?utf-8?q?=22Foo_Bar=C3=9F=2" in res)
560 self.assertTrue("X-Testing: Yes" in res)
561 self.assertTrue("Subject: Test Mail" in res)
562 self.assertTrue("To: [email protected]" in res)
563 self.assertTrue(re.search("Date: .*GMT", res))
564
565 def testIvoidExternal(self):
566 self.assertEqual(
567 base.makeLinkForIvoid("ivo://leibniz-kis/chrotel/q/epn_core"),
568 "https://dc.g-vo.org/LP/ivo://leibniz-kis/chrotel/q/epn_core")
569
570 def testIvoidMalformed(self):
571 self.assertRaisesWithMsg(
572 ValueError,
573 "Not an ivoid: ''",
574 base.makeLinkForIvoid,
575 ("",))
576
577 def testIvoidInternalNonResolving(self):
578 self.assertEqual(
579 base.makeLinkForIvoid("ivo://x-testing/toss/q/line_tap"),
580 "https://dc.g-vo.org/LP/ivo://x-testing/toss/q/line_tap")
581
582 def testIvoidInternalResolving(self):
583 self.assertEqual(
584 base.makeLinkForIvoid("ivo://x-testing/data/cores/dl"),
585 "http://localhost:8080/data/cores/dl/info")
586
587
588 import lxml
589 from gavo.helpers import testtricks
590
591 VALID_OAI = """<?xml-stylesheet href='/static/xsl/oai.xsl' type='text/xsl'?><oai:OAI-PMH xmlns:oai="http://www.openarchives.org/OAI/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/ http://vo.ari.uni-heidelberg.de/docs/schemata/OAI-PMH.xsd"><oai:responseDate>2014-07-21T15:13:09Z</oai:responseDate><oai:request verb="ListSets"/><oai:ListSets><oai:set><oai:setSpec>ivo_managed</oai:setSpec><oai:setName>ivo_managed</oai:setName></oai:set></oai:ListSets></oai:OAI-PMH>"""
592
593 class ValidatorTest(testhelpers.VerboseTest):
594 def testSimpleValidator(self):
595 val = testtricks.getJointValidator(["oai_dc.xsd", "OAI-PMH.xsd"])
596 oaiTree = lxml.etree.fromstring(VALID_OAI)
597 val.assertValid(oaiTree)
598
599 lxml.etree.SubElement(oaiTree[2][0], "p")
600 self.assertFalse(val(oaiTree))
601
602
603 class PgValidatorTest(testhelpers.VerboseTest):
604 resources = [("conn", tresc.dbConnection)]
605
606 def testBasicAcceptance(self):
607 base.sqltypeToPgValidator("integer")("int4")
608
609 def testBadRejecting(self):
610 self.assertRaisesWithMsg(base.ConversionError,
611 "No Postgres pg_types validators type for float",
612 base.sqltypeToPgValidator,
613 ("float",))
614
615 def testBasicRejecting(self):
616 self.assertRaisesWithMsg(TypeError,
617 "int4 is not compatible with a float column",
618 base.sqltypeToPgValidator("real"),
619 ("int4",))
620
621 def testArrayAcceptance(self):
622 base.sqltypeToPgValidator("real[]")("_float8")
623
624 def testNondbRejecting(self):
625 self.assertRaisesWithMsg(TypeError,
626 "Column with a non-db type file mapped to db type wurst",
627 base.sqltypeToPgValidator("file"),
628 ("wurst",))
629
630 def testPgSphereOk(self):
631 rd = api.parseFromString(api.RD,
632 """<resource schema="test"><table id="valtest" onDisk="true">
633 <column name="x" type="spoint"/></table></resource>""")
634 rd.sourceId = "inline"
635 table = api.TableForDef(rd.tables[0], connection=self.conn, create=True)
636 try:
637 table.ensureOnDiskMatches() # raises DataError if test fails
638 finally:
639 self.conn.rollback()
640 table.drop()
641
642 def testPgSphereRaises(self):
643 rd = api.parseFromString(api.RD,
644 """<resource schema="public"><table id="valtest" onDisk="true">
645 <column name="x" type="spoint"/></table></resource>""")
646 rd.sourceId = "inline"
647 self.conn.execute("create table valtest (x integer)")
648 table = api.TableForDef(rd.tables[0], connection=self.conn)
649 try:
650 self.assertRaisesWithMsg(api.DataError,
651 "Table public.valtest: type mismatch in column x (Incompatible"
652 " type in DB: Expected spoint, found int4)",
653 table.ensureOnDiskMatches,
654 ())
655 finally:
656 self.conn.rollback()
657 table.drop()
658
659
660 from gavo.user import validation
661
662 class TableValTest(testhelpers.VerboseTest):
663 resources = [("ignored", tresc.csTestTable)]
664
665 class defaultArgs:
666 compareDB = False
667
668 def _getRdWithTable(self, columns):
669 rd = base.parseFromString(rscdesc.RD,
670 """<resource schema="__test"><table id="totest" onDisk="True">
671 <meta>
672 creationDate: 2012-12-12T12:12:12
673 subject: testing
674 description: something to ignore
675 </meta>
676 %s</table></resource>"""%columns)
677 rd.sourceId = "testing/q"
678 return rd
679
680 def _getValFuncOutput(self, func, rd):
681 return testhelpers.captureOutput(func, (rd, self.defaultArgs))[1]
682
683 def _getMessagesForColumns(self, columns):
684 rd = self._getRdWithTable(columns)
685 return self._getValFuncOutput(validation.validateTables, rd)
686
687 def testReservedName(self):
688 self.assertEqual(self._getMessagesForColumns(
689 "<column name='distance'/>"),
690 "[WARNING] testing/q: Column totest.distance: Name is not a regular ADQL identifier.\n")
691
692 def testDelimitedId(self):
693 self.assertEqual(self._getMessagesForColumns(
694 "<column name='quoted/distance'/>"),
695 "")
696
697 def testBadUCD(self):
698 self.assertEqual(self._getMessagesForColumns(
699 "<column name='foo' ucd='em.IR'/>"),
700 "[WARNING] testing/q: Column __test.totest.foo: UCD em.IR not accepted by astropy (Secondary word 'em.IR' is not valid as a primary word).\n")
701
702 def testTAPSchemaValidation(self):
703 td = testhelpers.getTestRD().getById("csdata")
704 prev = td.columns[0].ucd
705 try:
706 td.columns[0].ucd = "blabla"
707 self.assertEqual(
708 list(validation.validateTable(td, True)), [
709 ('warning', 'Column test.csdata.alpha: UCD blabla not'
710 " accepted by astropy (Unknown word 'blabla')."),
711 ('error',
712 "Table test.csdata: Column alpha: tap_schema ucd!='blabla'")])
713 finally:
714 td.columns[0].ucd = prev
715
716
717 from gavo.web import examplesrender
718
719 class ExamplesTest(testhelpers.VerboseTest):
720 def testWorkingExamples(self):
721 ex = examplesrender.Example(
722 base.META_CLASSES_FOR_KEYS["_example"](
723 "Here is a :genparam:`par(example, no?)` "
724 "example for genparam.""", title="Working genparam"))
725 res = ex._getTranslatedHTML()
726 self.assertTrue(b'<span property="generic-parameter" typeof="keyval"'
727 in res)
728 self.assertTrue(b'<span property="key" class="genparam-key">par</span>'
729 in res)
730 self.assertTrue(b'<span property="value" class="genparam-value">'
731 b'example, no?</span>' in res)
732
733 def testFailingExample(self):
734 ex = examplesrender.Example(
735 base.META_CLASSES_FOR_KEYS["_example"]("Here is a :genparam:`parfoo` "
736 "example for genparam.""", title="Working genparam"))
737 res = ex._getTranslatedHTML()
738 self.assertTrue(b"parfoo does not" in res)
739 self.assertTrue(b'<span class="problematic"' in res)
740
741
742 def _getUpgraders():
743 class To10Upgrader(upgrade.Upgrader):
744 version = 9
745 s_010_foo = "CREATE TABLE foo"
746 u_010_fill_foo = "INSERT INTO foo"
747
748 class To11Upgrader(upgrade.Upgrader):
749 version = 10
750
751 s_010_bar = "CREATE TABLE bar"
752
753 u_010_fill_bar = "INSERT INTO bar"
754
755 u_005_register_bar = "INSERT INTO metastore"
756
757 class To20Upgrader(upgrade.Upgrader):
758 version = 19
759
760 s_005_addheck = "ALTER TABLE bar ADD COLUMN quux"
761 s_010_addheck = "ALTER TABLE bar ADD COLUMN honk"
762
763 return list(locals().values())
764
765
766 class UpgraderTest(testhelpers.VerboseTest):
767 def testSchemachangeSort(self):
768 statements = list(upgrade.iterStatements(9, 11, _getUpgraders()))
769 self.assertEqual(statements[0], "CREATE TABLE foo")
770 self.assertTrue(statements[2] is upgrade._COMMIT)
771 self.assertEqual(statements[3], 'INSERT INTO foo')
772 updateSchemaversion = statements[4]
773 self.assertTrue("To10Upgrader" in repr(updateSchemaversion.__self__))
774 self.assertEqual(len(statements), 10)
775
776 def testHoleCovered(self):
777 statements = list(upgrade.iterStatements(10, 20, _getUpgraders()))
778 self.assertEqual(statements[2], "ALTER TABLE bar ADD COLUMN honk")
779 self.assertTrue(statements[3] is upgrade._COMMIT)
780 self.assertTrue("To20Upgrader" in repr(statements[-2].__self__))
781
782
783 class TestScaffoldTest(testhelpers.VerboseTest):
784 def testDataServer(self):
785 with testhelpers.DataServer("success!\n") as url:
786 res = utils.urlopenRemote(url).read()
787 self.assertEqual(res, b"success!\n")
788
789 # try another to make sure the first has been killed; if
790 # it hasn't then this second server can't be bound to the port.
791 with testhelpers.DataServer(b"second success!\n") as url:
792 res = utils.urlopenRemote(url).read()
793 self.assertEqual(res, b"second success!\n")
794
795
796 from gavo import rsc
797 from gavo.formats import fitstable
798 from gavo.user import mkrd
799
800 class FITSColGenTest(testhelpers.VerboseTest,
801 metaclass=testhelpers.SamplesBasedAutoTest):
802 def testBasic(self):
803 table = api.TableForDef(api.resolveCrossId("data/test#abcd"),
804 rows=[{"a": "foobar", "b": 23, "c": 42, "d": 0,
805 "e": datetime.datetime(2011, 12, 12)}])
806 hdus = fitstable.makeFITSTable(rsc.wrapTable(table))
807 self.assertEqual(
808 mkrd.getColumnXML(mkrd.iterColAttrsFITS(hdus[1])),
809 '<column name="a" type="text"\n'
810 ' \n'
811 ' description="Some weirdness"\n'
812 ' verbLevel="1"/>\n'
813 '<column name="b" type="integer"\n'
814 ' \n'
815 ' description=""\n'
816 ' verbLevel="1"/>\n'
817 '<column name="c" type="integer"\n'
818 ' \n'
819 ' description=""\n'
820 ' verbLevel="1"/>\n'
821 '<column name="d" type="integer"\n'
822 ' unit="km" \n'
823 ' description=""\n'
824 ' verbLevel="1"/>\n'
825 '<column name="e" type="text"\n'
826 ' \n'
827 ' utype="junk.junk.junk"\n'
828 ' description=""\n'
829 ' verbLevel="1"/>')
830
831 def testBadCode(self):
832 self.assertRaisesWithMsg(
833 base.ReportableError,
834 "FITS type code 'JUNK' of flaubert not handled by gavo mkrd;"
835 " add handling if you can.",
836 mkrd.getTypeForFTFormat,
837 ("JUNK", "flaubert"))
838
839 def _runTest(self, example):
840 fitsCode, dbType = example
841 self.assertEqual(
842 mkrd.getTypeForFTFormat(fitsCode, "testing"),
843 dbType)
844
845 samples = [
846 ("A", "char"),
847 ("1A", "char"),
848 ("10A", "text"),
849 ("L", "boolean"),
850 ("15L", "boolean[]"),
851 #5
852 ("1B", "bytea"),
853 ("10I", "smallint[]"),
854 ("J", "integer"),
855 ("40K", "bigint[]"),
856 ("2E", "real[]"),
857 #10
858 ("2D", "double precision[]"),
859 ("PD()", "double precision[]"),
860 ("1PE()", "real[]"),
861 ("1PI(120)", "smallint[]"),
862 ("PA()", "text"),
863 ]
864
865
866 class VOTableColGenTest(testhelpers.VerboseTest):
867 def testBasic(self):
868 from gavo.formats import votable
869 table = api.TableForDef(api.resolveCrossId("data/test#abcd"))
870 inF = io.BytesIO(votable.getAsVOTable(table))
871 self.assertEqual(
872 mkrd.getColumnXML(mkrd.iterColAttrsVOTable(inF, 1)),
873 '<column name="a" type="text"\n'
874 ' ucd=""\n'
875 ' description="Some weirdness"\n'
876 ' verbLevel="1"/>\n'
877 '<column name="b" type="integer"\n'
878 ' ucd=""\n'
879 ' description=""\n'
880 ' verbLevel="1"/>\n'
881 '<column name="c" type="integer"\n'
882 ' ucd=""\n'
883 ' description=""\n'
884 ' verbLevel="1"/>\n'
885 '<column name="d" type="integer"\n'
886 ' unit="km" ucd=""\n'
887 ' description=""\n'
888 ' verbLevel="1"/>\n'
889 '<column name="e" type="timestamp"\n'
890 ' ucd=""\n'
891 ' utype="junk.junk.junk"\n'
892 ' description=""\n'
893 ' verbLevel="1"/>')
894
895
896 _BBB_EXAMPLE = """
897 Some random junk
898
899 Abstract:
900 We provide a catalogue of 541 stars, brown dwarfs, and exoplanets in 339
901 outreach potential.
902
903 File Summary:
904 --------------------------------------------------------------------------------
905 FileName Lrecl Records Explanations
906 --------------------------------------------------------------------------------
907 ReadMe 80 . this file
908 The10pcSample.dat 930 561 the 10 pc catalogue
909
910
911 --------------------------------------------------------------------------------
912 Byte-by-byte Description of file: The10pcSample.dat
913 --------------------------------------------------------------------------------
914 Bytes Format Units Label Explanations
915 --------------------------------------------------------------------------------
916 1- 4 I4 --- NB_OBJ Running number for object
917 11- 36 A26 --- SYSTEM_NAME Name of the system
918 74- 87 F14.9 --- RA Right ascension in ICRS
919 129-159 A31 --- PARALLAX_BIBCODE Reference for the parallax
920 178-193 F7.2 mas/yr PMRA_ERROR Proper motion uncertainty in right
921 ascension
922 348-349 I2 --- G_CODE =2 if G from Gaia DR2 ; =3 if G from
923 Gaia EDR3 ; =10 if G derived from
924 spectral type ; =20 for spectral type >T6
925 (arbitrarily set to absolute G mag = 25)
926 583-930 I8 --- COMMENT Additional comments on exoplanets,
927 multiplicity, etc
928
929 --------------------------------------------------------------------------------
930 """
931
932 class VizColGenTest(testhelpers.VerboseTest):
933 def testBasic(self):
934 self.assertEqual(
935 mkrd.getColumnXML(mkrd.iterColAttrsViz(io.StringIO(_BBB_EXAMPLE))),
936 '<column name="NB_OBJ" type="integer"\n'
937 ' ucd=""\n'
938 ' description="Running number for object"\n'
939 ' verbLevel="1"/>\n'
940 '<column name="SYSTEM_NAME" type="text"\n'
941 ' ucd=""\n'
942 ' description="Name of the system"\n'
943 ' verbLevel="1"/>\n'
944 '<column name="RA" type="double precision"\n'
945 ' ucd=""\n'
946 ' description="Right ascension in ICRS"\n'
947 ' verbLevel="1"/>\n'
948 '<column name="PARALLAX_BIBCODE" type="text"\n'
949 ' ucd=""\n'
950 ' description="Reference for the parallax"\n'
951 ' verbLevel="1"/>\n'
952 '<column name="PMRA_ERROR" type="real"\n'
953 ' unit="mas/yr" ucd=""\n'
954 ' description="Proper motion uncertainty in right ascension"\n'
955 ' verbLevel="1"/>\n'
956 '<column name="G_CODE" type="smallint"\n'
957 ' ucd=""\n'
958 ' description="=2 if G from Gaia DR2 ; =3 if G from Gaia EDR3 ; =10 if G derived from spectral type ; =20 for spectral type >T6 (arbitrarily set to absolute G mag = 25)"\n'
959 ' verbLevel="1"/>\n'
960 '<column name="COMMENT" type="bigint"\n'
961 ' ucd=""\n'
962 ' description="Additional comments on exoplanets, multiplicity, etc"\n'
963 ' verbLevel="1"/>')
964
965
966 from gavo.base import typesystems
967
968 # I think we ought to have a test module for the whole type conversion
969 # thing -- I wonder why I didn't make one back when I wrote that stuff
970 class ScalarifyTest(testhelpers.VerboseTest,
971 metaclass=testhelpers.SamplesBasedAutoTest):
972 def _runTest(self, sample):
973 arrtype, stype = sample
974 self.assertEqual(typesystems.scalarify(arrtype), stype)
975
976 samples = [
977 ("char", "char"),
978 ("spoly", "spoly"),
979 ("int[]", "int"),
980 ("int[12][]", "int"),]
981
982 def testWithConversion(self):
983 self.assertEqual(typesystems.sqltypeToPython(
984 typesystems.scalarify("bigint[22][]"))("432"), 432)
985
986
987 from gavo.imp import astropyucd
988
989 class UCDTest(testhelpers.VerboseTest):
990 def testBasic(self):
991 self.assertEqual(
992 astropyucd.parse_ucd("pos.eq.dec;meta.main"),
993 [('ivoa', 'pos.eq.dec'), ('ivoa', 'meta.main')])
994
995 def testColor(self):
996 self.assertEqual(
997 astropyucd.parse_ucd("phot.color;em.opt.B;em.opt.V"),
998 [('ivoa', 'phot.color'), ('ivoa', 'em.opt.B'), ('ivoa', 'em.opt.V')])
999
1000 def testNonPrimary(self):
1001 self.assertEqual(
1002 astropyucd.check_ucd("obs;meta.curation",
1003 check_controlled_vocabulary=True),
1004 False)
1005
1006
1007 from gavo.user.admin import hipsgen, hipsfill
1008
1009
1010 class HipsGenTest(testhelpers.VerboseTest):
1011 def testHipsgen(self):
1012 with testhelpers.testFile("hg.rd", """<resource schema="test">
1013 <meta>
1014 creator: Painter, J.
1015 creationDate: 1981-12-24
1016 description: Pictures at an Exhibition
1017 subject: imaging
1018 title: ELP
1019 </meta>
1020 <table id="pics">
1021 <publish/>
1022 </table>
1023 <data id="imp">
1024 <sources pattern="data1/*.fits">
1025 <pattern>data2/fits/*.fits</pattern>
1026 </sources>
1027 <fitsProdGrammar/>
1028 <make><table/></make>
1029 </data></resource>""",
1030 inDir=base.getConfig("inputsDir")):
1031 _, generatedOutput, err = testhelpers.captureOutput(
1032 hipsgen,
1033 (None, utils.NS(dataId="hg#imp", minOrder=3)))
1034 self.assertEqual(generatedOutput,
1035 "in=data1\n"
1036 "in=data2/fits\n"
1037 "minOrder=3\n"
1038 "creator: Painter, J.\n"
1039 "id=ivo://x-testing/hg/pics\n"
1040 "status=public clonable\n"
1041 "title=ELP\n"
1042 "out=hips\n")
1043
1044 def testHipsfill(self):
1045 with tempfile.TemporaryDirectory() as d:
1046 with testhelpers.testFile("properties",
1047 "creator_did = ivo://org.gavo.dc/P/fornax/q/c\n"
1048 "#hips_creator = HiPS creator (institute or person)\n"
1049 "bib_reference = Gallilei, G., in prep.\n"
1050 "#obs_regime = Waveband keyword (Radio\n"
1051 "#em_max = Stop in spectral coordinates in meters\n",
1052 inDir=d) as tf:
1053 hipsfill(None,
1054 utils.NS(
1055 svcId="data/cores#convcat",
1056 hipsDir=pathlib.Path(d)))
1057 with open(tf) as f:
1058 filledOut = f.read()
1059
1060 self.assertEqual(filledOut,
1061 """creator_did = ivo://org.gavo.dc/P/fornax/q/c
1062 hips_creator = Gandalf, W.
1063 bib_reference = Gallilei, G., in prep.
1064 #obs_regime = Waveband keyword (Radio
1065 em_max = 6.621486190496428e-06
1066 """)
1067
1068
1069 class BiblinksImportTest(testhelpers.VerboseTest):
1070 resources = [("conn", tresc.dbConnection)]
1071
1072 def testImport(self):
1073 rd = base.caches.getRD("data/testdata")
1074 api.makeData(rd.getById("import-biblinks"), connection=self.conn)
1075
1076 with base.getTableConn() as conn:
1077 created = list(conn.queryToDicts("select * from dc.biblinks"))
1078
1079 self.assertEqual(len(created), 4)
1080 self.assertEqual(set(r["bib_ref"] for r in created
1081 if r["dataset_ref"]=='http://reg.g-vo.org/LP/x-testing/data/testdata/haslinks'),
1082 {'2015A&C....10...88D', '2005ASPC..347...29T'})
1083 self.assertEqual(set(r["relationship"] for r in created),
1084 {"Cites", "IsSupplementedBy"})
1085 self.assertEqual(set(r["bib_format"] for r in created),
1086 {None, "doi"})
1087 self.assertEqual(set(r["dataset_ref"] for r in created
1088 if r["bib_ref"]=='10.1051/0004-6361:20010923'),
1089 {'http://localhost:8080/getproduct/prod1.bin',
1090 'http://localhost:8080/getproduct/prod0.bin'})
1091
1092 def testReimport(self):
1093 # this tests whether importing removes the previously obtained
1094 # biblinks.
1095 return self.testImport()
1096
1097
1098 from gavo.rscdef import regtest
1099
1100 _EMPTY_VOTABLE = b"""
1101 <VOTABLE version="1.4" xmlns="http://www.ivoa.net/xml/VOTable/v1.3">
1102 <RESOURCE type="results">
1103 <TABLE name="result">
1104 <FIELD ID="hipno" arraysize="*" datatype="char" name="hipno" ucd="ID_MAIN"/>
1105 <DATA><BINARY><STREAM encoding="base64"/></BINARY>
1106 </DATA></TABLE></RESOURCE></VOTABLE>"""
1107
1108 _ERROR_VOTABLE = b"""
1109 <VOTABLE version="1.4" xmlns="http://www.ivoa.net/xml/VOTable/v1.3">
1110 <RESOURCE type="results">
1111 <INFO ID="Error" name="Error" value="Field SR: 'fromp' is not a valid literal for SR"/></RESOURCE></VOTABLE>"""
1112
1113
1114 class RegTestTest(testhelpers.VerboseTest):
1115 def testGetRowEmptyResponse(self):
1116 t = api.makeStruct(regtest.RegTest, title="Testtest")
1117 t.data = _EMPTY_VOTABLE
1118 self.assertEqual(t.getVOTableRows(), [])
1119
1120 def testGetRowErrorResponse(self):
1121 t = api.makeStruct(regtest.RegTest, title="Testtest")
1122 t.data = _ERROR_VOTABLE
1123 self.assertRaisesWithMsg(
1124 AssertionError,
1125 "Response did not contain a TABLE -- is it an error message?",
1126 t.getVOTableRows,
1127 ())
1128
1129 def testGetFirstErrorResponse(self):
1130 t = api.makeStruct(regtest.RegTest, title="Testtest")
1131 t.data = _ERROR_VOTABLE
1132 self.assertRaisesWithMsg(
1133 AssertionError,
1134 "Response did not contain a TABLE -- is it an error message?",
1135 t.getFirstVOTableRow,
1136 ())
1137
1138
1139 if __name__=="__main__":
1140 testhelpers.main(KVLMakeTest)