Debian Codegraph @

tests/dmtest.py

raw
1 """
2 Tests to do with new-style data modelling and VO-DML serialisation.
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 from gavo.helpers import testhelpers
12
13 from io import StringIO
14 import re
15
16 from gavo import base
17 from gavo import dm
18 from gavo import formats
19 from gavo import rsc
20 from gavo import rscdef
21 from gavo import rscdesc
22 from gavo import svcs
23 from gavo.dm import dmrd
24 from gavo.dm import sil
25 from gavo.helpers import testtricks
26 from gavo.formats import votablewrite
27
28
29 def normalizeSIL(sil):
30 return re.sub(r"\s+", " ", sil).strip()
31
32
33 INLINE_MODEL = """
34 <vo-dml:model xmlns:vo-dml="http://www.ivoa.net/xml/VODML/v1">
35 <name>localinline</name>
36 <title>Local inline DM</title>
37 <version>1.0</version>
38 <lastModified>2016-07-14Z11:17:00</lastModified>
39
40 <objectType>
41 <vodml-id>Polar</vodml-id>
42 <name>Polar</name>
43 <attribute>
44 <vodml-id>Polar.rule</vodml-id>
45 <name>rule</name>
46 <datatype>
47 <vodml-ref>dachstoy:Cooler</vodml-ref>
48 </datatype>
49 </attribute>
50 </objectType>
51 </vo-dml:model>
52 """
53
54
55 class XSDTest(testhelpers.VerboseTest, testtricks.XSDTestMixin):
56 def testCanSchemaValidate(self):
57 with open(base.getPathForDistFile("dm/meas.vo-dml.xml"), "rb") as f:
58 self.assertValidates(f.read())
59
60
61 class _InlineModel(testhelpers.TestResource):
62 def make(self, ignored):
63 return dm.Model.fromFile(StringIO(INLINE_MODEL))
64
65 _inlineModel = _InlineModel()
66
67
68 class ModelTest(testhelpers.VerboseTest):
69 resources = [("inlineModel", _inlineModel)]
70
71 def testMetadataParsing(self):
72 toydm = dm.getModelForPrefix("dachstoy")
73 self.assertEqual(toydm.description,
74 "A toy model for DaCHS regression testing")
75 self.assertEqual(toydm.title, "DaCHS Toy model")
76 self.assertEqual(toydm.version, "1.0a-pl23.44c")
77 self.assertEqual(toydm.uri, "http://docs.g-vo.org/dachstoy")
78
79 def testIdAccess(self):
80 toydm = dm.getModelForPrefix("dachstoy")
81 res = toydm.getByVODMLId("Ruler.width")
82 self.assertEqual(res.find("description").text, "A dimension")
83
84 def testPrefixIgnored(self):
85 toydm = dm.getModelForPrefix("dachstoy")
86 res = toydm.getByVODMLId("dachstoy:Ruler.width")
87 self.assertEqual(res.find("description").text, "A dimension")
88
89 def testNoIdAccess(self):
90 toydm = dm.getModelForPrefix("dachstoy")
91 self.assertRaisesWithMsg(base.NotFoundError,
92 "data model element 'Broken.toy' could not be located"
93 " in dachstoy data model",
94 toydm.getByVODMLId,
95 ("Broken.toy",))
96
97 def testGlobalResolution(self):
98 res = dm.resolveVODMLId("dachstoy:Ruler.width")
99 self.assertEqual(res.find("description").text, "A dimension")
100
101 def testLoadFromFile(self):
102 att = self.inlineModel.getByVODMLId("localinline:Polar.rule")
103 self.assertEqual(att.find("datatype/vodml-ref").text, "dachstoy:Cooler")
104 self.assertEqual(self.inlineModel.prefix, "localinline")
105
106 def testUnknownPrefix(self):
107 # this standin DM behaviour should change to an exception as this matures
108 model = dm.getModelForPrefix("notexisting")
109 self.assertEqual(model.title, "DaCHS standin model")
110 self.assertEqual(model.uri, "urn:dachsjunk:not-model:notexisting")
111
112
113 class AttributeResolutionTest(testhelpers.VerboseTest):
114 maxDiff = None
115
116 def testDirect(self):
117 attDef = dm.getAttributeDefinition("meas:Asymmetrical3D", "minus")
118 self.assertEqual(attDef, {
119 'datatype': 'ivoa:RealQuantity',
120 'description': 'Extent in each negative axis direction.',
121 'vodml-id': 'Asymmetrical3D.minus'})
122
123 def testIndirect(self):
124 attDef = dm.getAttributeDefinition("meas:GenericMeasure", "ucd")
125 self.assertEqual(attDef["datatype"], "ivoa:string")
126 self.assertEqual(attDef["vodml-id"], "Measure.ucd")
127
128 def testComposition(self):
129 attDef = dm.getAttributeDefinition("coords:CoordSpace", "axis")
130 self.assertEqual(attDef, {
131 'vodml-id': 'CoordSpace.axis',
132 'description': 'Describes an axis of the coordinate space.',
133 'datatype': 'coords:Axis'})
134
135
136 class SILGrammarTest(testhelpers.VerboseTest):
137 def testPlainObject(self):
138 res = sil.getGrammar().parseString("""
139 (:testclass) {
140 attr1: plain12-14
141 attr2: "this is a ""weird"" literal"
142 }""")
143 self.assertEqual(res[0],
144 ('obj', ':testclass', [
145 ('attr', 'attr1', 'plain12-14'),
146 ('attr', 'attr2', 'this is a "weird" literal')]))
147
148 def testNestedObject(self):
149 res = sil.getGrammar().parseString("""
150 (:testclass) {
151 attr1: (:otherclass) {
152 attr2: val
153 }
154 }""")
155 self.assertEqual(res[0],
156 ('obj', ':testclass', [
157 ('attr', 'attr1',
158 ('obj', ':otherclass', [
159 ('attr', 'attr2', 'val')]))]))
160
161 def testObjectCollection(self):
162 res = sil.getGrammar().parseString("""
163 (:testclass) {
164 seq: (:otherclass)[
165 {attr1: a}
166 {attr1: b}
167 {attr1: c}]}""")
168 self.assertEqual(res[0],
169 ('obj', ':testclass', [
170 ('attr', 'seq',
171 ('coll', ':otherclass', [
172 ('obj', None, [('attr', 'attr1', 'a')]),
173 ('obj', None, [('attr', 'attr1', 'b')]),
174 ('obj', None, [('attr', 'attr1', 'c')]),]))]))
175
176 def testImmediateCollection(self):
177 res = sil.getGrammar().parseString("""
178 (:testclass) {
179 seq: [a "b c d" @e]}""")
180 self.assertEqual(res[0],
181 ('obj', ':testclass',
182 [('attr', 'seq',
183 ('coll', None, ['a', 'b c d', 'e']))]))
184
185 def testAtomicFallback(self):
186 res = sil.getGrammar().parseString("""
187 (:testclass) {
188 attr1: val | fallback
189 }""")
190 self.assertEqual(res[0],
191 ('obj', ':testclass', [
192 ('attr', 'attr1',
193 ('fallback', 'val', 'fallback'))]))
194
195
196 def testObjectFallback(self):
197 res = sil.getGrammar().parseString("""
198 (:testclass) {
199 attr1: (:otherclass) {
200 attr2: val
201 }
202 | (:stillotherclass) { attr3: noval}
203 }""")
204 self.assertEqual(res[0],
205 ('obj', ':testclass', [
206 ('attr', 'attr1',
207 ('fallback',
208 ('obj', ':otherclass', [
209 ('attr', 'attr2', 'val')]),
210 ('obj', ":stillotherclass", [
211 ('attr', 'attr3', 'noval')])))]))
212
213 def testNullLiteral(self):
214 res = sil.getGrammar().parseString("""
215 (:testclass) {
216 seq: [a __NULL__ @e]
217 val: __NULL__}""")
218 self.assertEqual(res[0],
219 ('obj', ':testclass', [
220 ('attr', 'seq',
221 ('coll', None, ['a', None, 'e'])),
222 ('attr', 'val', None)]))
223
224
225 class SILParserTest(testhelpers.VerboseTest):
226 def testNestedObject(self):
227 res = sil.getAnnotation("""
228 (testdm:testclass) {
229 attr1: (testdm:otherclass) {
230 attr2: val
231 }
232 }""", dmrd.getAnnotationMaker(None))
233 self.assertEqual(normalizeSIL(res.asSIL()),
234 '(testdm:testclass) { (testdm:otherclass) { attr2: val} }')
235
236 def testObjectCollection(self):
237 res = sil.getAnnotation("""
238 (testdm:testclass) {
239 seq: (testdm:otherclass)[
240 {attr1: a}
241 {attr1: b}
242 {attr1: c}]}""", dmrd.getAnnotationMaker(None))
243 self.assertEqual(normalizeSIL(res.asSIL()),
244 '(testdm:testclass) { seq: (testdm:otherclass)'
245 ' [{ attr1: a} { attr1: b} { attr1: c} ] }')
246
247 def testAtomicCollection(self):
248 res = sil.getAnnotation("""
249 (testdm:testclass) {
250 seq: [a "b c" 3.2]}""", dmrd.getAnnotationMaker(None))
251 self.assertEqual(normalizeSIL(res.asSIL()),
252 '(testdm:testclass) { seq: [a "b c" 3.2] }')
253
254 def testComments(self):
255 res = sil.getAnnotation("""/* comment with stuff */
256 (testdm:testclass) /* another comment */ { /* and yet one */
257 seq: [a "b c" 3.2] /* here's an additional comment */}
258 /* final comment */""", dmrd.getAnnotationMaker(None))
259 self.assertEqual(normalizeSIL(res.asSIL()),
260 '(testdm:testclass) { seq: [a "b c" 3.2] }')
261
262 def testNoUntypedRoot(self):
263 self.assertRaisesWithMsg(base.StructureError,
264 "Root of Data Model annotation must have a type.",
265 sil.getAnnotation,
266 ("{attr1: (testdm:otherclass) {attr2: val}}",
267 dmrd.getAnnotationMaker(None)))
268
269 def testWithoutType(self):
270 res = sil.getAnnotation("(testdm:testclass){attr1: {attr2: val}}",
271 dmrd.getAnnotationMaker(None))
272 self.assertEqual(normalizeSIL(res.asSIL()),
273 '(testdm:testclass) { { attr2: val} }')
274
275 def testWithFallback(self):
276 res = sil.getAnnotation("(testdm:testclass){attr1: foo | bar}",
277 dmrd.getAnnotationMaker(None))
278 self.assertEqual(normalizeSIL(res.asSIL()),
279 '(testdm:testclass) { attr1: foo}')
280
281
282 class AnnotationTest(testhelpers.VerboseTest):
283 def testAtomicValue(self):
284 t = base.parseFromString(rscdef.TableDef,
285 """<table id="foo">
286 <dm>
287 (testdm:testclass) {
288 attr1: test
289 }
290 </dm></table>""")
291 self.assertEqual(t.annotations[0].type, "testdm:testclass")
292 self.assertEqual(t.annotations[0].childRoles["attr1"].value,
293 "test")
294 self.assertEqual(t.annotations[0].childRoles["attr1"].instance(),
295 t.annotations[0])
296
297 def testAtomicFallback(self):
298 t = base.parseFromString(rscdef.TableDef,
299 """<table id="foo">
300 <dm>
301 (testdm:testclass) {
302 attr1: @nix | test
303 }
304 </dm>
305 </table>""")
306 self.assertEqual(t.annotations[0].type, "testdm:testclass")
307 self.assertEqual(t.annotations[0].childRoles["attr1"].value,
308 "test")
309 self.assertEqual(t.annotations[0].childRoles["attr1"].instance(),
310 t.annotations[0])
311
312 def testObjectFallback(self):
313 t = base.parseFromString(rscdef.TableDef,
314 """<table id="foo">
315 <dm>
316 (testdm:testclass) {
317 attr1: {
318 bla: @nix
319 }
320 | {
321 kaputt: true
322 }
323 }
324 </dm>
325 </table>""")
326 self.assertEqual(t.annotations[0].type, "testdm:testclass")
327 self.assertEqual(t.annotations[0].childRoles["attr1"]
328 .childRoles["kaputt"].value, "true")
329
330 def testCollectionFallback(self):
331 t = base.parseFromString(rscdef.TableDef,
332 """<table id="foo">
333 <dm>
334 (testdm:testclass) {
335 attr1: [
336 @foo | isnich
337 @nix | fallback
338 ]
339 }
340 </dm>
341 <column name="foo"/>
342 </table>""")
343 self.assertEqual(t.annotations[0].type, "testdm:testclass")
344 self.assertEqual(t.annotations[0].childRoles["attr1"]
345 .children[0].value.name, "foo")
346 self.assertEqual(t.annotations[0].childRoles["attr1"]
347 .children[1].value, "fallback")
348
349 def testColumnReference(self):
350 t = base.parseFromString(rscdef.TableDef,
351 """<table id="foo">
352 <dm>
353 (testdm:testclass) {
354 attr1: @col1
355 }
356 </dm><column name="col1" ucd="stuff"/></table>""")
357 col = t.annotations[0].childRoles["attr1"].value
358 self.assertEqual(col.ucd, "stuff")
359
360 def testNULLAnnotation(self):
361 t = base.parseFromString(rscdef.TableDef,
362 """<table id="foo">
363 <dm>
364 (testdm:testclass) {
365 attr1: __NULL__
366 attr2: red
367 value: @col1
368 }
369 </dm><column name="col1" ucd="stuff"/></table>""")
370 self.assertEqual(t.annotations[0].childRoles["attr2"].value, "red")
371 self.assertFalse("attr1" in t.annotations[0].childRoles)
372
373
374 # Use this table (rather than _RealDMTable) to build tests against
375 # DMs we can control for testing purposes.
376 class _AnnotationTable(testhelpers.TestResource):
377 def make(self, deps):
378 td = base.parseFromString(rscdef.TableDef,
379 """<table id="foo">
380 <dm>
381 (dachstoy:Ruler) {
382 width: @col1
383 location:
384 (dachstoy:Location) {
385 x: 0.1
386 y: @raj2000
387 z: @dej2000
388 }
389 maker: [
390 Oma "Opa Rudolf" @artisan]
391 }
392 </dm>
393 <dm>
394 (geojson:FeatureCollection) {
395 feature: {
396 geometry: sepcoo
397 long: @raj2000
398 lat: @col1
399 }
400 }
401 </dm>
402 <param name="artisan" type="text">Onkel Fritz</param>
403 <column name="col1" ucd="stuff" type="text"/>
404 <column name="raj2000"/>
405 <column name="dej2000"/>
406 </table>""")
407
408 return rsc.TableForDef(td, rows=[
409 {"col1": "1.5", "raj2000": 0.3, "dej2000": 3.1}])
410
411 _ANNOTATION_TABLE = _AnnotationTable()
412
413
414 class _DirectVOT(testhelpers.TestResource):
415 resources = [("table", _ANNOTATION_TABLE)]
416
417 def make(self, deps):
418 return testhelpers.getXMLTree(votablewrite.getAsVOTable(
419 deps["table"],
420 ctx=votablewrite.VOTableContext(version=(1,6))), debug=False)
421
422
423 class DirectSerTest(testhelpers.VerboseTest):
424 resources = [("tree", _DirectVOT())]
425
426 def testTestModelDefined(self):
427 dmgroup = self.tree.xpath(
428 "//VODML/MODEL[@name='dachstoy']")[0]
429 self.assertEqual(
430 dmgroup.get("url"),
431 "http://docs.g-vo.org/dachstoy")
432
433 def testNoExtraModels(self):
434 self.assertEqual(2, # this is missing ivoa: -- do we want it?
435 len(self.tree.xpath("//MODEL")))
436
437 def testTestclassInstancePresent(self):
438 res = self.tree.xpath(
439 "//TEMPLATES/INSTANCE[@dmtype='dachstoy:Ruler']")
440 self.assertEqual(len(res), 1)
441
442 def testLiteralSerialized(self):
443 par = self.tree.xpath(
444 "//INSTANCE[@dmtype='dachstoy:Location']"
445 "/ATTRIBUTE[@dmrole='x']")[0]
446 self.assertEqual(par.get("value"), "0.1")
447 self.assertEqual(par.get("dmtype"), "ivoa:string")
448
449 def testChildColumnAnnotated(self):
450 # NOTE: this is currently the only test that actually checks the correct
451 # location of the VODML container resource.
452 fr = self.tree.xpath(
453 "RESOURCE/RESOURCE[1]/VODML/TEMPLATES/"
454 "INSTANCE[@dmtype='dachstoy:Ruler']"
455 "/ATTRIBUTE[@dmrole='width']/@ref")[0]
456 col = self.tree.getByID(fr)
457 self.assertEqual(col.get("name"), "col1")
458
459 def testNestedColumnAnnotated(self):
460 fr = self.tree.xpath(
461 "//INSTANCE[@dmtype='dachstoy:Location']/ATTRIBUTE[@dmrole='y']/@ref")[0]
462 col = self.tree.getByID(fr)
463 self.assertEqual(col.get("name"), "raj2000")
464
465 def testCollectionLiterals(self):
466 gr = self.tree.xpath(
467 "//INSTANCE/ATTRIBUTE[@dmrole='maker']/COLLECTION")
468 vals = testhelpers.pickSingle(gr).xpath("ATTRIBUTE/@value")
469 self.assertEqual(len(vals), 2)
470 self.assertEqual(vals[0], "Oma")
471 self.assertEqual(vals[1], "Opa Rudolf")
472
473 def testParamReferenced(self):
474 gr = self.tree.xpath(
475 "//TEMPLATES/INSTANCE/ATTRIBUTE[@dmrole='maker']"
476 "/COLLECTION/ATTRIBUTE/@ref")
477 paramref = testhelpers.pickSingle(gr)
478 par = self.tree.getByID(paramref)
479 self.assertEqual(par.get("value"), "Onkel Fritz")
480
481
482 class CopyTest(testhelpers.VerboseTest):
483 resources = [("table", _ANNOTATION_TABLE)]
484
485 def testParamDMRoleLink(self):
486 ann = self.table.tableDef.getByName("artisan").dmRoles[0]()
487 self.assertEqual(ann.name, "maker")
488
489 def testColumnDMRoleLink(self):
490 ann = self.table.tableDef.getByName("raj2000").dmRoles[0]()
491 self.assertEqual(ann.name, "y")
492
493 def testDMRolesCopying(self):
494 col = self.table.tableDef.getByName("raj2000")
495 colCopy = col.copy(None)
496 self.assertEqual(colCopy.dmRoles.__class__.__name__,
497 "OldRoles")
498
499 def testSimpleCopy(self):
500 newTD = self.table.tableDef.copy(None)
501 ann = next(newTD.iterAnnotationsOfType("dachstoy:Ruler"))
502 self.assertEqual(ann["maker"][0], "Oma")
503 self.assertEqual(ann["maker"][2].value, newTD.getByName("artisan"))
504 self.assertEqual(ann["width"].value, newTD.getByName("col1"))
505 self.assertEqual(ann["location"]["x"], "0.1")
506 self.assertEqual(ann["location"]["y"].value,
507 newTD.getByName("raj2000"))
508
509 ann = next(newTD.iterAnnotationsOfType("geojson:FeatureCollection"))
510 self.assertEqual(ann["feature"]["geometry"], "sepcoo")
511 self.assertEqual(ann["feature"]["long"].value,
512 newTD.getByName("raj2000"))
513
514 def testPartialCopy(self):
515 newTD = self.table.tableDef.change(id="copy", columns=[
516 self.table.tableDef.getByName("dej2000").copy(None)],
517 params=[])
518 ann = next(newTD.iterAnnotationsOfType("dachstoy:Ruler"))
519 self.assertEqual(ann["maker"][0], "Oma")
520 self.assertEqual(len(ann["maker"]), 2)
521 self.assertEqual(ann["location"]["z"].value,
522 newTD.getByName("dej2000"))
523 self.assertFalse("y" in ann["location"])
524 # the following assertion states that annotations without any
525 # columns/params referenced are not copied into the destination
526 # table.
527 self.assertEqual(len(newTD.annotations), 1)
528
529 def testOutputTableConstruction(self):
530 newTD = base.makeStruct(svcs.OutputTableDef,
531 columns=[
532 self.table.tableDef.getByName("raj2000"),
533 self.table.tableDef.getByName("dej2000")],
534 params=[
535 self.table.tableDef.getByName("artisan")])
536 ann = next(newTD.iterAnnotationsOfType("dachstoy:Ruler"))
537 self.assertEqual(ann["maker"][0], "Oma")
538 self.assertEqual(ann["location"]["z"].value,
539 newTD.getByName("dej2000"))
540 self.assertEqual(len(ann["maker"]), 3)
541
542 ann = next(newTD.iterAnnotationsOfType("geojson:FeatureCollection"))
543 self.assertEqual(ann["feature"]["geometry"], "sepcoo")
544 self.assertEqual(ann["feature"]["long"].value,
545 newTD.getByName("raj2000"))
546
547
548 # When you're looking for a table to pollute with custom
549 # constructs, use _AnnotationTable.
550 class _RealDMTable(testhelpers.TestResource):
551 # well, of course, these are not the real DMs at this point.
552 # as the come out, they should go in here, and this should
553 # be used to test validation.
554 def make(self, deps):
555 rd = base.parseFromString(rscdesc.RD,
556 # this needs a resource container since we need id resolution
557 """
558 <resource schema="test">
559 <table id="foo">
560 <dm>
561 (ds:DataSet) {
562 ProductType: timeseries
563 calibLevel: 1
564 dataId: @pubDID
565 creator: [
566 "Joe Cool"
567 "Charlie Brown"
568 ]
569 observationID: @pubDID
570 target: {
571 name: @targetName
572 position: @targetPos
573 }
574 }
575 </dm>
576
577 <dm id="targetPos">
578 (votable:Coordinates) {
579 spatial: {
580 frame: {
581 referenceSystem: ICRS
582 }
583 c1: @raj2000
584 c2: @dej2000
585 }
586 temporal: {
587 frame: {
588 timeScale: TT
589 referencePosition: HELIOCENTER
590 }
591 value: @HJD
592 }
593 }
594 </dm>
595
596 <param name="raj2000" type="double precision"
597 ucd="pos.eq.ra" unit="deg"/>
598 <param name="dej2000" type="double precision"
599 ucd="pos.eq.dec" unit="deg"/>
600 <param name="targetName" type="text"/>
601 <param name="pubDID" type="text"/>
602
603 <column name="HJD" type="double precision"/>
604
605 </table>
606 </resource>""")
607
608 t = rsc.TableForDef(rd.tables[0], rows=[
609 {"HJD": 2000000.125}])
610 t.setParam("raj2000", 230)
611 t.setParam("dej2000", -45)
612 return t
613
614 _REAL_DM_TABLE = _RealDMTable()
615
616
617 class _RealDMVOT(testhelpers.TestResource):
618 resources = [("table", _REAL_DM_TABLE)]
619
620 def make(self, deps):
621 return testhelpers.getXMLTree(votablewrite.getAsVOTable(
622 deps["table"],
623 ctx=votablewrite.VOTableContext(version=(1,6))), debug=False)
624
625 _REAL_DM_VOT = _RealDMVOT()
626
627
628 class ObjReftest(testhelpers.VerboseTest):
629 resources = [("table", _REAL_DM_TABLE),
630 ("serialized", _REAL_DM_VOT)]
631
632 def testInterInstanceAnnotation(self):
633 ds = next(self.table.tableDef.iterAnnotationsOfType("ds:DataSet"))
634 pos = ds["target"]["position"].objectReferenced
635 self.assertEqual(pos["spatial"]["frame"]["referenceSystem"],
636 "ICRS")
637 self.assertEqual(pos["spatial"]["c1"].value.name, "raj2000")
638
639 def testInstanceRefSerialisation(self):
640 groupref = self.serialized.xpath(
641 "//INSTANCE[@dmtype='ds:DataSet']/ATTRIBUTE[@dmrole='target']"
642 "/INSTANCE/ATTRIBUTE[@dmrole='position']/REFERENCE")[0]
643 pos = self.serialized.xpath("//*[@ID='{}']".format(
644 groupref.get("dmref")))[0]
645 self.assertEqual(pos.get("dmtype"), "votable:Coordinates")
646
647 self.assertEqual(pos.xpath("ATTRIBUTE[@dmrole='temporal']"
648 "/INSTANCE/ATTRIBUTE[@dmrole='frame']/INSTANCE"
649 "/ATTRIBUTE[@dmrole='referencePosition']/@value")[0],
650 "HELIOCENTER")
651
652
653 class VOTWithPhotcals(testhelpers.TestResource):
654 def make(self, deps):
655 rd = base.parseFromString(rscdesc.RD,
656 """
657 <resource schema="test">
658 <table id="foo">
659 <dm>
660 (phot:PhotCal) {
661 filterIdentifier: "2MASS/Ks"
662 zeroPointFlux: 1e-11
663 magnitudeSystem: Vega
664 effectiveWavelength: 2.2e-6
665 value: @kmag
666 }
667 </dm>
668
669 <dm>
670 (phot:PhotCal) {
671 filterIdentifier: "Johnson/V"
672 effectiveWavelength: 6.2e-7
673 value: @vmag
674 }
675 </dm>
676
677 <column name="kmag" ucd="phot.mag;em.IR"/>
678 <column name="vmag" ucd="phot.mag;em.opt"/>
679 </table>
680 </resource>""")
681
682 t = rsc.TableForDef(rd.tables[0], rows=[
683 {"kmag": 10.3, "vmag": 8.1}])
684 res = formats.getFormatted("vodml", t)
685 return res, testhelpers.getXMLTree(res, debug=False)
686
687
688 class PhotcalTest(testhelpers.VerboseTest):
689 # this is for Ada's temporary PHOTCAL group hack from
690 # http://ivoa.net/documents/Notes/LightCurveTimeSeries//index.html
691
692 resources = [("l_t", VOTWithPhotcals())]
693
694 def testVODMLPresent(self):
695 tree = self.l_t[1]
696 kmagGroup = tree.xpath("//INSTANCE[@dmtype='phot:PhotCal'"
697 "and ATTRIBUTE[@dmrole='value']/@ref='kmag']")[0]
698 self.assertEqual(
699 kmagGroup.xpath("ATTRIBUTE[@dmrole='filterIdentifier']/@value")[0],
700 "2MASS/Ks")
701 self.assertEqual(
702 kmagGroup.xpath("ATTRIBUTE[@dmrole='zeroPointFlux']/@value")[0],
703 "1e-11")
704 self.assertEqual(
705 kmagGroup.xpath("ATTRIBUTE[@dmrole='magnitudeSystem']/@value")[0],
706 "Vega")
707 self.assertEqual(
708 kmagGroup.xpath("ATTRIBUTE[@dmrole='effectiveWavelength']/@value")[0],
709 "2.2e-6")
710
711 vmagGroup = tree.xpath("//INSTANCE[@dmtype='phot:PhotCal'"
712 "and ATTRIBUTE[@dmrole='value']/@ref='vmag']")[0]
713 self.assertEqual(
714 vmagGroup.xpath("ATTRIBUTE[@dmrole='filterIdentifier']/@value")[0],
715 "Johnson/V")
716
717 def testPhotcalGroupsPresent(self):
718 self.assertEqual(
719 ["phot_def", "phot_def-02"],
720 [n.get("ID") for n in self.l_t[1].xpath("//GROUP[@name='photcal']")])
721
722 def testAllParamsSerialised(self):
723 self.assertEqual(
724 len(self.l_t[1].xpath(
725 "RESOURCE/GROUP[@ID='phot_def']/PARAM")),
726 4)
727
728 def testColumnReferencing(self):
729 tree = self.l_t[1]
730 references = tree.xpath(
731 "RESOURCE/GROUP/FIELDref/@ref")
732
733 col = tree.getByID(references[0])
734 self.assertEqual(col.get("ucd"), "phot.mag;em.IR")
735
736 col = tree.getByID(references[1])
737 self.assertEqual(col.get("ucd"), "phot.mag;em.opt")
738
739 def testFloatSerialization(self):
740 self.assertEqual(
741 self.l_t[1].xpath("//PARAM[@name='effectiveWavelength']/@value"),
742 ["2.2e-6", "6.2e-7"])
743
744 def testStupidBackReferences(self):
745 self.assertEqual(
746 self.l_t[1].xpath("//FIELD/@ref"),
747 ["phot_def", "phot_def-02"])
748
749
750 if __name__=="__main__":
751 testhelpers.main(DirectSerTest)