Debian Codegraph @

tests/rowmakertest.py

raw
1 """
2 Tests for the various structures in rscdef.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import datetime
12 import os
13
14 import numpy
15
16 from gavo.helpers import testhelpers
17
18 from gavo import base
19 from gavo import rsc
20 from gavo import rscdef
21 from gavo import rscdesc #noflake: for registration
22 from gavo import utils
23 from gavo.utils import DEG
24
25
26 def makeDD(tableCode, rowmakerCode, grammar="<dictlistGrammar/>",
27 moreMakeStuff="", parentRD=None):
28 dd = base.parseFromString(rscdef.DataDescriptor,
29 '<data><table id="foo">%s</table>'
30 '<make table="foo">'
31 ' <rowmaker id="_foo">%s</rowmaker>'
32 ' %s'
33 '</make>'
34 '%s'
35 '</data>'%(
36 tableCode, rowmakerCode, moreMakeStuff, grammar))
37 if parentRD:
38 dd.parent = parentRD
39 td = dd.getTableDefById("foo")
40 return dd, td
41
42
43 class RowmakerDefTest(testhelpers.VerboseTest):
44 """tests for some aspects of creation of rowmaker definitions.
45 """
46 def testBasic(self):
47 makeDD('<column name="x"/>', '<map dest="x">a+b</map>')
48 map = base.parseFromString(rscdef.MapRule,'<map dest="bar"/>')
49 self.assertEqual(map.source, "bar")
50
51 def testNoDestRaises(self):
52 self.assertRaisesWithMsg(base.StructureError,
53 "At IO:'<map>bar</map>', (1, 8):"
54 " You must set key on map elements",
55 base.parseFromString, (rscdef.MapRule, '<map>bar</map>'))
56
57 def testStatementRaises(self):
58 self.assertRaisesWithMsg(base.BadCode,
59 'At IO:\'<data><table id="foo"><column name="x"/></table><make...\', (1, 108):'
60 " Bad source code in expression (Not an expression)",
61 makeDD, ('<column name="x"/>',
62 '<map dest="x">c = a+b</map>'))
63
64 def testBadSourceRaises(self):
65 self.assertRaisesWithMsg(base.BadCode,
66 'At IO:\'<data><table id="foo"><column name="x"/></table><make...\', (1, 102):'
67 " Bad source code in expression (invalid syntax (<unknown>, line 1))",
68 makeDD, ('<column name="x"/>', '<map dest="x">-</map>'))
69
70 def testPleonasticRaises(self):
71 self.assertRaisesWithMsg(base.StructureError,
72 'At IO:\'<map dest="bar" src="foo">bar</map>\', (1, 29):'
73 ' Map must have exactly one of source attribute or element content',
74 base.parseFromString,
75 (rscdef.MapRule,'<map dest="bar" src="foo">bar</map>'))
76
77
78 class RowmakerMapTest(testhelpers.VerboseTest):
79 """tests for mapping of values during parsing.
80 """
81 def testBasicCode(self):
82 dd, td = makeDD('<column name="x" type="integer" required="True"/>',
83 '<map dest="x">int(vars["src"])</map>')
84 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
85 self.assertEqual(mapper({'src': '15'}, None)['x'], 15)
86
87 def testBasicMap(self):
88 dd, td = makeDD('<column name="x" type="integer" required="True"/>',
89 '<map dest="x" src="src"/>')
90 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
91 self.assertEqual(mapper({'src': '15'}, None)['x'], 15)
92
93 def testWithDefault(self):
94 dd, td = makeDD('<column name="x" type="integer" required="True"'
95 '><values default="18"/></column>', '<map dest="x">int(@x)</map>')
96 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
97 self.assertEqual(mapper({}, None)['x'], 18)
98
99 def testMultilineExpressions(self):
100 dd, td = makeDD('<column name="x" type="integer" required="True"/>'
101 '<column name="y" type="text"/>',
102 '<map dest="y">("foobar"+\n'
103 '@src.decode("utf-8"))\n</map>'
104 '<map dest="x">int(\[email protected]("utf-8")\n)</map>')
105 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
106 self.assertEqual(mapper({"src": b'-20'}, None),
107 {"x": -20, "y": 'foobar-20'})
108 self.assertRaisesWithMsg(base.ValidationError,
109 "Field x: While building x in _foo: invalid literal for int() with base 10: '3x3'",
110 mapper, ({"src": b"3x3"}, None))
111 self.assertRaisesWithMsg(base.ValidationError,
112 "Field y: While building y in _foo: 'utf-8' codec can't decode byte 0x98 in position 0:"
113 " invalid start byte",
114 mapper, ({"src": b"\x98x"}, None))
115
116 def testDefaultLiterals(self):
117 dd, td = makeDD('<column name="si" type="smallint"/>'
118 ' <column name="ii" type="integer"/>'
119 ' <column name="bi" type="bigint"/>'
120 ' <column name="r"/>'
121 ' <column name="dp" type="double precision"/>'
122 ' <column name="b" type="boolean"/>'
123 ' <column name="tx" type="text"/>'
124 ' <column name="c" type="char"/>'
125 ' <column name="d" type="date"/>'
126 ' <column name="ts" type="timestamp"/>'
127 ' <column name="t" type="time"/>'
128 ' <column name="raw" type="raw"/>',
129 '<map dest="si" src="si"/>'
130 ' <map dest="ii" src="ii"/>'
131 ' <map dest="bi" src="bi"/>'
132 ' <map dest="r" src="r"/>'
133 ' <map dest="dp" src="dp"/>'
134 ' <map dest="b" src="b"/>'
135 ' <map dest="tx" src="tx"/>'
136 ' <map dest="c" src="c"/>'
137 ' <map dest="d" src="d"/>'
138 ' <map dest="ts" src="ts"/>'
139 ' <map dest="t" src="t"/>'
140 ' <map dest="raw" src="raw"/>')
141 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
142 self.assertEqual(mapper({"si": "0", "ii": "2000", "bi": "-3000",
143 "r": "0.25", "dp": "25e3", "b": "Off", "tx": "abc", "c": "\xae",
144 "d": "2004-04-08", "ts": "2004-04-08T22:30:15", "t": "22:30:14",
145 "raw": ["x", "y", "z"]}, None), {
146 'c': '\xae', 'b': False, 'd': datetime.date(2004, 4, 8),
147 'tx': 'abc', 'bi': -3000,
148 'ts': datetime.datetime(2004, 4, 8, 22, 30, 15), 'ii': 2000,
149 'raw': ['x', 'y', 'z'], 'si': 0, 'r': 0.25,
150 't': datetime.time(22, 30, 14), 'dp': 25000.0})
151
152 def testIdmapsSimple(self):
153 dd, td = makeDD('<column name="foo"/><column name="bar"/>',
154 '<idmaps>foo</idmaps><map key="bar">3.0</map>')
155 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
156 self.assertEqual(mapper({'foo': 2}, None),
157 {'foo': 2, 'bar': 3.0})
158
159 def testIdmapsDontOverwrite(self):
160 dd, td = makeDD('<column name="foo"/><column name="bar"/>',
161 '<map dest="foo">float(@foo)/2</map><idmaps>*</idmaps>')
162 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
163 self.assertEqual(mapper({'foo': 2, 'bar': 2}, None),
164 {'foo': 1, 'bar':2})
165
166 def testIdmapsAndNull(self):
167 dd, td = makeDD('<column name="foo" type="text"/>',
168 '<map dest="foo">parseWithNull(@foo, str, "None")</map>'
169 '<idmaps>*</idmaps>')
170 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
171 self.assertEqual(mapper({'foo': "None"}, None), {'foo': None})
172 self.assertEqual(mapper({'foo': "123"}, None), {'foo': "123"})
173
174 def testMapNullAuto(self):
175 dd, td = makeDD('<column name="foo" type="integer"/>',
176 '<map dest="foo" nullExpr="22"/>')
177 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
178 self.assertEqual(mapper({'foo': "22"}, None), {'foo': None})
179 self.assertEqual(mapper({'foo': "23"}, None), {'foo': 23})
180
181 def testMapNullExprValue(self):
182 dd, td = makeDD('<column name="foo" type="integer"/>',
183 '<map dest="foo" nullExpr="22">parseInt(@bar)+22</map>')
184 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
185 self.assertEqual(mapper({'bar': "0"}, None), {'foo': None})
186 self.assertEqual(mapper({'bar': "1"}, None), {'foo': 23})
187
188 def testBadNullExpr(self):
189 self.assertRaisesWithMsg(base.BadCode,
190 'At IO:\'<data><table id="foo"><column name="foo" type="intege...\', (1, 152):'
191 " Bad source code in expression (invalid syntax"
192 " (<unknown>, line 1))",
193 makeDD,
194 ('<column name="foo" type="integer"/>',
195 '<map dest="foo" nullExpr="22-">parseInt(@bar)+22</map>'))
196
197 def testNullExcAutoTimestamp(self):
198 dd, td = makeDD('<column name="foo" type="timestamp"/>',
199 '<map dest="foo" src="foo" nullExcs="ValueError"/>')
200 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
201 self.assertEqual(mapper({'foo': "x3"}, None), {'foo': None})
202
203 def testOddSourceAtts(self):
204 dd, td = makeDD('<column name="foo"/><column name="bar"/>',
205 '<map dest="foo" source=\'knall"fall\'/>'
206 r'<map dest="bar" source="bad\ass"/>')
207 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
208 self.assertEqual(
209 mapper({
210 'knall"fall': "21",
211 "bad\\ass": "5e4"}, None),
212 {'foo': 21., 'bar': 5e4})
213
214 def testNumpyBool(self):
215 dd, td = makeDD('<column name="b" type="boolean"/>',
216 '<idmaps>*</idmaps>')
217 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
218 self.assertEqual(mapper({"b": numpy.bool_(True)}, None)["b"], True)
219 self.assertEqual(mapper({"b": numpy.bool_(False)}, None)["b"], False)
220
221
222 class RowmakerMapMessageTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest):
223 def _runTest(self, example):
224 tableBody, rmkBody, data, message = example
225 dd, td = makeDD(tableBody, rmkBody)
226 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
227 self.assertRaisesWithMsg(
228 base.ValidationError,
229 message,
230 mapper,
231 (data, None))
232
233 samples = [(
234 '<column name="x" type="integer" required="True"/>',
235 '<map dest="x">int(@src)</map>',
236 {},
237 "Field x: While building x in _foo: Key 'src' not found in a mapping."
238 ),(
239 '<column name="x" type="integer" required="True"/>',
240 '<map dest="x">int(@src)</map>',
241 {"src": "ab c"},
242 "Field x: While building x in _foo: invalid literal for int()"
243 " with base 10: 'ab c'"
244 ),(
245 '<column name="x" type="integer" required="True"/>',
246 '<var name="x">int(@src)</var>',
247 {"src": "ab c"},
248 "Field x: While assigning x in _foo: invalid literal for int()"
249 " with base 10: 'ab c'"
250 ),(
251 '<column name="x" type="text" required="True"/>',
252 '<map name="x">"abc"+@src</map>',
253 {"src": None},
254 "Field x: While building x in _foo: can only concatenate"
255 ' str (not "NoneType") to str'
256 ),
257
258 ]
259
260
261 class ApplyTest(testhelpers.VerboseTest):
262 """Tests for mapping procedures.
263 """
264 def testArtificial(self):
265 rd = base.parseFromString(rscdesc.RD,
266 '<resource schema="test"><procDef type="apply" id="artificial">'
267 '<setup><par key="val"/></setup><code>result["si"] = val</code>'
268 '</procDef>'
269 '<data><table id="foo"><column name="si" type="smallint"/></table>'
270 '<rowmaker id="_foo"><apply procDef="artificial" name="p1">\n'
271 '<bind key="val">23</bind></apply></rowmaker>\n'
272 '<make table="foo" rowmaker="_foo"/>'
273 '<dictlistGrammar/></data></resource>')
274 data = rd.dds[0]
275 mapper = data.rowmakers[0].compileForTableDef(data.makes[0].table)
276 self.assertEqual(mapper({"src": 23}, None), {'si': 23})
277
278 def testInline(self):
279 dd, td = makeDD(' <column name="si" type="smallint"/>',
280 ' <apply name="p1"><code>\n'
281 ' for i in range(int(vars["src"])):\n'
282 ' result["si"] = result.get("si", 0)+i\n'
283 ' </code></apply>')
284 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
285 self.assertEqual(mapper({"src": 23}, None), {'si': 253})
286
287 def testRaising(self):
288 self.assertRaisesWithMsg(base.NotFoundError,
289 "Element with id 'quatsch' could not be located in parse context",
290 makeDD, ('', '<apply name="xy" procDef="quatsch"/>'))
291
292 def testArgExpansion(self):
293 dd, td = makeDD('<column name="d" type="date"/>',
294 '<apply name="foo">'
295 ' <code>result["si"] = "\\test{1}{2}"\n</code>'
296 '</apply>')
297 res = rsc.makeData(dd, forceSource=[{}])
298 self.assertEqual(res.getPrimaryTable().rows,
299 [{'si': 'test macro expansion'},])
300
301 def testTableAccess(self):
302 dd, td = makeDD('<column name="d" type="date"/>',
303 '<apply name="foo">'
304 ' <code>result["ct"] = len(targetTable)\n</code>'
305 '</apply>')
306 res = rsc.makeData(dd, forceSource=[{}, {}, {}])
307 self.assertEqual(res.getPrimaryTable().rows,
308 [{'ct': 0}, {'ct': 1}, {'ct': 2}])
309
310 def testVariablesAvailable(self):
311 rowmakerDef = base.parseFromString(rscdef.RowmakerDef, """<rowmaker>
312 <apply>
313 <setup>
314 <par key="foo" late="True">@xzzx+"h"</par>
315 </setup>
316 <code>
317 result["norks"] = foo
318 </code>
319 </apply>
320 </rowmaker>""")
321 tab = rsc.TableForDef(base.makeStruct(rscdef.TableDef, columns=[]))
322 rmk = rowmakerDef.compileForTableDef(tab.tableDef)
323 self.assertEqual(rmk({"xzzx": "u"}, None)["norks"], "uh")
324
325 def testMissingRequiredPar(self):
326 self.assertRaisesWithMsg(base.StructureError,
327 'At IO:\'<data><table id="foo"><column name="d" type="text"/><...\', (6, 3):'
328 ' Parameter foo is not defaulted in foo and thus must be bound.',
329 makeDD,
330 ('<column name="d" type="text"/>',
331 """<apply name="foo">
332 <setup>
333 <par name="foo" late="True"/>
334 </setup>
335 <code>result["d"] = @foo</code>
336 </apply>""",))
337
338 def testLateAliasOverwrites(self):
339 rowmakerDef = base.parseFromString(rscdef.RowmakerDef, """<rowmaker>
340 <apply id="t">
341 <setup>
342 <par key="foo" alias="bar" late="True">"knall"</par>
343 </setup>
344 <code>
345 result[foo] = vars["in"]
346 </code>
347 </apply>
348 <apply procDef="t">
349 <bind name="bar">"fall"</bind>
350 </apply>
351 </rowmaker>""")
352 tab = rsc.TableForDef(base.makeStruct(rscdef.TableDef, columns=[]))
353 rmk = rowmakerDef.compileForTableDef(tab.tableDef)
354 self.assertEqual(
355 rmk({"in": "x"}, None),
356 {'knall': 'x', 'fall': 'x'})
357
358 def testEarlyAliasOverwrites(self):
359 rowmakerDef = base.parseFromString(rscdef.RowmakerDef, """<rowmaker>
360 <apply id="t">
361 <setup>
362 <par key="foo" alias="bar">"knall"</par>
363 </setup>
364 <code>
365 result[foo] = vars["in"]
366 </code>
367 </apply>
368 <apply procDef="t">
369 <bind name="bar">"fall"</bind>
370 </apply>
371 </rowmaker>""")
372 tab = rsc.TableForDef(base.makeStruct(rscdef.TableDef, columns=[]))
373 rmk = rowmakerDef.compileForTableDef(tab.tableDef)
374 self.assertEqual(
375 rmk({"in": "x"}, None),
376 {'knall': 'x', 'fall': 'x'})
377
378 def testComplexAliasing(self):
379 rmk = base.parseFromString(rscdef.RowmakerDef, """<rowmaker>
380 <apply procDef="//siap2#setMeta" id="foo">
381 <bind key="instrument">"tubelet"</bind>
382 <bind key="obs_collection">"testing"</bind>
383 </apply></rowmaker>""")
384 tab = rsc.TableForDef(base.makeStruct(rscdef.TableDef, columns=[]))
385 tab.tableDef.addMeta("facility", "GAVO")
386 rmk = rmk.compileForTableDef(tab.tableDef)
387 res = rmk({"prodtblAccref": "ab", "prodtblTable": None,
388 "prodtblMime": None, "prodtblFsize": None}, tab.tableDef)
389
390 # this means that the facility_name default has been overwritten
391 self.assertEqual(res["instrument_name"], "tubelet")
392 # this means that the getMeta defaults are still in place
393 self.assertEqual(res["facility_name"], "GAVO")
394
395 def testNoEarlyVar(self):
396 proc = base.parseFromString(
397 rscdef.RowmakerDef, """<rowmaker>
398 <apply procDef="//procs#dictMap" id="foo">
399 <bind key="mapping">@mapping</bind>
400 <bind key="key">"testing"</bind>
401 </apply></rowmaker>""")
402 td = base.makeStruct(rscdef.TableDef, columns=[])
403 self.assertRaisesWithMsg(
404 base.StructureError,
405 utils.EqualingRE(r"At .*/procs.rd, line 238: You cannot use @-references in non-late parameter bindings. But '@mapping' \(bound to mapping\) looks like an @-reference, so I give up."),
406 proc.compileForTableDef,
407 (td,))
408
409
410 class VarTest(testhelpers.VerboseTest):
411 """tests for rowmaker variables.
412 """
413 def testBadNameRaises(self):
414 self.assertRaisesWithMsg(base.StructureError,
415 'At IO:\'<data><table id="foo"></table><make table="foo"> <row...\', (1, 69):'
416 " '77x' is not a valid column identifier",
417 makeDD, ('', '<var name="77x">a</var>'))
418
419 def testBadSourceRaises(self):
420 self.assertRaisesWithMsg(base.StructureError,
421 'At IO:\'<data><table id="foo"></table><make table="foo"> <row...\', (1, 88): Bad source code in'
422 ' expression (Not an expression)',
423 makeDD, ('', '<var name="x77">a=b</var>'))
424
425 def testBasic(self):
426 dd, td = makeDD(' <column name="si" type="smallint"/>',
427 ' <var name="x">28</var>'
428 ' <var name="y">29+@x</var>'
429 ' <map dest="si">@y</map>')
430 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
431 self.assertEqual(mapper({}, None), {'si': 57})
432
433 def testRaising(self):
434 dd, td = makeDD(' <column name="si" type="smallint"/>',
435 ' <map dest="si" nullExcs="ZeroDivisionError">1/0</map>')
436 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
437 self.assertEqual(mapper({}, None), {'si': None})
438
439 def testDefaultMapping(self):
440 dd, td = makeDD(' <column name="x"/>',
441 ' <var key="xcooked" source="xraw" nullExcs="KeyError"/>'
442 ' <map key="x" source="xcooked"/>')
443 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
444 self.assertEqual(mapper({}, None), {'x': None})
445 self.assertEqual(mapper({"xraw": "33"}, None), {'x': 33.})
446
447
448 class SimpleMapsTest(testhelpers.VerboseTest):
449 def testBasic(self):
450 dd, td = makeDD('<column name="si" type="smallint"/>'
451 '<column name="bi" type="smallint"/>',
452 ' <simplemaps>si:x, bi:y</simplemaps>')
453 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
454 self.assertEqual(mapper({'x': 57, 'y':'28'}, None),
455 {'si': 57, 'bi': 28})
456
457 def testFromAttribute(self):
458 dd = base.parseFromString(rscdef.DataDescriptor,
459 '<data><table id="foo"><column name="z" type="date"/></table>'
460 '<dictlistGrammar/><make table="foo">'
461 '<rowmaker simplemaps="z:ds"/></make></data>')
462 td = dd.getTableDefById("foo")
463 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
464 self.assertEqual(mapper({'ds': '2010-01-03'}, None),
465 {'z': datetime.date(2010, 1, 3)})
466
467 def testMissingTargetFails(self):
468 dd, td = makeDD('<column name="si" type="smallint"/>',
469 ' <simplemaps>bi:y</simplemaps>')
470 self.assertRaisesWithMsg(base.NotFoundError,
471 "column 'bi' could not be located in table foo's columns",
472 dd.makes[0].rowmaker.compileForTableDef, (td,))
473
474
475 class PredefinedTest(testhelpers.VerboseTest):
476 """tests for procedures from //procs and some predefined rowmaker functions.
477 """
478 def testSimbadOk(self):
479 dd, td = makeDD(' <column name="alpha" type="real"/>'
480 ' <column name="delta" type="real"/>',
481 ' <apply procDef="//procs#resolveObject">'
482 ' <bind key="identifier">vars["src"]</bind>'
483 ' </apply>'
484 ' <map dest="alpha">@simbadAlpha</map>'
485 ' <map dest="delta">@simbadDelta</map>')
486 res = rsc.makeData(dd, forceSource=[{'src': "Aldebaran"}])
487 row = res.getPrimaryTable().rows[0]
488 self.assertEqual(str(row["alpha"])[:6], "68.980")
489 self.assertEqual(len(row), 2)
490
491 def testSimbadFail(self):
492 dd, td = makeDD('<column name="alpha" type="real"/>'
493 ' <column name="delta" type="real"/>',
494 ' <apply procDef="//procs#resolveObject">'
495 ' <bind key="ignoreUnknowns">False</bind>'
496 ' <bind key="identifier">src</bind>'
497 ' </apply>'
498 ' <map dest="alpha">simbadAlpha</map>'
499 ' <map dest="delta">simbadDelta</map>')
500 self.assertRaises(base.ValidationError,
501 rsc.makeData, dd, forceSource=[{'src': "Quxmux_333x"}])
502
503 def testNoAliasing(self):
504 dd, td = makeDD('<column name="x" type="text"/>'
505 '<column name="y" type="text"/>',
506 '<apply procDef="//procs#mapValue">'
507 '<bind key="sourceName">"%s"</bind>'
508 '<bind key="destination">"x"</bind><bind key="value">'
509 'vars["in1"]</bind></apply>'
510 '<apply procDef="//procs#mapValue">'
511 '<bind key="sourceName">"%s"</bind>'
512 '<bind key="destination">"y"</bind><bind key="value">'
513 'vars["in2"]</bind></apply>'
514 '<idmaps>*</idmaps>'%(os.path.abspath("test_data/map1.map"),
515 os.path.abspath("test_data/map2.map")))
516 res = rsc.makeData(dd, forceSource=[{'in1': 'foo', 'in2': 'left'}])
517 self.assertEqual(res.getPrimaryTable().rows,
518 [{'y': 'right', 'x': 'bar'}])
519
520 def testMapDict(self):
521 dd, td = makeDD(' <column name="foo" type="text"/>',
522 ' <apply procDef="//procs#dictMap" name="mapFoo">'
523 ' <bind key="key">"foo"</bind>'
524 ' <bind key="mapping">{"x": "u", "0": "1"}</bind>'
525 ' </apply><idmaps>*</idmaps>')
526 res = rsc.makeData(dd, forceSource=[{'foo': "x"}])
527 self.assertEqual(res.getPrimaryTable().rows[0]["foo"], "u")
528
529 self.assertRaisesWithMsg(base.ValidationError,
530 "Field foo: dictMap saw '1', which it was not prepared to see.",
531 rsc.makeData,
532 (dd,), forceSource=[{'foo': "1"}])
533
534 def testMapDictDefault(self):
535 dd, td = makeDD(' <column name="foo" type="text"/>',
536 ' <apply procDef="//procs#dictMap" name="mapFoo">'
537 ' <bind key="key">"foo"</bind>'
538 ' <bind key="default">None</bind>'
539 ' <bind key="mapping">{"x": "u", "0": "1"}</bind>'
540 ' </apply><idmaps>*</idmaps>')
541 res = rsc.makeData(dd, forceSource=[{'foo': "x"}, {"foo": "y"}])
542 rows = res.getPrimaryTable().rows
543 self.assertEqual(rows[0]["foo"], "u")
544 self.assertEqual(rows[1]["foo"], None)
545
546 def testUnboundDictMap(self):
547 dd, td = makeDD(' <column name="foo" type="text"/>',
548 ' <apply procDef="//procs#dictMap" name="mapFoo">'
549 ' <setup><par name="mapping">{"x": 3, "y": 2}</par>'
550 ' <par name="key">"foo"</par></setup>'
551 ' </apply><idmaps>*</idmaps>')
552 res = rsc.makeData(dd, forceSource=[{'foo': "x"}, {"foo": "y"}])
553 rows = res.getPrimaryTable().rows
554 self.assertEqual(rows[0]["foo"], "3")
555 self.assertEqual(rows[1]["foo"], "2")
556
557
558 class RowmakerMacroTest(testhelpers.VerboseTest):
559 """tests for the standard macros defined by row makers.
560 """
561 def test_standardPubDID(self):
562 dd, td = makeDD('<column name="x" type="text" required="True"/>',
563 r'<map dest="x">\standardPubDID</map>',
564 parentRD=testhelpers.getTestRD("ssatest"))
565 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
566 self.assertEqual(
567 mapper(
568 {'prodtblAccref': 'foo'}, None)['x'],
569 'ivo://x-testing/~?foo')
570
571 def test_standardPubDIDRejectingUnregistered(self):
572 with testhelpers.tempConfig(("ivoa", "authority", "x-unregistred")):
573 dd, td = makeDD('<column name="x" type="text" required="True"/>',
574 r'<map dest="x">\standardPubDID</map>',
575 parentRD=testhelpers.getTestRD("ssatest"))
576 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
577 self.assertRaisesWithMsg(base.ValidationError,
578 "Field x: While building x in _foo: You must configure your"
579 " IVOA authority before creating standard PubDIDs.",
580 mapper,
581 ({'prodtblAccref': 'foo'}, None))
582
583 def test_dlMetaURI(self):
584 dd, td = makeDD('<column name="x" type="text" required="True"/>',
585 r'<map dest="x">\dlMetaURI{dl}</map>',
586 parentRD=testhelpers.getTestRD("ssatest"))
587 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
588 self.assertEqual(
589 mapper(
590 {'prodtblAccref': 'foo'}, None)['x'],
591 'http://localhost:8080/data/ssatest/dl/dlmeta'
592 '?ID=ivo%3A//x-testing/~%3Ffoo')
593
594 def test_inputRelativePath(self):
595 dd, td = makeDD('<column name="x" type="text" required="True"/>',
596 r'<map dest="x">\inputRelativePath</map>',
597 parentRD=testhelpers.getTestRD("ssatest"))
598
599 class Parser:
600 sourceToken = dd.rd.getAbsPath('foo/bar+baz')
601
602 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
603 self.assertEqual(
604 mapper({"parser_": Parser} , None)['x'],
605 'foo/bar+baz')
606
607 def test_rowsMade(self):
608 dd, td = makeDD('<column name="x" type="integer" required="True"/>',
609 r'<map dest="x">\rowsMade</map>')
610
611 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
612 self.assertEqual(
613 mapper({}, None)['x'],
614 0)
615 self.assertEqual(
616 mapper({}, None)['x'],
617 1)
618
619 def test_property(self):
620 dd, td = makeDD('<column name="x" type="integer" required="True"/>',
621 r'<map dest="x">\property{prop}</map>',
622 grammar='<dictlistGrammar/><property key="prop">bla</property>')
623 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
624 self.assertEqual(
625 mapper({}, None)['x'],
626 "bla")
627
628 def test_srcstem(self):
629 dd, td = makeDD('<column name="x" type="integer" required="True"/>',
630 r'<map dest="x">\srcstem</map>')
631 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
632
633 class Parser:
634 sourceToken = 'goo/quux/foo/bar+baz.tar.gz'
635
636 self.assertEqual(
637 mapper({"parser_": Parser}, None)['x'],
638 "bar+baz")
639
640 def test_lastSourceEl(self):
641 dd, td = makeDD('<column name="x" type="text" required="True"/>',
642 r'<map dest="x">\lastSourceElements{3}</map>',
643 parentRD=testhelpers.getTestRD("ssatest"))
644 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
645
646 class Parser:
647 sourceToken = dd.rd.getAbsPath('goo/quux/foo/bar+baz')
648
649 self.assertEqual(
650 mapper({"parser_": Parser}, None)['x'],
651 'quux/foo/bar+baz')
652
653 def test_rootlessPathl(self):
654 dd, td = makeDD('<column name="x" type="text" required="True"/>',
655 r'<map dest="x">\rootlessPath</map>',
656 parentRD=testhelpers.getTestRD("ssatest"))
657 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
658
659 class Parser:
660 sourceToken = dd.rd.getAbsPath('norz/foo.fits')
661
662 self.assertEqual(
663 mapper({"parser_": Parser}, None)['x'],
664 'norz/foo.fits')
665
666 def test_inputSize(self):
667 dd, td = makeDD('<column name="x" type="integer" required="True"/>',
668 r'<map dest="x">\inputSize</map>',
669 parentRD=testhelpers.getTestRD("ssatest"))
670 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
671
672 class Parser:
673 sourceToken = dd.rd.getAbsPath('data/spec3.ssatest')
674
675 self.assertEqual(
676 mapper({"parser_": Parser}, None)['x'], 213)
677
678 def test_qName(self):
679 dd, td = makeDD('<column name="x" type="text" required="True"/>',
680 r'<map dest="x">\qName</map>',
681 parentRD=testhelpers.getTestRD("ssatest"))
682 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
683 self.assertEqual(
684 mapper({}, None)['x'], 'test.foo')
685
686
687 class IgnoreOnTest(testhelpers.VerboseTest):
688 """tests for working ignoreOn clauses.
689 """
690 def testBasic(self):
691 dd, td = makeDD('<column name="si"/>',
692 '<ignoreOn><keyPresent key="y"/></ignoreOn><idmaps>*</idmaps>')
693 mapper = dd.makes[0].rowmaker.compileForTableDef(td)
694 self.assertEqual(mapper({'si': '1'}, None), {'si': 1.0})
695 self.assertRaises(rscdef.IgnoreThisRow, mapper,
696 {'si': 1, 'y': None}, None)
697
698 def testBuilding(self):
699 dd, td = makeDD('<column name="si"/>',
700 '<ignoreOn><keyMissing key="y"/></ignoreOn><idmaps>*</idmaps>')
701 table = rsc.makeData(dd, forceSource=[{'si':1}, {'si':2, 'y':"yes"},
702 {'si': 3}]).getPrimaryTable()
703 self.assertEqual(table.rows, [{'si':2.}])
704
705
706 class ToParameterTest(testhelpers.VerboseTest):
707 def testPlain(self):
708 dd, td = makeDD('<param name="u" type="integer"/>', "",
709 '<dictlistGrammar asPars="True"/>',
710 '<parmaker><map dest="u" src="u"/></parmaker>')
711 data = rsc.makeData(dd, forceSource=[{"u": "10"}])
712 self.assertEqual(data.getPrimaryTable().getParam("u"), 10)
713
714 def testConstant(self):
715 dd, td = makeDD('<param name="u" type="integer"/>', "",
716 '<dictlistGrammar/>',
717 '<parmaker><map dest="u">10</map></parmaker>')
718 data = rsc.makeData(dd, forceSource=[])
719 self.assertEqual(data.getPrimaryTable().getParam("u"), 10)
720
721 def testIdmaps(self):
722 dd, td = makeDD('<param name="u" type="timestamp"/>'
723 '<param name="pos" type="spoint"/>', "",
724 '<dictlistGrammar asPars="True"/>',
725 '<parmaker idmaps="*"/>')
726 data = rsc.makeData(dd, forceSource=[
727 {'u': "2010-10-10T10:10:10", 'pos': '34,-30'}])
728 self.assertEqual(data.getPrimaryTable().getParam("u"),
729 datetime.datetime(2010, 10, 10, 10, 10, 10))
730 self.assertAlmostEqual(data.getPrimaryTable().getParam("pos").x,
731 34*DEG)
732
733 def testBadDest(self):
734 dd, td = makeDD('<param name="u" type="timestamp"/>', "",
735 '<dictlistGrammar/>',
736 '<parmaker><map dest="foo">10</map></parmaker>')
737 self.assertRaisesWithMsg(base.NotFoundError,
738 "column 'foo' could not be located in table foo's params",
739 rsc.makeData,
740 (dd, rsc.parseNonValidating, []))
741
742 def testBadSource(self):
743 dd, td = makeDD('<param name="u" type="timestamp"/>', "",
744 '<dictlistGrammar/>',
745 '<parmaker><map dest="u" src="bar"/></parmaker>')
746 self.assertRaisesWithMsg(base.ValidationError,
747 "Field u: While building u in <rowmaker without id>: Key 'bar'"
748 " not found in a mapping.",
749 rsc.makeData,
750 (dd, rsc.parseNonValidating, []))
751
752
753 if __name__=="__main__":
754 testhelpers.main(ToParameterTest)