Debian Codegraph @

tests/obscoretest.py

raw
1 """
2 Unit tests roughly to do with obscore.
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 os
13
14 from gavo.helpers import testhelpers
15 from gavo import api
16 from gavo import base
17 from gavo.protocols import obscore
18 from gavo.protocols import tap
19 from gavo.registry import builders
20
21 import tresc
22
23 _obscoreRDTrunk = """<resource schema="test" resdir="data">
24 <table id="glob" onDisk="True" mixin="//products#table">
25 <param name="foo" type="text">replaced</param>
26 <mixin %s>//obscore#publish</mixin>
27 <publish/>
28 </table>
29 <data id="import">
30 <dictlistGrammar>
31 <rowfilter procDef="//products#define">
32 <bind key="table">"test.glob"</bind>
33 <bind key="accref">@accref</bind>
34 <bind key="path">@accref</bind>
35 <bind key="fsize">22</bind>
36 </rowfilter>
37 </dictlistGrammar>
38 <make table="glob"/>
39 </data></resource>"""
40
41
42 class ObscoreTest(testhelpers.VerboseTest):
43 def testTypeRequired(self):
44 self.assertRaisesWithMsg(api.StructureError,
45 'At IO:\'<resource schema="test" resdir="data"> <table id="glo...\', (4, 29):'
46 " Mixin parameter dataproduct_type mandatory",
47 api.parseFromString,
48 (api.RD, _obscoreRDTrunk%""))
49
50 def testRestriction(self):
51 self.assertRaises(api.StructureError,
52 api.parseFromString,
53 api.RD, _obscoreRDTrunk%'productType="\'image\'" ',
54 context=base.ParseContext(restricted=True))
55
56 def testObscoreProperty(self):
57 rd = api.parseFromString(api.RD,
58 _obscoreRDTrunk%'productType="\'image\'" ')
59 viewPart = rd.tables[0].properties["obscoreClause"]
60 self.assertTrue("CAST('image' AS text) AS dataproduct_type" in viewPart)
61 self.assertTrue("CAST(__COMPUTE__ AS text) AS obs_publisher_did"
62 in viewPart)
63 self.assertTrue(
64 "CAST(accsize/1024 AS bigint) AS access_estsize" in viewPart)
65 self.assertTrue("CAST(NULL AS spoly) AS s_region" in viewPart)
66
67 def testScriptAdded(self):
68 rd = api.parseFromString(api.RD,
69 _obscoreRDTrunk%'productType="\'image\'" ')
70 for script in rd.getById("import").makes[0].table.scripts:
71 if script.id=="addTableToObscoreSources":
72 break
73 else:
74 self.fail("addTableToObscoreSources not added -- did obscore#publish"
75 " run?")
76
77
78 class _ObscoreRegistryRecord(testhelpers.TestResource):
79 def make(self, deps):
80 tree = testhelpers.getXMLTree(
81 builders.getVOResourceElement(
82 base.resolveCrossId("//obscore#ObsCore")).render(), debug=False)
83 return tree.xpath("metadata/Resource")[0]
84
85
86 class ObscoreResourceRecordTest(testhelpers.VerboseTest):
87 resources = [("tree", _ObscoreRegistryRecord())]
88
89 def testUtype(self):
90 self.assertEqual(self.tree.xpath("tableset/schema/table/utype")[0].text,
91 "ivo://ivoa.net/std/obscore#table-1.1")
92
93 def testTitle(self):
94 self.assertEqual(
95 self.tree.xpath("title")[0].text,
96 "Unittest Suite Obscore Table")
97
98 def testShortName(self):
99 self.assertEqual(
100 self.tree.xpath("shortName")[0].text,
101 "<13 chrs Obscore")
102
103 def testRelationship(self):
104 self.assertEqual(
105 self.tree.xpath("content/relationship[relationshipType='IsServedBy']"
106 "/relatedResource/@ivo-id")[0],
107 "ivo://x-testing/tap")
108
109 def testAuxCap(self):
110 self.assertEqual(
111 self.tree.xpath("capability[@standardID='ivo://ivoa.net/std/TAP#aux']"
112 "/interface/accessURL")[0].text,
113 "http://localhost:8080/tap")
114
115 def testColumn(self):
116 self.assertEqual(
117 self.tree.xpath("tableset/schema/table/column[name='t_xel']/ucd"
118 )[0].text,
119 "meta.number")
120
121
122 class _ObscorePublishedTable(testhelpers.TestResource):
123 resources = [('conn', tresc.dbConnection)]
124
125 def make(self, dependents):
126 conn = dependents["conn"]
127 from gavo import rsc
128
129 dd = api.parseFromString(api.RD,
130 _obscoreRDTrunk%'productType="\'image\'"'
131 ' collectionName="\'testing detritus\'"'
132 ' creatorDID="\'\\getParam{foo}\'"').getById("import")
133 dd.rd.sourceId = "__testing__"
134 d = rsc.makeData(dd,
135 forceSource=[{"accref": "foo/bar"}],
136 connection=conn,
137 parseOptions=rsc.getParseOptions(buildDependencies=True))
138 tap.publishToTAP(dd.rd, conn)
139 return d
140
141 def clean(self, data):
142 conn = data.tables["glob"].connection
143 try:
144 data.drop(data.dd, connection=conn)
145 tap.unpublishFromTAP(data.dd.rd, conn)
146 conn.commit()
147 except:
148 import traceback
149 traceback.print_exc()
150 conn.rollback()
151 res = list(data.tables["glob"].connection.query("select sqlFragment"
152 " from ivoa._obscoresources where tableName='test.glob'"))
153 # Yes, this is a test within a test resource. It's most
154 # convenient this way. I'm sorry.
155 assert len(res)==0
156
157
158 class ObscorePublishedTest(testhelpers.VerboseTest):
159 resources = [
160 ('oc', tresc.obscoreTable),
161 ('data', _ObscorePublishedTable()),
162 ('hcd', tresc.ssaTestTable),
163 ('siap', tresc.siapTestTable),
164 ('conn', tresc.dbConnection)]
165
166 def testJoinPresent(self):
167 res = list(self.data.tables["glob"].connection.query("select sqlFragment"
168 " from ivoa._obscoresources where tableName='test.glob'"))
169 self.assertEqual(len(res), 1)
170 self.assertTrue("('ivo://x-testing/~?'"
171 " || gavo_urlescape(accref)) AS obs_publisher_did," in res[0][0])
172
173 def testDataIsInObscore(self):
174 from gavo import rsc
175 oct = rsc.TableForDef(
176 base.caches.getRD("//obscore").getById("ObsCore"),
177 connection=self.conn)
178 res = list(oct.iterQuery(oct.tableDef,
179 "obs_id='foo/bar'"))
180 row = testhelpers.pickSingle(res)
181 self.assertEqual(row["dataproduct_type"], 'image')
182 self.assertEqual(row["access_estsize"], 0)
183
184 def testAccessibleThroughADQL(self):
185 from gavo.protocols import adqlglue
186 from gavo.formats import votablewrite
187 connection=self.data.tables["glob"].connection
188 res = adqlglue.runTAPQuery("select * from ivoa.ObsCore where"
189 " obs_collection='testing detritus'", 10, connection, [], 100,
190 autoClose=False)
191 self.assertTrue(b'<TD>foo/bar</TD>'
192 in votablewrite.getAsVOTable(res, tablecoding="td"))
193
194 def testMacroIsExpanded(self):
195 res = list(
196 self.data.tables["glob"].connection.queryToDicts(
197 "select obs_creator_did from ivoa.obscore"
198 " where obs_publisher_did='ivo://x-testing/~?foo/bar'"))
199 try:
200 self.assertEqual(res, [{'obs_creator_did': 'replaced'}])
201 except AssertionError:
202 import pdb;pdb.Pdb(nosigint=True).set_trace()
203 raise
204
205 def testModelDeclarationPresent(self):
206 res = list(
207 self.conn.query("SELECT dmivorn FROM tap_schema.supportedmodels"
208 " WHERE dmname ILIKE 'obscore%%'"))
209 self.assertEqual(res, [('ivo://ivoa.net/std/obscore#core-1.1',)])
210
211 def testSuspension(self):
212 t = self.data.tables["glob"]
213 with obscore.suspendFromObscore(t.tableDef.rd, self.conn):
214 with base.getTableConn() as econn:
215 self.assertEqual(
216 list(econn.query("SELECT obs_publisher_did FROM ivoa.obscore"
217 " WHERE source_table='test.glob'")),
218 [])
219
220 self.assertEqual(
221 list(self.conn.query("SELECT obs_publisher_did FROM ivoa.obscore"
222 " WHERE source_table='test.glob'")),
223 [('ivo://x-testing/~?foo/bar',)])
224
225 def testObscoreRelationDeclared(self):
226 for meta in self.data.tables["glob"].iterMeta("isServedBy"):
227 self.assertEqual(
228 meta.getMeta("ivoId").getContent("text"),
229 "ivo://x-testing/__system__/obscore/obscore")
230 self.assertEqual(meta.getContent("text"), "Unittest Suite Obscore")
231 break
232 else:
233 raise AssertionError("No isServedBy meta on obscore table")
234
235
236 class TablesetTest(testhelpers.VerboseTest):
237 resources = [
238 ('oc', tresc.obscoreTable),
239 ("table", tresc.ssaTestTable),
240 ("ssa", tresc.ssaTestTable)]
241
242 def testObscoreStubInOwnTableset(self):
243 vorElement = builders.getVOResourceElement(self.table.tableDef)
244 tree = testhelpers.getXMLTree(vorElement.render(), debug=False)
245
246 obscoreStub = tree.xpath(
247 "metadata/Resource/tableset/schema[name='ivoa']"
248 "/table[name='ivoa.obscore']")[0]
249 self.assertFalse(
250 obscoreStub.xpath("column"),
251 "ivoa.obscore on published table is not just a stub.")
252
253 def testInTAPTableset(self):
254 vorElement = builders.getVOResourceElement(
255 base.resolveCrossId("//tap#run"))
256 tree = testhelpers.getXMLTree(vorElement.render(), debug=False)
257 self.assertEqual(len(tree.xpath(
258 "metadata/Resource/tableset/schema[name='ivoa']"
259 "/table[name='ivoa.obscore']")), 1)
260 self.assertEqual(len(tree.xpath(
261 "metadata/Resource/tableset/schema[name='ivoa']"
262 "/table[name='ivoa.obscore']/column[name='s_ra']")), 1)
263
264 # assertion: the thing is found
265 _ = tree.xpath(
266 "metadata/Resource/tableset/schema[name='test']"
267 "/table[name='test.hcdtest']")[0]
268
269
270 class _ModifiedObscoreTables(testhelpers.TestResource):
271
272 def make(self, dependents):
273 with testhelpers.userconfigContent("""
274 <STREAM id="obscore-extraevents">
275 <property name="obscoreClause" cumulate="True">
276 ,
277 CAST(\\\\plutoLong AS real) AS pluto_long,
278 CAST(\\\\plutoLat AS real) AS pluto_lat
279 </property>
280 </STREAM>
281 <STREAM id="obscore-extrapars">
282 <mixinPar name="plutoLong">NULL</mixinPar>
283 <mixinPar name="plutoLat">22</mixinPar>
284 </STREAM>
285 <STREAM id="obscore-extracolumns">
286 <column name="pluto_long" tablehead="lambda_Pluto"/>
287 <column name="pluto_lat"/>
288 </STREAM>"""):
289
290 base.caches.clearForName("__system__/obscore")
291 with testhelpers.testFile(
292 os.path.join(api.getConfig("inputsDir"), "ex.rd"), """
293 <resource schema="__system">
294 <table id="instable" onDisk="yes">
295 <mixin plutoLong="56">//obscore#publishSSAPHCD</mixin>
296 </table>
297 </resource>
298 """) as fName:
299 insTable = base.caches.getRD(fName).getById("instable")
300 ocTable = base.caches.getRD("//obscore").getById("ObsCore")
301 base.caches.clearForName("__system__/obscore")
302
303 return insTable, ocTable
304
305
306 class ObscoreModificationTest(testhelpers.VerboseTest):
307
308 resources = [("tables", _ModifiedObscoreTables())]
309
310 def testObscoreTableChanged(self):
311 _, obscoreTD = self.tables
312 self.assertEqual(obscoreTD.getColumnByName("pluto_long").tablehead,
313 "lambda_Pluto")
314
315 def testSubstrateChanged(self):
316 substrateTD, _ = self.tables
317 self.assertTrue("CAST(56 AS real) AS pluto_long" in
318 substrateTD.getProperty("obscoreClause"))
319 self.assertTrue("CAST(22 AS real) AS pluto_lat" in
320 substrateTD.getProperty("obscoreClause"))
321
322
323 class _ObscoreLikeTD(testhelpers.TestResource):
324 def make(self, ignored):
325 return api.parseFromString(api.RD,
326 """<resource schema="test">
327
328 <table id="ol" onDisk="True">
329 <mixin
330 dataproduct_type="'image'"
331 dataproduct_subtype="NULL"
332 >//obscore#publishObscoreLike</mixin>
333 <FEED source="//obscore#obscore-columns">
334 <PRUNE name="dataproduct_.*"/>
335 </FEED>
336 </table>
337 </resource>
338 """).getById("ol")
339
340
341 class ObscoreLikeTest(testhelpers.VerboseTest):
342 resources = [("td", _ObscoreLikeTD())]
343
344 def testObscoreColumnsPresent(self):
345 self.assertEqual(self.td.getColumnByName("obs_id").description,
346 "Unique identifier for an observation")
347
348 def testPurgedColumnsMissing(self):
349 self.assertRaisesWithMsg(api.NotFoundError,
350 "column 'dataproduct_type' could not be located in table ol",
351 self.td.getColumnByName,
352 ("dataproduct_type",))
353
354 def testObscoreClause(self):
355 oc = self.td.expand(self.td.getProperty("obscoreClause"))
356 self.assertTrue("CAST('image' AS text) AS dataproduct_type," in oc)
357 self.assertTrue(" CAST(calib_level AS smallint) AS calib_level," in oc)
358
359 def testTableName(self):
360 oc = self.td.expand(self.td.getProperty("obscoreClause"))
361 self.assertTrue("CAST('test.ol' AS text) AS source_table" in oc)
362
363
364 class ObscoreDroppingTest(testhelpers.VerboseTest):
365 # make sure you don't commit anything here, as other tests rely on
366 # having obscore live
367 resources = [
368 ('oc', tresc.obscoreTable),]
369
370 def testDMUndeclared(self):
371 from gavo.user import dropping
372
373 class opts:
374 systemImport = True
375 force = False
376 dropAll = True
377
378 with base.getWritableAdminConn() as conn:
379 dropping._do_dropRD(opts, "//obscore", conn)
380 res = list(conn.query(
381 "SELECT dmivorn FROM tap_schema.supportedmodels"
382 " WHERE dmname ILIKE 'obscore%%'"))
383 self.assertEqual(res, [])
384 conn.rollback()
385
386 api.makeData(
387 base.resolveCrossId("//obscore#create"),
388 connection=conn)
389 conn.commit()
390
391
392 class ObscoreRecoverTest(testhelpers.VerboseTest):
393 resources = [
394 ("conn", tresc.dbConnection),
395 ('oc', tresc.obscoreTable),]
396
397 @contextlib.contextmanager
398 def crap(self, conn):
399 conn.execute("insert into ivoa._obscoresources"
400 " (tablename, sqlfragment, sourcerd)"
401 " values"
402 " ('tap_schema.tables', 'totally borken', 'non/existing'),"
403 " ('non.existing', 'select * from tap_schema.tables', 'non/existing')")
404 try:
405 yield
406 finally:
407 conn.rollback()
408
409 def testCrapBombs(self):
410 with self.crap(self.conn):
411 self.assertRaisesWithMsg(base.StructureError,
412 api.EqualingRE(".*Execution of python script createObscoreView"
413 " failed: syntax error at or near \"totally.*"),
414 api.makeData,
415 (api.resolveCrossId("//obscore#create"),),
416 connection=self.conn, runCommit=False)
417
418 def testCleanup(self):
419 with self.crap(self.conn):
420 api.makeData(
421 api.resolveCrossId("//obscore#recover"), connection=self.conn)
422
423 obscoreTables = set(r[0] for r in
424 self.conn.query("select tablename from ivoa._obscoresources"))
425
426 self.assertFalse("non.existing" in obscoreTables,
427 "Non-existing table not purged from obscore")
428 self.assertFalse("tap_schema.tables" in obscoreTables,
429 "Table with bad view contribution not purged from obscore tables")
430
431
432 class ObscoreStatsTest(testhelpers.VerboseTest):
433 resources = [
434 ("conn", tresc.dbConnection),
435 ("oc", tresc.obscoreTable)]
436
437 def testStatsStable(self):
438 from gavo.user import limits, importing
439 limits.updateTableLevelStats(
440 api.resolveCrossId("//obscore#ObsCore"), self.conn)
441 metacols = set(r[0] for r in self.conn.query(
442 "select column_name from dc.discrete_string_values"
443 " where tablename='ivoa.ObsCore'"))
444 self.assertEqual(metacols, {'target_class', 'instrument_name',
445 'obs_collection', 'facility_name', 'dataproduct_type'})
446 self.conn.commit()
447
448 importing.process(api.getParseOptions(), ["data/ssatest", "test_import"])
449 metacols = set(r[0] for r in self.conn.query(
450 "select column_name from dc.discrete_string_values"
451 " where tablename='ivoa.ObsCore'"))
452 self.assertEqual(metacols, {'target_class', 'instrument_name',
453 'obs_collection', 'facility_name', 'dataproduct_type'})
454
455
456 class ObsRadioTest(testhelpers.VerboseTest):
457 resources = [
458 ("conn", tresc.dbConnection)]
459
460 # building a proper testbed here is real work. I'm delaying this until
461 # I'm a bit more confident that my current plan will sort of work out.
462 def testCreation(self):
463 try:
464 api.makeData(api.resolveCrossId("//obs-radio#init"),
465 connection=self.conn, runCommit=False)
466 api.makeData(api.resolveCrossId("//obs-radio#create"),
467 connection=self.conn, runCommit=False)
468 finally:
469 self.conn.rollback()
470
471 def testColumns(self):
472 # This will certainly evolve as the spec does; adapt this using
473 # print(set(col.name for col in api.resolveCrossId("//obs-radio#obs_radio")))
474 self.assertEqual(
475 set(col.name for col in api.resolveCrossId("//obs-radio#obs_radio")),
476 {'obs_publisher_did', 's_fov_min', 'instrument_feed', 't_exp_min', 't_exp_mean', 'f_resolution', 'scan_mode', 't_exp_max', 'instrument_ant_max_dist', 'tracking_mode', 's_fov_max', 'uv_distribution_fill', 'instrument_ant_diameter', 's_maximum_angular_scale', 'uv_distribution_ecc', 's_resolution_min', 'uv_distance_max', 'uv_distance_min', 'instrument_ant_min_dist', 's_resolution_max', 'instrument_ant_number'})
477
478
479 if __name__=="__main__":
480 testhelpers.main(ObscoreModificationTest)