Debian Codegraph @

tests/formatstest.py

raw
1 # -*- coding: utf-8 -*-
2 """
3 Tests having to do with various output formats.
4 """
5
6 #c Copyright 2008-2025, the GAVO project <[email protected]>
7 #c
8 #c This program is free software, covered by the GNU GPL. See the
9 #c COPYING file in the source distribution.
10
11
12 import base64
13 import datetime
14 import io
15 import json
16 import os
17 import re
18 import warnings
19 from xml.etree import ElementTree as etree
20
21 from gavo.helpers import testhelpers
22
23 from gavo import base
24 from gavo import formal
25 from gavo import formats
26 from gavo import rsc
27 from gavo import rscdef
28 from gavo import rscdesc
29 from gavo import svcs
30 from gavo import utils
31 from gavo import votable
32 from gavo import web #noflake: for registration
33 from gavo.base import valuemappers #noflake: for registration
34 from gavo.formats import csvtable #noflake: for registration
35 from gavo.formats import fitstable #noflake: for registration
36 from gavo.formats import geojson #noflake: for registration
37 from gavo.formats import jsontable #noflake: for registration
38 from gavo.formats import texttable #noflake: for registration
39 from gavo.formats import votablewrite #noflake: for registration
40 from gavo.svcs import outputdef
41 from gavo.utils import pgsphere
42 from gavo.utils import pyfits
43 from gavo.web import htmltable
44
45
46 _colDefs = {
47 "klein": '<column name="klein" type="smallint">'
48 '<values nullLiteral="-1"/></column>',
49 "prim": '<column name="prim" type="integer" required="true"'
50 ' description="Some random primary key"/><primary>prim</primary>',
51 "nopt": '<column name="nopt" type="real" required="True"/>',
52 "echter": '<column name="echter" type="double precision"/>',
53 "datum": '<column name="datum" type="date"/>',
54 "indf": '<column name="indf" type="text"/><index columns="indf"/>',
55 "uu": '<column name="uu" type="unicode"/>'}
56
57
58 def _getFields(*args):
59 return [_colDefs[a] for a in args]
60
61
62 class ResolutionTest(testhelpers.VerboseTest):
63 def testResolutionUnknownKey(self):
64 self.assertRaisesWithMsg(formats.CannotSerializeIn,
65 "Cannot serialize in 'laberbrasel/td'.",
66 formats.getWriterFor,
67 ("laberbrasel/td",))
68
69 def testResolutionKey(self):
70 self.assertEqual(formats.getWriterFor("tsv"),
71 texttable.renderAsText)
72
73 def testResolutionMimeWithBlanks(self):
74 self.assertEqual(
75 formats.getWriterFor("text/csv; header = present").__name__,
76 "<lambda>")
77
78 def testMimeGetting(self):
79 self.assertEqual(
80 formats.getMIMEFor("votableb2"),
81 "application/x-votable+xml;serialization=BINARY2")
82
83 def testIterFormats(self):
84 labels = list(formats.iterFormats())
85 self.assertTrue("votableb2", labels)
86 self.assertTrue("tsv", labels)
87
88
89 class FITSWriterTest(testhelpers.VerboseTest):
90 def _makeRD(self, colNames, rd=None):
91 return base.parseFromString(rscdesc.RD,
92 """<resource resdir="%s" schema="test">
93 <data id="randomTest">
94 <dictlistGrammar/>
95 <table id="foo">
96 %s
97 </table>
98 <rowmaker id="_foo" idmaps="%s"/>
99 <make table="foo" rowmaker="_foo"/>
100 </data>
101 </resource>
102 """%(os.path.abspath("."), "\n".join(_getFields(*colNames)),
103 ",".join(colNames)))
104
105 _testData = [{"klein": 1, "prim": 2, "nopt": 4.25, "indf": "CEN A"},
106 {"klein": 2, "prim": 7, "nopt": 9.32, "indf":
107 "QSO 3248+33 Component Gamma"}]
108
109 def testMakeSimpleTable(self):
110 """tests for creation of a simple FITS table.
111 """
112 rd = self._makeRD(["klein", "prim", "nopt", "indf"])
113 dataSet = rsc.makeData(rd.getById("randomTest"),
114 forceSource=self._testData)
115 hdulist = fitstable.makeFITSTable(dataSet)
116 self.assertEqual(len(hdulist), 2, "Primary or extension hdu missing")
117 self.assertTrue("DATE" in hdulist[0].header, "No DATE keyword"
118 " in primary header")
119 ft = hdulist[1].data
120 self.assertEqual(ft.field("klein")[0], 1)
121 self.assertEqual(ft.field("prim")[1], 7)
122 self.assertEqual(ft.field("nopt")[0], 4.25)
123 self.assertEqual(ft.field("indf")[1], "QSO 3248+33 Component Gamma")
124 self.assertEqual(len(hdulist[1].columns), 4)
125 self.assertEqual(hdulist[1].columns[3].format, "27A")
126
127 def testMakeDoubleTable(self):
128 """tests for creation of a two-extension FITS table.
129 """
130 rd = self._makeRD(("klein", "prim", "nopt", "indf"))
131 rec2 = base.parseFromString(rscdef.TableDef,
132 '<table id="part2">%s</table>'%"".join(_getFields("prim", "nopt")))
133 dd = rd.getById("randomTest")
134 dd.tables.append(rec2)
135 dd.makes.append(base.makeStruct(rscdef.Make, table=rec2))
136 dd.finishElement()
137 dataSet = rsc.makeData(dd, forceSource=self._testData)
138 hdulist = fitstable.makeFITSTable(dataSet)
139 self.assertEqual(len(hdulist), 3, "Exporting composite data sets"
140 " doesn't catch additional tables")
141
142 def testTableWrite(self):
143 rd = self._makeRD(("klein", "prim", "nopt", "indf"))
144 dataSet = rsc.makeData(rd.getById("randomTest"),
145 forceSource=self._testData)
146 fName = fitstable.makeFITSTableFile(dataSet)
147 self.assertTrue(os.path.exists(fName), "makeFITSTableFile doesn't"
148 " create the file it says it creates")
149 hdulist = pyfits.open(fName)
150 self.assertEqual(len(hdulist), 2, "makeFITSTableFile wrote"
151 " weird file")
152 os.unlink(fName)
153
154 def testSomeNullvalues(self):
155 rd = self._makeRD(("klein", "echter", "indf"))
156 dataSet = rsc.makeData(rd.getById("randomTest"),
157 forceSource=[{"klein": None, "echter": None, "indf": None}])
158 hdulist = fitstable.makeFITSTable(dataSet)
159 resTup = hdulist[1].data[0]
160 self.assertEqual(resTup[0], -1)
161 self.assertFalse(resTup[1]==resTup[1]) # "isNan"
162 self.assertEqual(resTup[2], "")
163
164 def testUnicodishStuff(self):
165 rd = self._makeRD(("indf", "uu"))
166 dataSet = rsc.makeData(rd.getById("randomTest"),
167 forceSource=[{"indf": "Räuber", "uu": "Räuber"},
168 {"uu": "ja"*10, "indf": "ja"*40}])
169 hdulist = fitstable.makeFITSTable(dataSet)
170 resTup = hdulist[1].data[0]
171 self.assertEqual(resTup[0], "R?uber")
172 self.assertEqual(resTup[1], "R?uber")
173 self.assertEqual(hdulist[1].columns[0].format, "80A")
174 # the following should probably grow once we support some sort
175 # of unicode in fits binary tables.
176 self.assertEqual(hdulist[1].columns[1].format, "20A")
177
178
179 class _TestDataTable(testhelpers.TestResource):
180 """A fairly random table with mildly challenging data.
181 """
182 def make(self, deps):
183 dd = testhelpers.getTestRD().getById("tableMaker")
184 data = rsc.makeData(dd, forceSource=[
185 (1, -2, 3, "Wäre es da nicht besser,\n die Regierung setzte das Volk"
186 " ab\tund wählte ein anderes?", '2004-05-05',
187 {'json': -1},
188 pgsphere.SPoint.fromDegrees(124, -30),
189 pgsphere.SMoc.fromASCII("4/23 7/4523-5643")),
190 (None, None, None, None, None, None, None, None)])
191 return data
192
193 _testDataTable = _TestDataTable()
194
195
196 class _FormattedData(testhelpers.TestResource):
197 """_testDataTable after being pushed through formats.getFormatted.
198
199 If textify is true, the result will be utf-8 decoded and returned
200 as a string so it's nicer to write tests.
201 """
202 resources = [("data", _testDataTable)]
203
204 def __init__(self, destFormat, debug=False, textify=True):
205 self.destFormat = destFormat
206 self.debug = debug
207 self.textify = textify
208 testhelpers.TestResource.__init__(self)
209
210 def make(self, dependencies):
211 with warnings.catch_warnings():
212 warnings.simplefilter("ignore")
213 output = formats.getFormatted(self.destFormat, dependencies["data"])
214 if self.debug:
215 with open("generated.dat", "wb") as f:
216 f.write(output)
217 if self.textify:
218 return output.decode("utf-8")
219 else:
220 return output
221
222
223 class _FormattedAndParsedData(testhelpers.TestResource):
224 """_testDataTable serialised and deserialized again through loads.
225
226 What's coming back is (result-string, result-data).
227 """
228 resources = [("data", _testDataTable)]
229
230 def __init__(self, destFormat, loads, debug=False, textify=True):
231 self.destFormat = destFormat
232 self.debug = debug
233 self.loads = loads
234 self.textify = textify
235 testhelpers.TestResource.__init__(self)
236
237 def make(self, dependencies):
238 data = _FormattedData(self.destFormat, self.debug, textify=False
239 ).make(dependencies)
240 parsed = self.loads(data)
241 if self.textify:
242 data = data.decode("utf-8")
243 return data, parsed
244
245
246 class _JSONTable(testhelpers.TestResource):
247 """A table that went through JSON serialisation.
248
249 The resource is (json-text, decoded-json).
250 """
251 resources = [("data", _testDataTable)]
252
253 def make(self, deps):
254 jsText = formats.getFormatted("json", deps["data"])
255 decoded = json.loads(jsText)
256 return jsText, decoded
257
258
259 class JSONOutputTest(testhelpers.VerboseTest):
260 resources = [("tAndD", _FormattedAndParsedData('json', json.loads))]
261
262 def testColumns(self):
263 c1, c2, c3, c4, c5, c6, c7, c8 = self.tAndD[1]["columns"]
264 self.assertEqual(c1["datatype"], "int")
265 self.assertEqual(c2["name"], "afloat")
266 self.assertEqual(c3["arraysize"], None)
267 self.assertEqual(c4["description"], 'Just by a \xb5.')
268 self.assertEqual(c5["datatype"], "double")
269 self.assertEqual(c6["datatype"], "char")
270 self.assertEqual(c6["xtype"], "json")
271 self.assertEqual(c7["datatype"], "double")
272 self.assertEqual(c7["xtype"], "point")
273 self.assertEqual(c8["datatype"], "char")
274 self.assertEqual(c8["xtype"], "moc")
275
276 def testContains(self):
277 self.assertEqual(self.tAndD[1]["contains"], "table")
278
279 def testData(self):
280 self.assertEqual(self.tAndD[1]["data"], [
281 [1, -2.0, 3.0, 'W\xe4re es da nicht besser,\n'
282 ' die Regierung setzte das Volk ab\tund w\xe4hlte ein anderes?',
283 2453130.5, '{"json": -1}',
284 list(pgsphere.SPoint.fromDegrees(124., -30.).asDALI()),
285 '4/23 7/4523-5643'],
286 [None, None, None, None, None, None, None, None]])
287
288 def testParameterDescription(self):
289 intPar = self.tAndD[1]["params"]["intPar"]
290 self.assertEqual(intPar["value"], 42)
291 self.assertEqual(intPar["description"], "test integer parameter")
292
293 def testParameterMetadata(self):
294 floatPar = self.tAndD[1]["params"]["exactFloatPar"]
295 self.assertEqual(floatPar["value"], 0.25)
296 self.assertEqual(floatPar["unit"], "m")
297 self.assertEqual(floatPar["ucd"], "phys.width")
298
299 def testMetaInfo(self):
300 dd = testhelpers.getTestRD().getById("tableMaker")
301 data = rsc.makeData(dd, forceSource=[
302 (1, 2, 3, "ei", '2004-05-05')])
303 table = data.getPrimaryTable()
304 table.addMeta("_warning", "Warning 1")
305 table.addMeta("_warning", "Warning 2")
306 table.addMeta("_queryStatus", "OK")
307 afterRoundtrip = json.loads(
308 formats.getFormatted("json", data))
309 self.assertEqual(afterRoundtrip["warnings"],
310 ["Warning 1", "Warning 2"])
311 self.assertEqual(afterRoundtrip["queryStatus"],
312 "OK")
313
314
315 class FormatOutputTest(testhelpers.VerboseTest):
316 """a base class for tests against formatted output.
317 """
318 # extra pain to allow both _FormattedData and _FormattedAndPartData
319 # in output, plus unwrapping stuff wrapped by testhelpers.
320 def _getOutput(self):
321 output = getattr(self.output, "original", self.output)
322 if isinstance(output, tuple):
323 # it's a tuple wrapped by testresources
324 return output[0]
325 else:
326 return output
327
328 def assertOutputHas(self, fragment):
329 try:
330 self.assertTrue(fragment in self._getOutput(),
331 "'%s' not found in output"%utils.debytify(fragment))
332 except AssertionError:
333 with open("generated.dat", "wb") as f:
334 f.write(utils.bytify(self._getOutput()))
335 raise
336
337 def assertOutputHasNot(self, fragment):
338 self.assertFalse(fragment in self._getOutput(),
339 "Forbidded string '%s' found in output"%fragment)
340
341
342 class TextOutputTest(FormatOutputTest):
343 resources = [("output", _FormattedData("txt", debug=False))]
344
345 def testNullSerialization(self):
346 self.assertEqual(self.output.split('\n')[1],
347 'N/A N/A N/A N/A N/A N/A N/A N/A')
348
349 def testValues(self):
350 self.assertEqual(self.output.split("\n")[0],
351 ' 1 -2.0 3.0 Wäre es da nicht besser,\\n die Regierung setzte das Volk ab\\tund wählte ein anderes? 2453130.5 {"json": -1} [124.0 -29.999999999999996] 4/23 7/4523-5643')
352
353
354 class TSVColumnsOutputTest(FormatOutputTest):
355 resources = [("output", _FormattedData("tsv"))]
356
357 def testNullSerialization(self):
358 self.assertEqual(self.output.split('\n')[1],
359 'N/A\tN/A\tN/A\tN/A\tN/A\tN/A\tN/A\tN/A')
360
361 def testValues(self):
362 self.assertEqual(self.output.split("\n")[0],
363 "1\t-2.0\t3.0\tWäre es da nicht besser,\\n die Regierung setzte"
364 " das Volk ab\\tund wählte ein anderes?\t2453130.5"
365 '\t{"json": -1}'
366 "\t[124.0 -29.999999999999996]"
367 "\t4/23 7/4523-5643")
368
369 def testBytea(self):
370 td = base.parseFromString(rscdef.TableDef,
371 '<table><column name="x" type="bytea"/></table>')
372 t = rsc.TableForDef(td, rows=[{"x": None}, {"x": b"\0\0\t"},
373 {"x": "\0\0\t"}])
374 self.assertEqual(
375 formats.getFormatted("tsv", t),
376 b'N/A\n\\x00\\x00\\t\n\\x00\\x00\\t\n')
377
378
379 class CSVOutputTest(FormatOutputTest):
380 resources = [("output", _FormattedData("text/csv"))]
381
382 def testNumerics(self):
383 self.assertTrue(self.output.startswith('1,-2.0,3.0,'))
384
385 def testStringDefusion(self):
386 self.assertOutputHas(',"Wäre es da nicht'
387 ' besser,\\n die Regierung setzte das Volk ab\\tund wählte'
388 ' ein anderes?",')
389
390 def testNULLs(self):
391 self.assertEqual(self.output.split("\r\n")[1], ',,,,,,,')
392
393 def testWeirdTypes(self):
394 self.assertOutputHas('2453130.5,"{""json"": -1}","(124.0, -29.999999999999996)"')
395
396
397 class CSVHeaderOutputTest(FormatOutputTest):
398 resources = [("output", _FormattedData("text/csv; header=present", False))]
399
400 def testWeirdTypes(self):
401 self.assertOutputHas("(124.0, -29.999999999999996)")
402
403 def testParamCommentWritten(self):
404 self.assertOutputHas('# intPar = 42 // test integer parameter')
405
406 def testParamStringValueUsed(self):
407 self.assertOutputHas('# roughFloatPar = 0.3 // \r\n')
408
409 def testNullParamNotWritten(self):
410 self.assertOutputHasNot('stringPar')
411
412 def testHeaderPresent(self):
413 self.assertEqual(self.output.split("\r\n")[3],
414 "anint,afloat,adouble,atext,adate,somejson,apos,amoc")
415
416
417 class DefaultVOTableOutputTest(FormatOutputTest):
418 resources = [("output", _FormattedData("votable", False))]
419
420 def testTableDescriptionPickedUp(self):
421 self.assertOutputHas('<DESCRIPTION>Some test data with a reason')
422
423 def testUnicodeDeclared(self):
424 self.assertOutputHas('datatype="unicodeChar"')
425
426 def testEncodingInDescription(self):
427 self.assertOutputHas('Just by a \xb5')
428
429 def testDataEncoded(self):
430 self.assertOutputHas(
431 '<STREAM encoding="base64">AAAAAcAAAABACAAAAAAAAAAAAF')
432
433 def testParam(self):
434 self.assertOutputHas("<PARAM")
435 self.assertOutputHas('name="roughFloatPar"')
436 self.assertOutputHas('value="0.3"')
437 self.assertOutputHas(' ucd="phys.width"')
438
439
440 class TDVOTableOutputTest(DefaultVOTableOutputTest):
441 resources = [("output", _FormattedData("votabletd", False))]
442
443 def testDataEncoded(self):
444 self.assertOutputHas("<DATA><TABLEDATA>")
445 self.assertOutputHas("<TD>Wäre es da nicht besser,")
446
447 def testNullSerialization(self):
448 self.assertOutputHas("<TR><TD>-8888</TD><TD>NaN</TD><TD>NaN</TD>"
449 "<TD></TD><TD>NaN</TD><TD></TD><TD></TD><TD></TD></TR>")
450 self.assertOutputHas('null="-8888"')
451
452
453 class B2VOTableOutputTest(DefaultVOTableOutputTest):
454 resources = [("output", _FormattedAndParsedData(
455 "votableb2", votable.loads))]
456
457 def testDataEncoded(self):
458 self.assertOutputHas("<DATA><BINARY2>")
459 self.assertOutputHas('<STREAM encoding="base64">AAAAAAHAAAAAQAg'
460 'AAAAAAAAAAABSAFcA5AByAGUA')
461
462 def testNULLsDecoded(self):
463 data, metadata = self.output[1]
464 self.assertEqual(data[1], [None, None, None, None, None, None, None, None])
465
466 def testGeometry(self):
467 # XXX TODO: actually parse this
468 data, metadata = self.output[1]
469 self.assertEqual(data[0][6], pgsphere.SPoint.fromDegrees(124., -30.))
470
471 def testRegionDeclared(self):
472 data, metadata = self.output[1]
473 self.assertEqual(metadata[6].xtype, "point")
474
475
476 class V11VOTableOutputTest(DefaultVOTableOutputTest):
477 resources = [("output", _FormattedData("votabletd1.1"))]
478
479 def testDataEncoded(self):
480 self.assertOutputHas("<DATA><TABLEDATA>")
481 self.assertOutputHas("<TD>Wäre es da nicht besser,")
482
483 def testNamespace(self):
484 self.assertOutputHas('version="1.1"')
485 self.assertOutputHas('xmlns="http://www.ivoa.net/xml/VOTable/v1.1"')
486
487 def testXtypeSwallowed(self):
488 self.assertFalse("xtype" in self.output)
489
490
491 class FITSOutputTest(FormatOutputTest):
492 resources = [("output", _FormattedData("fits", debug=False, textify=False))]
493
494 def testIsFITS(self):
495 self.assertOutputHas(b'SIMPLE = T')
496
497 def testBintablePresent(self):
498 self.assertOutputHas(b"XTENSION= 'BINTABLE'")
499
500 def testColumnMapping(self):
501 self.assertOutputHas(b"TTYPE2 = 'afloat '")
502 self.assertOutputHas(b"TTYPE3 = 'adouble '")
503 self.assertOutputHas(b"TFORM3 = 'D '")
504
505 def testDescriptionPresent(self):
506 self.assertOutputHas(b"TCOMM3 = 'This is a complex beast so it needs"
507 b" a description that requires &' CONTINUE 'continuatio= n cards "
508 b"in FITS binary tables.'")
509
510 def testSimplePar(self):
511 self.assertOutputHas(
512 b"INTPAR = 42 / test integer parameter")
513
514 def testHierarchPar(self):
515 self.assertOutputHas(
516 b"HIERARCH exactFloatPar = 0.25 / This can be exactly represented"
517 b" in two's complemEND")
518
519 def testDataEncoded(self):
520 self.assertOutputHas(b"W?re es da nic")
521 self.assertOutputHas(b'\x00\x00\x00\x01')
522 self.assertOutputHas(b'@\x00\x00\x00{"json": -1}')
523
524 def testNULLsEncoded(self):
525 reclen = (4+4+8+82 # short, float, double, text
526 + 8 # date as a double (because of unit="d")
527 + 12 # len(json)
528 + 8 + 8 # position as double[2]
529 + 16 # len(moc)
530 )
531 offset = 2880*3 # skip two headers
532 self.assertEqual(self.output[offset+reclen:offset+2*reclen],
533 b"\xff\xff\xdd\x48" # null int
534 b"\x7f\xc0\x00\x00" # NaN float
535 b"\x7f\xf8\x00\x00\x00\x00\x00\x00" # NaN double
536 +b"\x00"*82 # text
537 +b"\x7f\xf8\x00\x00\x00\x00\x00\x00" # NaN double from date
538 +b"\x00"*12 # json
539 +b"\x7f\xf8\x00\x00\x00\x00\x00\x00\x7f\xf8\x00\x00\x00\x00\x00\x00"
540 +b"\x00"*16 # moc
541 )
542
543 def testCharWithNull(self):
544 td = base.parseFromString(rscdef.TableDef, """<table id="t">
545 <column name="c" type="char"><values nullLiteral="."/>
546 </column></table>""")
547 rendered = formats.getFormatted("fits",
548 rsc.TableForDef(td, rows=[{"c": None}, {"c": "x"}]))
549 self.assertTrue(b"XTENSION= 'BINTABLE" in rendered,
550 "Not a bintable?")
551 self.assertTrue(b"\0x\0\0\0" in rendered,
552 "Char NULLs not serialised?")
553
554
555
556 def _getHTMLTree(columns, rows):
557 td = base.parseFromString(rscdef.TableDef, """<table id="t">
558 %s</table>"""%columns)
559 t = rsc.TableForDef(td, rows=rows)
560 rendered = formats.getFormatted("html", t)
561 return testhelpers.getXMLTree(rendered)
562
563
564 class HTMLOutputTest(FormatOutputTest):
565 resources = [("output", _FormattedData("html"))]
566
567 def testTableDeclared(self):
568 self.assertOutputHas('<table class="results">')
569
570 def testMetadataWritten(self):
571 self.assertOutputHas('Real</th><th ')
572
573 def testNormalData(self):
574 self.assertOutputHas(
575 '<tr class="data"><td>1</td><td>-2.0</td><td>3.0</td><td>')
576 self.assertOutputHas('Wäre es da nicht besser,')
577 self.assertOutputHas('wählte ein anderes?</td><td>2453130.5')
578
579 def testNULLs(self):
580 self.assertOutputHas('<td>N/A</td><td>N/A</td>')
581
582 def testCheckmarks(self):
583 tree = _getHTMLTree(
584 '<column name="t" type="integer" displayHint="type=checkmark"/>',
585 [{"t": 1}, {"t":0}, {"t":None}])
586 self.assertEqual(
587 [t.text for t in tree.xpath("//td")],
588 ['✓', None, None])
589
590 def testImageURL(self):
591 tree = _getHTMLTree(
592 '<column name="t" type="text" displayHint="type=imageURL,width=20"/>',
593 [{"t": "http://foo"}, {"t":None}])
594 fields = tree.xpath("//td")
595 img = fields[0][0]
596 self.assertEqual(img.text, None)
597 self.assertEqual(img.get("alt"), "Image at http://foo")
598 self.assertEqual(img.get("width"), "20")
599 self.assertEqual(img.get("src"), "http://foo")
600 self.assertEqual(len(fields[1]), 0)
601
602 def testNullHandledMisc(self):
603 tree = _getHTMLTree(
604 '<column name="h" type="text" displayHint="type=keephtml"/>'
605 '<column name="s" type="text" displayHint="type=simbadlink"/>'
606 '<column name="b" type="text" displayHint="type=bar"/>',
607 [{"h": None, "s": None, "b": None}])
608 self.assertEqual(
609 [etree.tostring(m) for m in tree.xpath("//td")],
610 [b"<td />", b"<td />", b"<td />"])
611
612 def testProductMapperNopreview(self):
613 tree = _getHTMLTree(
614 '<column name="h" type="text" displayHint="type=product,nopreview=T"/>',
615 [{"h": "http://foo/image.fits"}, {"h": "gack/image.fits"},
616 {"h": None}, {"h": "abc"}])
617 fields = tree.xpath("//td")
618
619 a = fields[0].xpath("a")[0]
620 self.assertEqual(a.get("href"), "http://foo/image.fits")
621 self.assertEqual(a.text, "image.fits")
622
623 prod = fields[1].xpath("a")[0]
624 self.assertEqual(prod.get("class"), "productlink")
625 self.assertEqual(prod.get("href"),
626 "http://localhost:8080/getproduct/gack/image.fits")
627
628 self.assertEqual(len(fields[2]), 0)
629
630 self.assertEqual(fields[3].xpath("a")[0].text, "File")
631
632
633 class FormatDataTest(testhelpers.VerboseTest):
634 resources = [("data", _testDataTable)]
635
636 def testRaising(self):
637 with open("/dev/null", "wb") as dest:
638 self.assertRaises(formats.CannotSerializeIn, formats.formatData,
639 "wabbadubba", self.data, dest)
640
641
642 class _ExplicitNullTestTable(testhelpers.TestResource):
643 """A table having some types with explicit null values and an all-null row.
644 """
645 def make(self, deps):
646 td = base.parseFromString(rscdef.TableDef,
647 """
648 <table id="nulls">
649 <column name="anint" type="integer"><values nullLiteral="-1"/></column>
650 <column name="atext" type="text"><values nullLiteral="xxy"/></column>
651 <column name="fixtx" type="char(7)"><values nullLiteral="xxy"/></column>
652 </table>
653 """)
654 return rsc.TableForDef(td,
655 rows=[dict((col.name, None) for col in td)])
656
657
658 _explicitNullTestTable = _ExplicitNullTestTable()
659
660 class ExplicitNullValueTest(testhelpers.VerboseTest):
661 resources = [("nullsTable", _explicitNullTestTable)]
662
663 def _runTestForFormat(self, formatName, assertion):
664 destF = io.BytesIO()
665 formats.formatData(formatName, self.nullsTable, destF)
666 assertion(destF.getvalue())
667
668 def testHTML(self):
669 def assertion(data):
670 self.assertEqual(
671 re.search(b'<tr class="data">(<td>.*)</tr>', data).group(0),
672 b'<tr class="data"><td>N/A</td><td>N/A</td><td>N/A</td></tr>')
673 self._runTestForFormat("html", assertion)
674
675 def testTDVOTable(self):
676 # there's votabletest exercising this more thoroughly, but while we
677 # are at it...
678 def assertion(data):
679 self.assertTrue(b'<VALUES null="-1"' in data)
680 self.assertTrue(b'<TR><TD>-1</TD><TD></TD><TD></TD></TR>' in data)
681 self._runTestForFormat("votabletd", assertion)
682
683 def testBinVOTable(self):
684 def assertion(data):
685 self.assertTrue(b'<VALUES null="-1"' in data)
686 self.assertTrue(b'<VALUES null="xxy"' in data)
687 decoded = base64.b64decode(re.search(
688 b'(?s)<STREAM encoding="base64">(.*)</STREAM>',
689 data).group(1))
690 self.assertEqual(decoded, b"".join([
691 b'\xff\xff\xff\xff',
692 b'\x00\x00\x00\x03xxy',
693 b'xxy ',]))
694 self._runTestForFormat("votable", assertion)
695
696 def testCSV(self):
697 def assertion(data):
698 self.assertEqual(b",,", data.strip())
699 self._runTestForFormat("text/csv", assertion)
700
701 def testTSV(self):
702 def assertion(data):
703 self.assertEqual(b'N/A\tN/A\tN/A', data.strip())
704 self._runTestForFormat("tsv", assertion)
705
706
707 def _mkr(i, s, d, dd, obl, st):
708 return locals()
709
710
711 HTML_OUTPUT_DEF = """
712 <outputTable id="foo">
713 <outputField name="i" type="integer" required="True" description="Ha!"
714 unit="Msol"/>
715 <outputField name="s" type="text" description="some string &lt;"/>
716 <outputField name="d" type="timestamp" tablehead="date"/>
717 <outputField name="dd" type="timestamp" tablehead="Ja"
718 note="junk"/>
719 <outputField name="obl" type="text">
720 <formatter>
721 if data is None:
722 return None
723 return "&amp;"+data+"&lt;"
724 </formatter>
725 </outputField>
726 <outputField name="st" type="text" wantsRow="True">
727 <formatter>
728 if data["i"] is None:
729 return None
730 return T.a(href=str(2*data["i"]))[str(data["obl"])]
731 </formatter>
732 </outputField>
733 <meta name="note" tag="junk">
734 This column only here for no purpose at all
735 </meta>
736 </outputTable>
737 """
738
739 class _RenderedHTML(testhelpers.TestResource):
740 def make(self, ignored):
741 td = base.parseFromString(outputdef.OutputTableDef, HTML_OUTPUT_DEF)
742 table = rsc.TableForDef(td, rows=[
743 _mkr(1, "Hnä",
744 datetime.datetime(2005, 4, 3, 2, 1),
745 datetime.datetime(2005, 4, 3, 2, 22), "gurke", None),
746 _mkr(None, None, None, None, None, None)])
747 destF = io.BytesIO()
748 formats.formatData("html", table, destF)
749 return destF.getvalue(), testhelpers.getXMLTree(
750 destF.getvalue(), debug=False)
751
752
753 class HTMLRenderTest(testhelpers.VerboseTest):
754 resources = [("rendered", _RenderedHTML())]
755
756 def _assertXpathText(self, xpath, value):
757 els = self.rendered[1].xpath(xpath)
758 self.assertEqual(len(els), 1, "Ambiguous xpath %s"%xpath)
759 self.assertEqual(els[0].text, value)
760
761 def testTitleFallbackOnName(self):
762 self._assertXpathText("table/thead/tr[1]/th[1]", "I")
763
764 def testTitleIsTablehead(self):
765 self._assertXpathText("table/thead/tr[1]/th[4]", "Ja")
766
767 def testDescriptionTitleEscaped(self):
768 self.assertEqual(
769 self.rendered[1].xpath("table/thead/tr[1]/th[2]")[0].get("title"),
770 "some string <")
771
772 def testNoteInTitle(self):
773 self._assertXpathText("table/thead/tr[1]/th[4]/sup/a", "junk")
774
775 def testIntRendered(self):
776 self._assertXpathText("table/tbody/tr[1]/td[1]", "1")
777
778 def testIntNull(self):
779 self._assertXpathText("table/tbody/tr[2]/td[1]", "N/A")
780
781 def testUnicodeRendered(self):
782 self._assertXpathText("table/tbody/tr[1]/td[2]",
783 "Hnä")
784
785 def testTextNull(self):
786 self._assertXpathText("table/tbody/tr[2]/td[2]", "N/A")
787
788 def testDefaultDateDisplay(self):
789 self._assertXpathText("table/tbody/tr[1]/td[3]",
790 "2005-04-03T02:01:00")
791
792 def testDateNull(self):
793 self._assertXpathText("table/tbody/tr[2]/td[3]", "N/A")
794
795 def testISODateDisplay(self):
796 self._assertXpathText("table/tbody/tr[1]/td[4]",
797 "2005-04-03T02:22:00")
798
799 def testSingleFormatter(self):
800 self._assertXpathText("table/tbody/tr[1]/td[5]",
801 "&gurke<")
802
803 def testSingleFormatterNull(self):
804 self._assertXpathText("table/tbody/tr[2]/td[5]", "N/A")
805
806 def testRowFormatter(self):
807 self._assertXpathText("table/tbody/tr[1]/td[6]/a",
808 "gurke")
809 anchor = self.rendered[1].xpath("table/tbody/tr[1]/td[6]/a")[0]
810 self.assertEqual(anchor.get("href"), "2")
811
812 def testRowFormatterNull(self):
813 self._assertXpathText("table/tbody/tr[2]/td[6]", "N/A")
814
815 def testFootnotePresent(self):
816 self._assertXpathText("dl/dd/p",
817 "This column only here for no purpose at all")
818 anchor = self.rendered[1].xpath("dl/dt/a")[0]
819 self.assertEqual(anchor.get("name"), "note-junk")
820
821
822 class _RenderedKeyValueHTML(testhelpers.TestResource):
823 def make(self, ignored):
824 td = base.parseFromString(outputdef.OutputTableDef, HTML_OUTPUT_DEF)
825 table = rsc.TableForDef(td, rows=[
826 _mkr(1, "Hnä",
827 datetime.datetime(2005, 4, 3, 2, 1),
828 datetime.datetime(2005, 4, 3, 2, 22), "gurke", None)])
829 frag = htmltable.HTMLKeyValueFragment(table, svcs.emptyQueryMeta)
830 rendered = b"<div>"+formal.flattenSync(frag)+b"</div>"
831 return testhelpers.getXMLTree(rendered, debug=False)
832
833
834 class HTMLKeyValueTest(testhelpers.VerboseTest):
835 resources = [("tree", _RenderedKeyValueHTML())]
836
837 def testValues(self):
838 self.assertEqual(
839 [e.text for e in self.tree.xpath("//td[@class='data']")],
840 ['1', 'Hn\xe4', '2005-04-03T02:01:00',
841 '2005-04-03T02:22:00', '&gurke<', None])
842
843 def testDescriptions(self):
844 self.assertEqual(
845 [e.text for e in self.tree.xpath("//td[@colspan='2']")],
846 ['Ha!', 'some string <', None, None, None, None])
847
848 def testUnitsRendered(self):
849 self.assertEqual(self.tree.xpath("//th/br")[0].tail,
850 "[Msol]")
851
852 def testFootnotesRendered(self):
853 self.assertEqual(self.tree.xpath("dl[dt/a/@name='note-junk']/dd/p")[0].text,
854 "This column only here for no purpose at all")
855
856
857 class GeojsonTest(testhelpers.VerboseTest):
858 def testSepcooAnnotation(self):
859 td = base.parseFromString(rscdef.TableDef, """<table>
860 <dm>
861 (geojson:FeatureCollection){
862 crs: (geojson:CRS) {
863 type: name
864 properties: (geojson:CRSProperties) {
865 name: "urn:private:metric"
866 }
867 }
868 feature: (geojson:Feature) {
869 geometry: (geojson:Geometry) {
870 type: sepcoo
871 latitude: @lat
872 longitude: @long
873 }
874 }
875 }
876 </dm>
877 <column name="lat"/>
878 <column name="long"/>
879 <column name="name" type="text"/>
880 <column name="color" type="text"/>
881 </table>""")
882 table = rsc.TableForDef(td, rows=[
883 {"lat": 1.2, "long": 3.4, "name": "rock1", "color": "red"},
884 {"lat": 2.2, "long": -3.4, "name": "rock2", "color": "blue"},])
885 tx = formats.getFormatted("geojson", table)
886 self.assertEqual(json.loads(tx), {
887 "crs": {"type": "name", "properties": {"name": "urn:private:metric"}},
888 "type": "FeatureCollection",
889 "features": [
890 {"type": "Point", "properties": {"name": "rock1", "color": "red"},
891 "coordinates": [3.4, 1.2]},
892 {"type": "Point", "properties": {"name": "rock2", "color": "blue"},
893 "coordinates": [-3.4, 2.2]}]})
894
895 def testSepArrayAnnotation(self):
896 td = base.parseFromString(rscdef.TableDef, """<table>
897 <dm>
898 (geojson:FeatureCollection){
899 crs: (geojson:CRS) {
900 type: name
901 properties: (geojson:CRSProperties) {
902 name: "urn:private:metric"
903 }
904 }
905 feature: (geojson:Feature) {
906 geometry: (geojson:Geometry) {
907 type: seppoly
908 c1_1: @c1min
909 c2_1: @c2min
910 c1_2: @c1max
911 c2_2: @c2max
912 }
913 }
914 }
915 </dm>
916 <column name="c1min"/>
917 <column name="c1max"/>
918 <column name="c2min"/>
919 <column name="c2max"/>
920 <column name="c3min"/>
921 <column name="c3max"/>
922 <column name="name" type="text"/>
923 <column name="color" type="text"/>
924 </table>""")
925 table = rsc.TableForDef(td, rows=[
926 {"c1min": 2.2, "c1max": 3.4, "c2min": -1, "c2max": 2.2,
927 "c3min": 2003, "c3max": 3004,
928 "name": "rock2", "color": "blue"},])
929 tx = formats.getFormatted("geojson", table)
930 self.assertEqual(json.loads(tx), {
931 'crs': {'type': 'name',
932 'properties': {'name': 'urn:private:metric'}},
933 'type': 'FeatureCollection',
934 'features': [{'type': 'Polygon',
935 'properties': {'color': 'blue', 'c3min': 2003,
936 'c3max': 3004, 'name': 'rock2'},
937 'coordinates': [[2.2, 3.4], [-1, 2.2], [2.2, 3.4]]}]})
938
939 def testSepSimplexAnnotation(self):
940 td = base.parseFromString(rscdef.TableDef, """<table>
941 <dm>
942 (geojson:FeatureCollection){
943 crs: (geojson:CRS) {
944 type: link
945 properties: (geojson:CRSProperties) {
946 href: "http://where.ever/fantasy"
947 type: simple
948 }
949 }
950 feature: (geojson:Feature) {
951 geometry: (geojson:Geometry) {
952 type: sepsimplex
953 c1min: @c1min
954 c2min: @c2min
955 c1max: @c1max
956 c2max: @c2max
957 }
958 }
959 }
960 </dm>
961 <column name="c1min"/>
962 <column name="c1max"/>
963 <column name="c2min"/>
964 <column name="c2max"/>
965 </table>""")
966 table = rsc.TableForDef(td, rows=[
967 {"c1min": 2.2, "c1max": 3.4, "c2min": -1, "c2max": 2.2},])
968 tx = formats.getFormatted("geojson", table)
969 self.assertEqual(json.loads(tx), {
970 'crs': {'type': 'url',
971 'properties': {
972 'href': 'http://where.ever/fantasy',
973 'type': 'simple'}},
974 'type': 'FeatureCollection',
975 'features': [
976 {'type': 'Polygon', 'properties': {},
977 'coordinates': [[2.2, -1], [2.2, 2.2], [3.4, 2.2],
978 [3.4, -1], [2.2, -1]]}]})
979
980 def testGeometryAnnotation(self):
981 td = base.parseFromString(rscdef.TableDef, """<table>
982 <dm>
983 (geojson:FeatureCollection){
984 feature: (geojson:Feature) {
985 geometry: (geojson:Geometry) {
986 type: geometry
987 value: @s_region
988 }
989 }
990 }
991 </dm>
992 <column name="s_region" type="spoly"/>
993 <column name="observed_at" type="timestamp" unit="d"/>
994 <column name="s_point" type="spoint"/>
995 </table>""")
996 table = rsc.TableForDef(td, rows=[{
997 "s_region": pgsphere.SPoly.fromDALI([1.25, 1.0, 3, 9.5, 0.5, 4.25]),
998 "observed_at": datetime.datetime(2017, 2, 7),
999 "s_point": pgsphere.SPoint.fromDegrees(4, 5)
1000 },])
1001 tx = formats.getFormatted("geojson", table)
1002 self.assertEqual(json.loads(tx), {
1003 'features': [{
1004 'coordinates': [[1.25, 1.0], [3.0, 9.5], [0.5, 4.25]],
1005 'properties': {'observed_at': 2457791.5,
1006 's_point': [4., 5.]},
1007 'type': 'Polygon'},],
1008 'type': 'FeatureCollection'})
1009
1010
1011 class ExtensionRecTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
1012 def _runTest(self, sample):
1013 fName, expectedMT = sample
1014 self.assertEqual(
1015 formats.guessMediaType(fName), expectedMT)
1016
1017 samples = [
1018 ("bla.vot", base.votableType),
1019 ("/kvat/hnooik/bla.fits", "application/fits"),
1020 ("http://www.foo.bar/img.ps", "application/postscript"),
1021 ("http://www.foo.bar/map.geojson", "application/geo+json"),
1022 ("http://www.foo.bar/data.json", "application/json"),
1023 ("rund.data.tsv", "text/tab-separated-values"),
1024 ("cat.csv", "text/csv"),
1025 ("cat.vottd", "application/x-votable+xml;serialization=TABLEDATA"),
1026 ("cat.vot6",
1027 "application/x-votable+xml;serialization=TABLEDATA;version=1.6"),
1028 ]
1029
1030
1031 class ExtensionGenTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
1032 def _runTest(self, sample):
1033 mt, ext = sample
1034 self.assertEqual(
1035 ext, formats.getExtensionFor(mt))
1036
1037 samples = [
1038 (base.votableType, ".vot"),
1039 ("application/x-votable+xml; content=datalink", ".vot"),
1040 ("votabletd", ".vottd"),
1041 ("fits", ".fits"),
1042 ("tsv", ".tsv"),
1043 ("text/html", ".html"),
1044 ("text/html;charset=UTF-8", ".html"),
1045 ("text/csv", ".csv"),
1046 ("application/json", ".json"),
1047 ("application/fits", ".fits"),
1048 ("image/fits", ".fits"),
1049 ("image/png", ".png"),
1050 # ("image/jpeg", ".jpeg"), this is not predicatable in mimetypes
1051 ("vnd.gavo/invalid", ".dat"),
1052 ]
1053
1054
1055 if __name__=="__main__":
1056 testhelpers.main(HTMLRenderTest)