| 1 |
# -*- coding: utf-8 -*- |
| 2 |
""" |
| 3 |
Tests for grammars and their helpers. |
| 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 contextlib |
| 14 |
import io |
| 15 |
import os |
| 16 |
import struct |
| 17 |
import unittest |
| 18 |
|
| 19 |
from astropy import table |
| 20 |
|
| 21 |
from gavo.helpers import testhelpers |
| 22 |
|
| 23 |
from gavo import base |
| 24 |
from gavo import rsc |
| 25 |
from gavo import rscdef |
| 26 |
from gavo import svcs |
| 27 |
from gavo import utils |
| 28 |
from gavo.grammars import binarygrammar |
| 29 |
from gavo.grammars import columngrammar |
| 30 |
from gavo.grammars import common |
| 31 |
from gavo.grammars import fitsprodgrammar |
| 32 |
from gavo.grammars import fitstablegrammar |
| 33 |
from gavo.grammars import odbcgrammar |
| 34 |
from gavo.grammars import pdsgrammar |
| 35 |
from gavo.grammars import regrammar |
| 36 |
from gavo.grammars import uniongrammar |
| 37 |
from gavo.grammars import xmlgrammar |
| 38 |
from gavo.helpers import testtricks |
| 39 |
|
| 40 |
try: |
| 41 |
from gavo.grammars import hdf5grammar |
| 42 |
def skipIfNoH5py(obj): |
| 43 |
return obj |
| 44 |
except ImportError: |
| 45 |
def skipIfNoH5py(obj): |
| 46 |
return unittest.skip("No h5py")(obj) |
| 47 |
|
| 48 |
@contextlib.contextmanager |
| 49 |
def TestFile(initData): |
| 50 |
"""context-manages a BytesIO that's constructed with a string. |
| 51 |
""" |
| 52 |
f = io.BytesIO(utils.bytify(initData)) |
| 53 |
try: |
| 54 |
yield f |
| 55 |
finally: |
| 56 |
f.close() |
| 57 |
|
| 58 |
|
| 59 |
def getCleaned(rawIter): |
| 60 |
"""returns cleaned rawdicts form a rawdict iterator |
| 61 |
|
| 62 |
(this currently just kills the parser_ key). |
| 63 |
""" |
| 64 |
res = [] |
| 65 |
for d in rawIter: |
| 66 |
del d["parser_"] |
| 67 |
res.append(d) |
| 68 |
return res |
| 69 |
|
| 70 |
|
| 71 |
class PredefinedRowfilterTest(testhelpers.VerboseTest): |
| 72 |
def testOnIndex(self): |
| 73 |
dd = testhelpers.getTestRD().getById("expandOnIndex") |
| 74 |
data = rsc.makeData(dd, forceSource=[{"b": 3, "c": 4, "a": "eins"}]) |
| 75 |
self.assertEqual(data.getPrimaryTable().rows, |
| 76 |
[{'a': 'eins', 'c': 4, 'b': 3, 'd': 3}, |
| 77 |
{'a': 'eins', 'c': 4, 'b': 3, 'd': 4}]) |
| 78 |
|
| 79 |
def testExpandComma(self): |
| 80 |
dd = testhelpers.getTestRD().getById("expandComma") |
| 81 |
data = rsc.makeData(dd, forceSource=[{"stuff": "x,yz,foo, bar ", |
| 82 |
"b": 23}, {"stuff":"quux", "b": 3}]) |
| 83 |
self.assertEqual(data.getPrimaryTable().rows, [ |
| 84 |
{'a': 'x', 'b': 23}, {'a': 'yz', 'b': 23}, |
| 85 |
{'a': 'foo', 'b': 23}, {'a': 'bar', 'b': 23}, |
| 86 |
{'a': 'quux', 'b': 3}]) |
| 87 |
|
| 88 |
def testStandardPreviewPath(self): |
| 89 |
dd = testhelpers.getTestRD().getById("productimport-skip") |
| 90 |
res = set() |
| 91 |
for source in dd.iterSources(None): |
| 92 |
for row in dd.grammar.parse(source, None): |
| 93 |
res.add(row["prodtblPreview"]) |
| 94 |
|
| 95 |
self.assertEqual(set(str(p) for p in res), |
| 96 |
set(['prefoo/ZGF0YS9hLmltcA==', |
| 97 |
'prefoo/ZGF0YS9iLmltcA=='])) |
| 98 |
|
| 99 |
|
| 100 |
class SequencedRowfilterTest(testhelpers.VerboseTest): |
| 101 |
def _makeGrammar(self, rowgenDefs): |
| 102 |
return base.parseFromString(rscdef.getGrammar("dictlistGrammar"), |
| 103 |
"<dictlistGrammar>%s</dictlistGrammar>"%rowgenDefs) |
| 104 |
|
| 105 |
def _getProcessedFor(self, filterDefs, input): |
| 106 |
g = self._makeGrammar(filterDefs) |
| 107 |
res = getCleaned(g.parse(input)) |
| 108 |
return res |
| 109 |
|
| 110 |
def testSimplePipe(self): |
| 111 |
res = self._getProcessedFor(""" |
| 112 |
<rowfilter><code> |
| 113 |
row["output"] = row["input"]+1 |
| 114 |
del row["input"] |
| 115 |
yield row |
| 116 |
</code></rowfilter> |
| 117 |
<rowfilter><code> |
| 118 |
row["processed"] = row["output"]*row["output"] |
| 119 |
yield row |
| 120 |
</code></rowfilter>""", [{"input": 2}]) |
| 121 |
self.assertEqual(res, [{"output":3, "processed":9}]) |
| 122 |
|
| 123 |
def testForking(self): |
| 124 |
res = self._getProcessedFor(""" |
| 125 |
<rowfilter><code> |
| 126 |
b = row["input"] |
| 127 |
del row["input"] |
| 128 |
row["output"] = b |
| 129 |
yield row.copy() |
| 130 |
row["output"] += b |
| 131 |
yield row |
| 132 |
</code></rowfilter> |
| 133 |
<rowfilter><code> |
| 134 |
row["processed"] = row["output"]*row["output"] |
| 135 |
yield row.copy() |
| 136 |
row["processed"] = row["processed"]*row["output"] |
| 137 |
yield row |
| 138 |
</code></rowfilter>""", [{"input": 2}]) |
| 139 |
self.assertEqual(res, [ |
| 140 |
{"output":2, "processed":4}, |
| 141 |
{"output":2, "processed":8}, |
| 142 |
{"output":4, "processed":16}, |
| 143 |
{"output":4, "processed":64},]) |
| 144 |
|
| 145 |
|
| 146 |
class _MacroExpandedStuff(testhelpers.TestResource): |
| 147 |
def make(self, ignored): |
| 148 |
from gavo import rscdesc |
| 149 |
rd = base.parseFromString(rscdesc.RD, r"""<resource schema="test" |
| 150 |
resdir=""> |
| 151 |
<table id="foo"><column name="prodtblPath" type="text"/> |
| 152 |
<column name="prodtblPreview" type="text"/> |
| 153 |
<column name="srcstem" type="text"/> |
| 154 |
<column name="rootless" type="text"/> |
| 155 |
<column name="previewDir" type="text"/> |
| 156 |
<column name="prodtblEmbargo" type="timestamp"/> |
| 157 |
<column name="moddlp" type="text"/> |
| 158 |
</table> |
| 159 |
<data id="i"> |
| 160 |
<property name="previewDir">previews</property> |
| 161 |
<sources pattern="data/ex.fits"/> |
| 162 |
<fitsProdGrammar> |
| 163 |
<rowfilter procDef="//products#define"> |
| 164 |
<bind name="table">"foo"</bind> |
| 165 |
<bind name="path">\fullDLURL{echdl}</bind> |
| 166 |
<bind name="preview">\splitPreviewPath{.jpeg}</bind> |
| 167 |
<bind name="embargo">\sourceDate</bind> |
| 168 |
</rowfilter> |
| 169 |
<rowfilter name="morestuff"> |
| 170 |
<code> |
| 171 |
row["somethingelse"] = 23 |
| 172 |
row.update({ |
| 173 |
"srcstem": \srcstem, |
| 174 |
"previewDir": "\property{previewDir}", |
| 175 |
"rootless": \rootlessPath, |
| 176 |
"moddlp": \fullDLURL{echdl}{str(@somethingelse)} |
| 177 |
}) |
| 178 |
yield row |
| 179 |
</code> |
| 180 |
</rowfilter> |
| 181 |
</fitsProdGrammar> |
| 182 |
<make table="foo"/></data> |
| 183 |
<service id="echdl"><datalinkCore/></service></resource>""") |
| 184 |
rd.sourceId = "glob/bob" |
| 185 |
return rsc.makeData(rd.getById("i")).getPrimaryTable().rows |
| 186 |
|
| 187 |
|
| 188 |
class MacroTest(testhelpers.VerboseTest): |
| 189 |
resources = [("rows", _MacroExpandedStuff())] |
| 190 |
|
| 191 |
def testDLURL(self): |
| 192 |
self.assertEqual(self.rows[0]["prodtblPath"], |
| 193 |
"http://localhost:8080/glob/bob/echdl/dlget" |
| 194 |
"?ID=ivo%3A%2F%2Fx-testing%2F~%3Fdata%2Fex.fits") |
| 195 |
|
| 196 |
def testTwoArgDLURL(self): |
| 197 |
self.assertEqual(self.rows[0]["moddlp"], |
| 198 |
"http://localhost:8080/glob/bob/echdl/dlget?ID=ivo%3A%2F%2Fx" |
| 199 |
"-testing%2F~%3F23") |
| 200 |
|
| 201 |
def testSplitPreview(self): |
| 202 |
self.assertEqual(self.rows[0]["prodtblPreview"], |
| 203 |
"previews/data/ex.fits.jpeg") |
| 204 |
|
| 205 |
def testSourceDate(self): |
| 206 |
# should we force the source date to something we can test here? |
| 207 |
self.assertTrue(self.rows[0]["prodtblEmbargo"].year>2010, |
| 208 |
"Ancient files on disk?") |
| 209 |
|
| 210 |
def testSrcstem(self): |
| 211 |
self.assertEqual(self.rows[0]["srcstem"], "ex") |
| 212 |
|
| 213 |
def testPreviewDir(self): |
| 214 |
self.assertEqual(self.rows[0]["previewDir"], "previews") |
| 215 |
|
| 216 |
def testRootless(self): |
| 217 |
self.assertEqual(self.rows[0]["rootless"], "data/ex.fits") |
| 218 |
|
| 219 |
ignoreTestData = [ |
| 220 |
{'a': 'xy', 'b': 'cc', 'd': 'yok'}, |
| 221 |
{'a': 'xy', 'b': 'DD'}, |
| 222 |
{'a': 'zz', 'b': ''}, |
| 223 |
] |
| 224 |
|
| 225 |
class IgnoreTests(testhelpers.VerboseTest): |
| 226 |
def _makeGrammar(self, ignoreClauses): |
| 227 |
return base.parseFromString(rscdef.getGrammar("dictlistGrammar"), |
| 228 |
"<dictlistGrammar><ignoreOn>%s</ignoreOn></dictlistGrammar>"% |
| 229 |
ignoreClauses) |
| 230 |
|
| 231 |
def _makeBailingGrammar(self, ignoreClauses): |
| 232 |
return base.parseFromString(rscdef.getGrammar("dictlistGrammar"), |
| 233 |
"<dictlistGrammar><ignoreOn bail='True'>%s</ignoreOn></dictlistGrammar>"% |
| 234 |
ignoreClauses) |
| 235 |
|
| 236 |
def _assertResultLen(self, ignoreClauses, expectedLength): |
| 237 |
res = list(self._makeGrammar(ignoreClauses).parse(ignoreTestData)) |
| 238 |
self.assertEqual(len(res), expectedLength, |
| 239 |
"%s yielded %s, expected %d rows"%(ignoreClauses, res, expectedLength)) |
| 240 |
|
| 241 |
def testKeyIs(self): |
| 242 |
self._assertResultLen('<keyIs key="a" value="xy"/>', 1) |
| 243 |
self._assertResultLen('<keyIs key="a" value="zz"/>', 2) |
| 244 |
self._assertResultLen('<keyIs key="a" value=""/>', 3) |
| 245 |
self._assertResultLen('<keyIs key="b" value=""/>', 2) |
| 246 |
self._assertResultLen('<keyIs key="d" value="yok"/>', 2) |
| 247 |
|
| 248 |
def testKeyPresent(self): |
| 249 |
self._assertResultLen('<keyPresent key="a"/>', 0) |
| 250 |
self._assertResultLen('<keyPresent key="b"/>', 0) |
| 251 |
self._assertResultLen('<keyPresent key="d"/>', 2) |
| 252 |
self._assertResultLen('<keyPresent key="yikes"/>', 3) |
| 253 |
|
| 254 |
def testTriggerSeq(self): |
| 255 |
self._assertResultLen('<keyPresent key="d"/><keyIs key="b" value=""/>' |
| 256 |
, 1) |
| 257 |
|
| 258 |
def testNot(self): |
| 259 |
self._assertResultLen('<not><keyPresent key="a"/></not>', 3) |
| 260 |
self._assertResultLen('<not><keyPresent key="d"/></not>', 1) |
| 261 |
self._assertResultLen('<not><keyPresent key="d"/>' |
| 262 |
'<keyIs key="b" value=""/></not>', 2) |
| 263 |
|
| 264 |
def testAnd(self): |
| 265 |
self._assertResultLen('<and><keyIs key="a" value="xy"/>' |
| 266 |
'<keyIs key="b" value="DD"/></and>', 2) |
| 267 |
|
| 268 |
def testBail(self): |
| 269 |
g = self._makeBailingGrammar('<keyMissing key="d"/>') |
| 270 |
def parseAll(): |
| 271 |
return list(g.parse(ignoreTestData)) |
| 272 |
self.assertRaises(rscdef.TriggerPulled, parseAll) |
| 273 |
|
| 274 |
def testBailNot(self): |
| 275 |
g = self._makeBailingGrammar('<keyMissing key="a"/>') |
| 276 |
list(g.parse(ignoreTestData)) |
| 277 |
|
| 278 |
|
| 279 |
class EmbeddedGrammarTest(testhelpers.VerboseTest): |
| 280 |
def testSimple(self): |
| 281 |
from gavo import rscdesc |
| 282 |
rd = base.parseFromString(rscdesc.RD, |
| 283 |
"""<resource schema="test"><data id="fake"><embeddedGrammar> |
| 284 |
<iterator><code> |
| 285 |
yield {'x': 1, 'y': 2} |
| 286 |
yield {'x': 2, 'y': 2} |
| 287 |
</code></iterator></embeddedGrammar></data></resource>""") |
| 288 |
self.assertEqual(getCleaned(rd.dds[0].grammar.parse(None)), |
| 289 |
[{'y': 2, 'x': 1}, {'y': 2, 'x': 2}]) |
| 290 |
|
| 291 |
def testErrorBehaviour(self): |
| 292 |
from gavo import rscdesc |
| 293 |
rd = base.parseFromString(rscdesc.RD, |
| 294 |
"""<resource schema="test"> |
| 295 |
<table id="bla"><column name="foo" type="text"/></table> |
| 296 |
<data id="fake"><embeddedGrammar> |
| 297 |
<iterator><code> |
| 298 |
for prefix in ["vor", "nach"]: |
| 299 |
self.location = f"{self.sourceToken}, {prefix}" |
| 300 |
yield {"foo": prefix+self.sourceToken} |
| 301 |
UndefinedName |
| 302 |
</code></iterator></embeddedGrammar><make table="bla"/> |
| 303 |
</data></resource>""") |
| 304 |
self.assertRaisesWithMsg(base.SourceParseError, |
| 305 |
'At sicht, vor: NameError("name \'UndefinedName\' is not defined")', |
| 306 |
rsc.makeData, |
| 307 |
(rd.dds[0],), forceSource="sicht") |
| 308 |
|
| 309 |
|
| 310 |
class KVGrammarTest(testhelpers.VerboseTest): |
| 311 |
def testSimple(self): |
| 312 |
grammar = base.parseFromString(rscdef.getGrammar("keyValueGrammar"), |
| 313 |
r'<keyValueGrammar commentPattern="--.*?\*/" enc="utf-8"/>') |
| 314 |
with TestFile("a=b\nc=2 --nothing*/\n" |
| 315 |
"wonkö:Närd".encode("utf-8")) as f: |
| 316 |
rec = list(grammar.parse(f))[0] |
| 317 |
self.assertEqual(rec["a"], 'b') |
| 318 |
self.assertEqual(rec["c"], '2') |
| 319 |
self.assertEqual(rec["wonkö"], 'Närd') |
| 320 |
|
| 321 |
def testPairs(self): |
| 322 |
grammar = base.parseFromString(rscdef.getGrammar("keyValueGrammar"), |
| 323 |
'<keyValueGrammar kvSeparators="/" pairSeparators="%"' |
| 324 |
' yieldPairs="True"/>') |
| 325 |
with TestFile("a/b%c/d") as f: |
| 326 |
recs = [(v['key'], v['value']) |
| 327 |
for v in grammar.parse(f)] |
| 328 |
self.assertEqual(recs, [('a', 'b'), ('c', 'd')]) |
| 329 |
|
| 330 |
def testError(self): |
| 331 |
self.assertRaisesWithMsg(base.LiteralParseError, |
| 332 |
"At IO:'<keyValueGrammar commentPattern=\"**\"/>', (1, 0):" |
| 333 |
" '**' is not a valid value for commentPattern", |
| 334 |
base.parseFromString, |
| 335 |
(rscdef.getGrammar("keyValueGrammar"), |
| 336 |
'<keyValueGrammar commentPattern="**"/>')) |
| 337 |
|
| 338 |
|
| 339 |
class CSVGrammarTest(testhelpers.VerboseTest): |
| 340 |
def testSimple(self): |
| 341 |
grammar = base.parseFromString(rscdef.getGrammar("csvGrammar"), |
| 342 |
'<csvGrammar/>') |
| 343 |
with TestFile("la,le,lu\n1, 2, schaut") as f: |
| 344 |
recs = getCleaned(grammar.parse(f)) |
| 345 |
self.assertEqual(recs, |
| 346 |
[{"la": '1', "le": ' 2', "lu": " schaut"}]) |
| 347 |
|
| 348 |
def testStrip(self): |
| 349 |
grammar = base.parseFromString(rscdef.getGrammar("csvGrammar"), |
| 350 |
'<csvGrammar strip="True"/>') |
| 351 |
with TestFile("la,le,lu\n1, 2, schaut") as f: |
| 352 |
recs = getCleaned(grammar.parse(f)) |
| 353 |
self.assertEqual(recs, |
| 354 |
[{"la": '1', "le": '2', "lu": "schaut"}]) |
| 355 |
|
| 356 |
def testNames(self): |
| 357 |
grammar = base.parseFromString(rscdef.getGrammar("csvGrammar"), |
| 358 |
'<csvGrammar names="col1, col2, col3"/>') |
| 359 |
with TestFile("la,le,lu\n1,2,schaut") as f: |
| 360 |
recs = getCleaned(grammar.parse(f)) |
| 361 |
self.assertEqual(recs, [ |
| 362 |
{"col1": "la", "col2": "le", "col3": "lu"}, |
| 363 |
{"col1": '1', "col2": '2', "col3": "schaut"}]) |
| 364 |
|
| 365 |
def testSkipLines(self): |
| 366 |
grammar = base.parseFromString(rscdef.getGrammar("csvGrammar"), |
| 367 |
'<csvGrammar topIgnoredLines="3"/>') |
| 368 |
with TestFile( |
| 369 |
"There's\nsome\njunk at the top here\nla,le,lu\n1,2,schaut") as f: |
| 370 |
recs = getCleaned(grammar.parse(f)) |
| 371 |
self.assertEqual(recs, [ |
| 372 |
{"la": '1', "le": '2', "lu": "schaut"}]) |
| 373 |
|
| 374 |
def testWithPreFilter(self): |
| 375 |
grammar = base.parseFromString(rscdef.getGrammar("csvGrammar"), |
| 376 |
'<csvGrammar preFilter="zcat"/>') |
| 377 |
with TestFile( |
| 378 |
b'\x1f\x8b\x08\x08\xb7\xd2\xa4U\x00\x03zw.txt\x00\xcbI\xd4\xc9I' |
| 379 |
b'\xd5\xc9)\xe52\xd41\xd2)N\xceH,-\xe1\x02\x00S@8\x1f\x14' |
| 380 |
b'\x00\x00\x00') as f: |
| 381 |
recs = getCleaned(grammar.parse(f)) |
| 382 |
self.assertEqual(recs, [ |
| 383 |
{"la": '1', "le": '2', "lu": "schaut"}]) |
| 384 |
|
| 385 |
|
| 386 |
class ColDefTest(testhelpers.VerboseTest): |
| 387 |
def testSimple(self): |
| 388 |
g = base.parseFromString(columngrammar.ColumnGrammar, |
| 389 |
'<columnGrammar colDefs="a:1 B:2-5 C_dfoo:4 _gobble:6-8"/>') |
| 390 |
with TestFile("abcdefghijklmnoq") as f: |
| 391 |
res = getCleaned(g.parse(f))[0] |
| 392 |
self.assertEqual(res, {'a': 'a', 'C_dfoo': 'd', 'B': 'bcde', |
| 393 |
'_gobble': 'fgh'}) |
| 394 |
|
| 395 |
def testFunkyWhite(self): |
| 396 |
g = base.parseFromString(columngrammar.ColumnGrammar, |
| 397 |
'<columnGrammar colDefs="a :1 B: 2 - 5 C_dfoo: 4 _gobble : 6 -8"/>') |
| 398 |
with TestFile("abcdefghijklmnoq") as f: |
| 399 |
res = getCleaned(g.parse(f))[0] |
| 400 |
self.assertEqual(res, {'a': 'a', 'C_dfoo': 'd', 'B': 'bcde', |
| 401 |
'_gobble': 'fgh'}) |
| 402 |
|
| 403 |
def testHalfopen(self): |
| 404 |
g = base.parseFromString(columngrammar.ColumnGrammar, |
| 405 |
'<columnGrammar><colDefs>a:5- B:-5</colDefs></columnGrammar>') |
| 406 |
with TestFile("abcdefg") as f: |
| 407 |
res = getCleaned(g.parse(f))[0] |
| 408 |
self.assertEqual(res, {'a': 'efg', 'B': 'abcde'}) |
| 409 |
|
| 410 |
def testBeauty(self): |
| 411 |
g = base.parseFromString(columngrammar.ColumnGrammar, |
| 412 |
"""<columnGrammar><colDefs> |
| 413 |
a: 5- |
| 414 |
B: -5 |
| 415 |
gnugga: 1-2 |
| 416 |
</colDefs></columnGrammar>""") |
| 417 |
with TestFile("abcdefg") as f: |
| 418 |
res = getCleaned(g.parse(f))[0] |
| 419 |
self.assertEqual(res, {'a': 'efg', 'B': 'abcde', 'gnugga': 'ab'}) |
| 420 |
|
| 421 |
def testErrorBadChar(self): |
| 422 |
self.assertRaisesWithMsg(base.LiteralParseError, |
| 423 |
"At IO:'<columnGrammar><colDefs>a:5-% B:-5</colDefs></columnG...', (1, 34):" |
| 424 |
" 'a:5-% B:-5' is not a valid value for colDefs", |
| 425 |
base.parseFromString, (columngrammar.ColumnGrammar, |
| 426 |
'<columnGrammar><colDefs>a:5-% B:-5</colDefs></columnGrammar>')) |
| 427 |
|
| 428 |
def testErrorNiceHint(self): |
| 429 |
try: |
| 430 |
base.parseFromString(columngrammar.ColumnGrammar, |
| 431 |
'<columnGrammar><colDefs>a:5- B:c</colDefs></columnGrammar>') |
| 432 |
except base.LiteralParseError as ex: |
| 433 |
self.assertTrue(ex.hint.endswith( |
| 434 |
"Expected end of text, found 'B' (at char 5), (line:1, col:6)")) |
| 435 |
else: |
| 436 |
self.fail("LiteralParseError not raised") |
| 437 |
|
| 438 |
|
| 439 |
class ColumnGrammarTest(testhelpers.VerboseTest): |
| 440 |
def testWithComment(self): |
| 441 |
g = base.parseFromString(columngrammar.ColumnGrammar, |
| 442 |
'<columnGrammar commentIntroducer="#"><colDefs>a:1-</colDefs>' |
| 443 |
'</columnGrammar>') |
| 444 |
with TestFile("#Anfang\nMitte\n#Ende") as f: |
| 445 |
res = list(g.parse(f)) |
| 446 |
self.assertEqual(testhelpers.pickSingle(res)['a'], 'Mitte') |
| 447 |
|
| 448 |
def testWithoutComment(self): |
| 449 |
g = base.parseFromString(columngrammar.ColumnGrammar, |
| 450 |
'<columnGrammar><colDefs>a:1-</colDefs>' |
| 451 |
'</columnGrammar>') |
| 452 |
with TestFile("#Anfang\nMitte\n#Ende") as f: |
| 453 |
res = list(g.parse(f)) |
| 454 |
self.assertEqual(len(res), 3) |
| 455 |
self.assertEqual(res[0]['a'], "#Anfang") |
| 456 |
|
| 457 |
def testWithPreFilterAndEnc(self): |
| 458 |
grammar = base.parseFromString(rscdef.getGrammar("columnGrammar"), |
| 459 |
"""<columnGrammar preFilter="zcat" enc="utf-8"> |
| 460 |
<colDefs>a: 1-4</colDefs></columnGrammar>""") |
| 461 |
with TestFile(b'\x1f\x8b\x08\x08\x02ps^\x00\x03x\x00s9\xbc-%5\xe7' |
| 462 |
b'\xdad.\x85\x93\x13\xcfM\xe2\x02\x00Y\xd9\xa1S\x0f\x00\x00\x00') as f: |
| 463 |
recs = getCleaned(grammar.parse(f)) |
| 464 |
self.assertEqual(recs, [ |
| 465 |
{"a": "Döde"}, |
| 466 |
{"a": "ɑΒ"}]) |
| 467 |
|
| 468 |
def testEndMarker(self): |
| 469 |
grammar = base.parseFromString(rscdef.getGrammar("columnGrammar"), |
| 470 |
"""<columnGrammar endMarker="schlussjetzt $"> |
| 471 |
<colDefs>a: 1-4</colDefs></columnGrammar>""") |
| 472 |
with TestFile("schluss jetzt\nschlussjetzt nicht\n" |
| 473 |
" schlussjetzt wieder nicht\nschlussjetzt \ndasnicht\n") as f: |
| 474 |
recs = getCleaned(grammar.parse(f)) |
| 475 |
self.assertEqual(recs, |
| 476 |
[{'a': 'schl'}, {'a': 'schl'}, {'a': 'sc'}]) |
| 477 |
|
| 478 |
|
| 479 |
class BinaryRecordTest(testhelpers.VerboseTest): |
| 480 |
def testTypes(self): |
| 481 |
brd = base.parseFromString(binarygrammar.BinaryRecordDef, |
| 482 |
"""<binaryRecordDef binfmt="packed"> |
| 483 |
chr(1s) fong(12s) b(b) B(B) h(h) H(H) i(i) I(I) q(q) Q(Q) |
| 484 |
f(f) d(d)</binaryRecordDef>""") |
| 485 |
self.assertEqual(brd.structFormat, "=1s12sbBhHiIqQfd") |
| 486 |
self.assertEqual(brd.recordLength, 55) |
| 487 |
|
| 488 |
def testBadIdentifier(self): |
| 489 |
self.assertRaises(base.LiteralParseError, |
| 490 |
base.parseFromString, binarygrammar.BinaryRecordDef, |
| 491 |
"<binaryRecordDef>22s(d)</binaryRecordDef>") |
| 492 |
|
| 493 |
def testBadCode(self): |
| 494 |
self.assertRaises(base.LiteralParseError, |
| 495 |
base.parseFromString, binarygrammar.BinaryRecordDef, |
| 496 |
"<binaryRecordDef>x(P)</binaryRecordDef>") |
| 497 |
|
| 498 |
def testNativeTypes(self): |
| 499 |
brd = base.parseFromString(binarygrammar.BinaryRecordDef, |
| 500 |
"<binaryRecordDef>c(1s)s(i)t(d)</binaryRecordDef>") |
| 501 |
self.assertEqual(brd.structFormat, "1sid") |
| 502 |
self.assertFalse(brd.recordLength==13, "You platform doesn't pack?") |
| 503 |
|
| 504 |
|
| 505 |
class BinaryGrammarTest(testhelpers.VerboseTest): |
| 506 |
plainTestData = [(42, 0.25), (-30, 40.)] |
| 507 |
plainExpectedResult = [{'s': 42, 't': 0.25}, {'s': -30, 't': 40.0}] |
| 508 |
|
| 509 |
def testUnarmoredParse(self): |
| 510 |
with TestFile(b"u"*20+b"".join(struct.pack("id", *r) |
| 511 |
for r in self.plainTestData)) as f: |
| 512 |
grammar = base.parseFromString(binarygrammar.BinaryGrammar, |
| 513 |
"""<binaryGrammar skipBytes="20"><binaryRecordDef>s(i)t(d) |
| 514 |
</binaryRecordDef></binaryGrammar>""") |
| 515 |
self.assertEqual( |
| 516 |
getCleaned(grammar.parse(f)), |
| 517 |
self.plainExpectedResult) |
| 518 |
|
| 519 |
def testNetworkBinfmt(self): |
| 520 |
with TestFile(b"".join(struct.pack("!id", *r) |
| 521 |
for r in self.plainTestData)) as inputFile: |
| 522 |
grammar = base.parseFromString(binarygrammar.BinaryGrammar, |
| 523 |
"""<binaryGrammar><binaryRecordDef binfmt="big">s(i)t(d) |
| 524 |
</binaryRecordDef></binaryGrammar>""") |
| 525 |
self.assertEqual( |
| 526 |
getCleaned(grammar.parse(inputFile)), |
| 527 |
self.plainExpectedResult) |
| 528 |
|
| 529 |
|
| 530 |
def testFortranParse(self): |
| 531 |
|
| 532 |
def doFortranArmor(data): |
| 533 |
return struct.pack(b"i%dsi"%len(data), len(data), data, len(data)) |
| 534 |
|
| 535 |
with TestFile(b"".join(doFortranArmor(struct.pack("id", *r)) |
| 536 |
for r in self.plainTestData)) as inputFile: |
| 537 |
grammar = base.parseFromString(binarygrammar.BinaryGrammar, |
| 538 |
"""<binaryGrammar armor="fortran"><binaryRecordDef>s(i)t(d) |
| 539 |
</binaryRecordDef></binaryGrammar>""") |
| 540 |
self.assertEqual( |
| 541 |
getCleaned(grammar.parse(inputFile)), |
| 542 |
self.plainExpectedResult) |
| 543 |
|
| 544 |
|
| 545 |
class FITSProdGrammarTest(testhelpers.VerboseTest): |
| 546 |
|
| 547 |
sample = os.path.join(base.getConfig("inputsDir"), "data", "ex.fits") |
| 548 |
grammarT = fitsprodgrammar.FITSProdGrammar |
| 549 |
|
| 550 |
def _getParse(self, grammarDef): |
| 551 |
grammar = base.parseFromString(self.grammarT, grammarDef) |
| 552 |
return list(grammar.parse(self.sample))[0] |
| 553 |
|
| 554 |
def _assertBasicFieldsPresent(self, d): |
| 555 |
self.assertEqual(len(d), 104) |
| 556 |
self.assertEqual(d["EXTEND"], True) |
| 557 |
self.assertEqual(d["OBSERVER"], "M.Wolf") |
| 558 |
self.assertEqual(d["LATPOLE"], 0.0) |
| 559 |
self.assertTrue("PLATE_ID" in d) |
| 560 |
|
| 561 |
def testBasic(self): |
| 562 |
self._assertBasicFieldsPresent( |
| 563 |
self._getParse("""<fitsProdGrammar qnd="False"/>""")) |
| 564 |
|
| 565 |
def testBasicQnD(self): |
| 566 |
self._assertBasicFieldsPresent( |
| 567 |
self._getParse("""<fitsProdGrammar/>""")) |
| 568 |
|
| 569 |
def testNameMapping(self): |
| 570 |
d = self._getParse("""<fitsProdGrammar><mapKeys><map |
| 571 |
dest="blind">EXPTIME</map></mapKeys></fitsProdGrammar>""") |
| 572 |
self.assertEqual(d["blind"], '10801') |
| 573 |
|
| 574 |
def testHDUsField(self): |
| 575 |
d = self._getParse("""<fitsProdGrammar hdusField="__HDUS"/>""") |
| 576 |
self.assertEqual(d["__HDUS"][0].data[0][0], 7896.0) |
| 577 |
|
| 578 |
|
| 579 |
class FITSTableGrammarTest(testhelpers.VerboseTest): |
| 580 |
def testBasic(self): |
| 581 |
t = table.Table([ |
| 582 |
table.MaskedColumn([1, 0], mask=[False, True]), |
| 583 |
table.MaskedColumn([2.0, 0], mask=[False, True]), |
| 584 |
table.MaskedColumn(['foo', ''], mask=[False, True])], |
| 585 |
names=["an_int", "a_float", "a_string"], |
| 586 |
dtype=["i4", "f8", str]) |
| 587 |
|
| 588 |
with utils.sandbox(): |
| 589 |
t.write("tmp.fits", format="fits") |
| 590 |
grammar = base.parseFromString(fitstablegrammar.FITSTableGrammar, |
| 591 |
"<fitsTableGrammar/>") |
| 592 |
res = list(grammar.parse("tmp.fits")) |
| 593 |
|
| 594 |
self.assertEqual(res[0]["an_int"], 1) |
| 595 |
self.assertEqual(res[0]["a_float"], 2.0) |
| 596 |
self.assertEqual(res[0]["a_string"], 'foo') |
| 597 |
|
| 598 |
self.assertEqual(res[1]["an_int"], None) |
| 599 |
self.assertEqual(res[1]["a_float"], None) |
| 600 |
self.assertEqual(res[1]["a_string"], None) |
| 601 |
|
| 602 |
|
| 603 |
class ReGrammarTest(testhelpers.VerboseTest): |
| 604 |
def testBadInputRejection(self): |
| 605 |
grammar = base.parseFromString(regrammar.REGrammar, |
| 606 |
"""<reGrammar names="a,b"/>""") |
| 607 |
with TestFile("1 2\n3") as f: |
| 608 |
self.assertRaisesWithMsg(base.SourceParseError, |
| 609 |
"At line 2: 1 fields found, expected 2", |
| 610 |
lambda: list(grammar.parse(f)), |
| 611 |
()) |
| 612 |
|
| 613 |
def testComment(self): |
| 614 |
grammar = base.parseFromString(regrammar.REGrammar, |
| 615 |
"""<reGrammar names="a,b" commentPat="(?m)^#.*$"/>""") |
| 616 |
with TestFile("1 2\n# more data\n3 2\n#end of file.\n") as f: |
| 617 |
self.assertEqual( |
| 618 |
getCleaned(grammar.parse(f)), |
| 619 |
[{'a': '1', 'b': '2'}, {'a': '3', 'b': '2'}]) |
| 620 |
|
| 621 |
def testNoComment(self): |
| 622 |
grammar = base.parseFromString(regrammar.REGrammar, |
| 623 |
"""<reGrammar names="a,b"/>""") |
| 624 |
with TestFile("1 2\n#more data\n3 2\n#endof file.\n") as f: |
| 625 |
self.assertEqual( |
| 626 |
getCleaned(grammar.parse(f)), [ |
| 627 |
{'a': '1', 'b': '2'}, |
| 628 |
{'a': '#more', 'b': 'data'}, |
| 629 |
{'a': '3', 'b': '2'}, |
| 630 |
{'a': '#endof', 'b': 'file.'}]) |
| 631 |
|
| 632 |
def testIgnoredEnd(self): |
| 633 |
grammar = base.parseFromString(regrammar.REGrammar, |
| 634 |
r"""<reGrammar names="a,b" recordSep="\\\\" commentPat="(?m)^\\.*$"/>""") |
| 635 |
with TestFile("1\n2\\\\\n3 4\\\\\n\\ignore all this\n\n\\and this.\n" |
| 636 |
) as f: |
| 637 |
self.assertEqual( |
| 638 |
getCleaned(grammar.parse(f)), [ |
| 639 |
{'a': '1', 'b': '2'}, |
| 640 |
{'a': '3', 'b': '4'}]) |
| 641 |
|
| 642 |
def testLineCount(self): |
| 643 |
grammar = base.parseFromString(regrammar.REGrammar, |
| 644 |
r"""<reGrammar names="a,b" recordSep="//" fieldSep=","/>""") |
| 645 |
with TestFile("a,b//c,d//e\n,f//g,h//j//\n1,d//\n") as f: |
| 646 |
self.assertRaisesWithMsg(base.SourceParseError, |
| 647 |
"At line 2: 1 fields found, expected 2", |
| 648 |
list, |
| 649 |
(grammar.parse(f),)) |
| 650 |
|
| 651 |
|
| 652 |
class FilteredInputTest(testhelpers.VerboseTest): |
| 653 |
def testSimple(self): |
| 654 |
with testtricks.testFile("filterInput", "ab\ncd\nef\n") as srcName: |
| 655 |
f = common.FilteredInputFile("tac", open(srcName, "rb")) |
| 656 |
self.assertEqual(f.read(), b"ef\ncd\nab\n") |
| 657 |
f.close() |
| 658 |
|
| 659 |
def testLargeOutput(self): |
| 660 |
data = " \n"*200000 |
| 661 |
with testtricks.testFile( |
| 662 |
"filterInput", data, writeGz=True) as srcName: |
| 663 |
f = common.FilteredInputFile("zcat", open(srcName, "rb")) |
| 664 |
result = f.read() |
| 665 |
self.assertEqual(result, data.encode("ascii")) |
| 666 |
f.close() |
| 667 |
|
| 668 |
def testLargeInput(self): |
| 669 |
with TestFile(" \n"*200000) as inF: |
| 670 |
f = common.FilteredInputFile("gzip", inF) |
| 671 |
result = f.read() |
| 672 |
self.assertEqual(len(result), 10216) |
| 673 |
f.close() |
| 674 |
|
| 675 |
def testFailedCommand(self): |
| 676 |
with TestFile("abc") as outerF: |
| 677 |
f = common.FilteredInputFile("verpotshket", outerF, |
| 678 |
silent=True) |
| 679 |
self.assertRaisesWithMsg(IOError, |
| 680 |
"Child exited with return code 127", |
| 681 |
f.read, |
| 682 |
()) |
| 683 |
f.close() |
| 684 |
|
| 685 |
def testReadWithSizeAndClose(self): |
| 686 |
with TestFile("abc") as outerF: |
| 687 |
f = common.FilteredInputFile("yes", outerF, silent=True) |
| 688 |
self.assertEqual(b"y\n"*10, f.read(20)) |
| 689 |
f.close() |
| 690 |
self.assertEqual(f.process.returncode, -15) |
| 691 |
|
| 692 |
def testReadline(self): |
| 693 |
with TestFile(base64.b64decode( |
| 694 |
"H4sIAFcmV1AAA0vkSgQCMDHcABcXAN3p7JLdAAAA")) as outerF: |
| 695 |
f = common.FilteredInputFile("zcat", outerF) |
| 696 |
self.assertEqual(f.readline(), b"a\n") |
| 697 |
self.assertEqual(f.readline(), b"aaaa\n") |
| 698 |
self.assertEqual(f.readline(), b"a"*212+b"\n") |
| 699 |
self.assertEqual(f.readline(), b"\n") |
| 700 |
self.assertEqual(f.readline(), b"") |
| 701 |
|
| 702 |
def testReadlineNoLF(self): |
| 703 |
with TestFile("AAAA\nBBBB") as outerF: |
| 704 |
f = common.FilteredInputFile("cat", outerF) |
| 705 |
self.assertEqual(f.readline(), b"AAAA\n") |
| 706 |
self.assertEqual(f.readline(), b"BBBB") |
| 707 |
|
| 708 |
|
| 709 |
class PDSGrammarTest(testhelpers.VerboseTest): |
| 710 |
def testLabelTypes(self): |
| 711 |
grammar = base.parseFromString(pdsgrammar.PDSGrammar, "<pdsGrammar/>") |
| 712 |
with TestFile( |
| 713 |
'PDS_VERSION_ID = PDS3\r\nLABEL_REVISION_NOTE = ' |
| 714 |
'"SE-MTC,09/07/2010"\r\n\r\n /* File format and length */' |
| 715 |
'\r\nPRODUCT_ID = "S1_00237390711"\r\nORIGINAL_PRODUCT_ID =' |
| 716 |
' "PSA7AD50"\r\nEND\r\n') as f: |
| 717 |
try: |
| 718 |
recs = list(grammar.parse(f)) |
| 719 |
except base.ReportableError: |
| 720 |
# PyPDS probably missing, skip this test |
| 721 |
return |
| 722 |
|
| 723 |
self.assertEqual( |
| 724 |
testhelpers.pickSingle(recs)["PRODUCT_ID"], |
| 725 |
'"S1_00237390711"') |
| 726 |
|
| 727 |
|
| 728 |
class ContextGrammarTest(testhelpers.VerboseTest): |
| 729 |
def testCaseMess(self): |
| 730 |
grammar = base.parseFromString(svcs.ContextGrammar, |
| 731 |
"""<contextGrammar inputTD="data/cores#knok"> |
| 732 |
<inputKey name="UPPER"/> |
| 733 |
<inputKey name="UppER"/> |
| 734 |
<inputKey name="lower"/> |
| 735 |
</contextGrammar>""") |
| 736 |
ri = grammar.parse({ |
| 737 |
"Lower": ["1"], |
| 738 |
"UPPER": "2", |
| 739 |
"UppER": "3",}) |
| 740 |
list(ri) |
| 741 |
res = ri.getParameters() |
| 742 |
self.assertEqual(res["UppER"], 3.0) |
| 743 |
self.assertEqual(res["UPPER"], 2.0) |
| 744 |
self.assertEqual(res["rV"], -4.0) |
| 745 |
self.assertEqual(res["lower"], 1.0) |
| 746 |
|
| 747 |
|
| 748 |
class XMLGrammarTest(testhelpers.VerboseTest): |
| 749 |
def testPathMogrification(self): |
| 750 |
with TestFile( |
| 751 |
"""<root><elem attr="foo">eins<child>bar</child>zwei |
| 752 |
<child>quux</child>drei</elem> |
| 753 |
<x:other xmlns:x="http://burp" what="a" noise="b"/> |
| 754 |
<other><child/></other> |
| 755 |
</root>""") as f: |
| 756 |
self.assertEqual( |
| 757 |
list(xmlgrammar.iterEventsCounting(f, True)), [ |
| 758 |
('root/elem/child', 'bar'), |
| 759 |
('root/elem/child[0]', 'quux'), |
| 760 |
('root/elem', 'einszwei drei'), |
| 761 |
('root/elem/@attr', 'foo'), |
| 762 |
('root/other', None), |
| 763 |
('root/other/@what', 'a'), |
| 764 |
('root/other/@noise', 'b'), |
| 765 |
('root/other[0]/child', None), |
| 766 |
('root/other[0]', None), |
| 767 |
('root', None)]) |
| 768 |
|
| 769 |
def testParsingOk(self): |
| 770 |
grammar = base.parseFromString(xmlgrammar.XMLGrammar, "<xmlGrammar/>") |
| 771 |
with TestFile(""" |
| 772 |
<foo><bar ct="0">one</bar><bar ct="1" delete="T"/></foo>""") as f: |
| 773 |
recs = list(grammar.parse(f)) |
| 774 |
del recs[0]["parser_"] |
| 775 |
self.assertEqual(recs, [{ |
| 776 |
'foo': None, |
| 777 |
'foo/bar': 'one', |
| 778 |
'foo/bar/@ct': '0', |
| 779 |
'foo/bar[0]': None, |
| 780 |
'foo/bar[0]/@ct': '1', |
| 781 |
'foo/bar[0]/@delete': 'T'}]) |
| 782 |
|
| 783 |
def testParsingError(self): |
| 784 |
grammar = base.parseFromString(xmlgrammar.XMLGrammar, "<xmlGrammar/>") |
| 785 |
with TestFile("""<foo/> |
| 786 |
</foo>""") as f: |
| 787 |
self.assertRaisesWithMsg(base.SourceParseError, |
| 788 |
# The repetition of the position in the message is somewhat |
| 789 |
# unfortunate, but I'm not sure how consistent position reporting |
| 790 |
# is in core lxml (and there's no way I can see to get at the |
| 791 |
# message only). The file name is added to the message in errhandle. |
| 792 |
"At (2, 5): Extra content at the end of the document, line 2, column 5", |
| 793 |
list, |
| 794 |
(grammar.parse(f),)) |
| 795 |
|
| 796 |
|
| 797 |
class MapKeysTest(testhelpers.VerboseTest): |
| 798 |
def testNoDupeKey(self): |
| 799 |
self.assertRaisesWithMsg(base.StructureError, |
| 800 |
"At IO:'<mapKeys>x: foo, y: bar, z: foo </mapKeys>', (4, 0):" |
| 801 |
" foo clobbers an existing source within the key map.", |
| 802 |
base.parseFromString, |
| 803 |
(common.MapKeys, "<mapKeys>x: foo,\ny: bar,\nz: foo\n</mapKeys>")) |
| 804 |
|
| 805 |
def testBadLiteral(self): |
| 806 |
self.assertRaisesWithMsg(base.LiteralParseError, |
| 807 |
"At IO:'<mapKeys>henk</mapKeys>', (1, 13):" |
| 808 |
" 'henk' is not a valid value for mapKeys", |
| 809 |
base.parseFromString, |
| 810 |
(common.MapKeys, "<mapKeys>henk</mapKeys>")) |
| 811 |
|
| 812 |
|
| 813 |
class ODBCGrammarTest(testhelpers.VerboseTest): |
| 814 |
def testNoQuery(self): |
| 815 |
self.assertRaisesWithMsg(base.StructureError, |
| 816 |
"At IO:'<odbcGrammar/>', (1, 14): Need to give at least one of" |
| 817 |
" query and makeQuery in an odbcGrammar.", |
| 818 |
base.parseFromString, |
| 819 |
(odbcgrammar.ODBCGrammar, |
| 820 |
"""<odbcGrammar/>""")) |
| 821 |
|
| 822 |
def testTooMuchQuery(self): |
| 823 |
self.assertRaisesWithMsg(base.StructureError, |
| 824 |
'At IO:\'<odbcGrammar query="something"> <makeQuery><code>pass...\',' |
| 825 |
' (2, 44): Cannot give both query and makeQuery in an odbcGrammar.', |
| 826 |
base.parseFromString, |
| 827 |
(odbcgrammar.ODBCGrammar, |
| 828 |
"""<odbcGrammar query="something"> |
| 829 |
<makeQuery><code>pass</code></makeQuery></odbcGrammar>""")) |
| 830 |
|
| 831 |
def testBasic(self): |
| 832 |
g = base.parseFromString(odbcgrammar.ODBCGrammar, |
| 833 |
"""<odbcGrammar query="select * from tap_schema.tables"/>""") |
| 834 |
profile = base.getDBProfile("untrustedquery") |
| 835 |
try: |
| 836 |
with testhelpers.testFile("odbcsource.txt", |
| 837 |
"DRIVER={PostgreSQL UNICODE};SERVER=%s;" |
| 838 |
"DATABASE=%s;UID=%s;PWD={%s}"%(profile.host, profile.database, |
| 839 |
profile.user, profile.password)) as p: |
| 840 |
recs = list(g.parse(p)) |
| 841 |
except ModuleNotFoundError: |
| 842 |
# no pyodbc installed. Let's ignore this |
| 843 |
raise unittest.SkipTest("No pyodbc installed, not testing odbc grammar.") |
| 844 |
|
| 845 |
self.assertTrue(len(recs)>0) |
| 846 |
for row in recs: |
| 847 |
if row["schema_name"]=="tap_schema": |
| 848 |
break |
| 849 |
else: |
| 850 |
self.assertFalse("TAP_SCHEMA didn't come back from ODBC grammar?") |
| 851 |
|
| 852 |
def testWithLocalQuery(self): |
| 853 |
g = base.parseFromString(odbcgrammar.ODBCGrammar, |
| 854 |
"""<odbcGrammar> |
| 855 |
<makeQuery> |
| 856 |
<code> |
| 857 |
with base.getTableConn() as conn: |
| 858 |
table_name = next(conn.query( |
| 859 |
"select table_name from tap_schema.tables limit 1" |
| 860 |
))[0] |
| 861 |
self.hiddenTableName = table_name |
| 862 |
|
| 863 |
return ("SELECT table_name FROM tap_schema.tables" |
| 864 |
" WHERE table_name!={}").format(escapeSQL(table_name)) |
| 865 |
</code> |
| 866 |
</makeQuery> |
| 867 |
</odbcGrammar> |
| 868 |
""") |
| 869 |
profile = base.getDBProfile("untrustedquery") |
| 870 |
try: |
| 871 |
with testhelpers.testFile("odbcsource.txt", |
| 872 |
"DRIVER={PostgreSQL UNICODE};SERVER=%s;" |
| 873 |
"DATABASE=%s;UID=%s;PWD={%s}"%(profile.host, profile.database, |
| 874 |
profile.user, profile.password)) as p: |
| 875 |
parsed = list(g.parse(p)) |
| 876 |
embargoedName = parsed[0]["parser_"].hiddenTableName |
| 877 |
foundNames = [r["table_name"] for r in parsed] |
| 878 |
|
| 879 |
self.assertFalse(embargoedName in foundNames) |
| 880 |
self.assertTrue([n for n in foundNames if n.startswith("tap_schema")]) |
| 881 |
|
| 882 |
except ModuleNotFoundError: |
| 883 |
# no pyodbc installed. Let's ignore this |
| 884 |
raise unittest.SkipTest("No pyodbc installed, not testing odbc grammar.") |
| 885 |
|
| 886 |
|
| 887 |
@skipIfNoH5py |
| 888 |
class HDF5GrammarTest(testhelpers.VerboseTest): |
| 889 |
def testAstropyFlavour(self): |
| 890 |
src = os.path.join(base.getConfig("inputsDir"), "data", "hdex.hdf5") |
| 891 |
grammar = base.parseFromString(hdf5grammar.HDF5Grammar, |
| 892 |
"<hdf5Grammar dataset='testdata'/>") |
| 893 |
res = list(grammar.parse(src)) |
| 894 |
for d in res: |
| 895 |
del d["parser_"] |
| 896 |
|
| 897 |
self.assertEqual(res, [{ |
| 898 |
'apex': b'Position ICRS 42 -23.789', |
| 899 |
'field': 6.0217, |
| 900 |
'result_': 1}, { |
| 901 |
'apex': b'', |
| 902 |
'field': None, |
| 903 |
'result_': None}]) |
| 904 |
|
| 905 |
def testBadDsName(self): |
| 906 |
src = os.path.join(base.getConfig("inputsDir"), "data", "hdex.hdf5") |
| 907 |
grammar = base.parseFromString(hdf5grammar.HDF5Grammar, |
| 908 |
"<hdf5Grammar dataset='gone' style='vaex'/>") |
| 909 |
self.assertRaisesWithMsg(base.ReportableError, |
| 910 |
utils.EqualingRE("Dataset gone not found in .*inputs/data/hdex.hdf5. Note that we want the parent of the columns group here. The following datasets are visible in the root: testdata, testdata.__table_column_meta__"), |
| 911 |
list, |
| 912 |
(grammar.parse(src),)) |
| 913 |
|
| 914 |
def testVaexStyle(self): |
| 915 |
src = os.path.join(base.getConfig("inputsDir"), "data", "fromvaex.hdf5") |
| 916 |
grammar = base.parseFromString(hdf5grammar.HDF5Grammar, |
| 917 |
"<hdf5Grammar dataset='table' style='vaex'/>") |
| 918 |
res = list(grammar.parse(src)) |
| 919 |
self.assertEqual(res[0]["source_id"], 4464711039265053952) |
| 920 |
self.assertAlmostEqual(res[1]["parallax"], 1.84249) |
| 921 |
|
| 922 |
|
| 923 |
class _SampleUnionGrammar(testhelpers.TestResource): |
| 924 |
def make(self, _): |
| 925 |
return base.parseFromString(uniongrammar.UnionGrammar, r""" |
| 926 |
<unionGrammar> |
| 927 |
<handles pattern="\.txt$"> |
| 928 |
<reGrammar names="a,b,c"/> |
| 929 |
</handles> |
| 930 |
<handles pattern="\.csv$"> |
| 931 |
<csvGrammar/> |
| 932 |
</handles> |
| 933 |
</unionGrammar>""") |
| 934 |
|
| 935 |
|
| 936 |
class UnionGrammarTest(testhelpers.VerboseTest): |
| 937 |
resources = [("g", _SampleUnionGrammar())] |
| 938 |
|
| 939 |
def testBadRESyntax(self): |
| 940 |
self.assertRaisesWithMsg(base.StructureError, |
| 941 |
"At IO:'<unionGrammar><handles pattern=\")\"><dictlistGrammar/>...', (1, 53): Bad handles pattern: ')' (unbalanced parenthesis at position 0)", |
| 942 |
base.parseFromString, |
| 943 |
(uniongrammar.UnionGrammar, |
| 944 |
'<unionGrammar><handles pattern=")"><dictlistGrammar/></handles>' |
| 945 |
'</unionGrammar>')) |
| 946 |
|
| 947 |
def testBasic(self): |
| 948 |
with testhelpers.testFile("nop.txt", "1 2 3\n") as name: |
| 949 |
self.assertEqual( |
| 950 |
getCleaned(self.g.parse(name)), |
| 951 |
[{'a': '1', 'b': '2', 'c': '3'}]) |
| 952 |
|
| 953 |
with testhelpers.testFile("nop.csv", "x,y,z\n1,2,3\n") as name: |
| 954 |
self.assertEqual( |
| 955 |
getCleaned(self.g.parse(name)), |
| 956 |
[{'x': '1', 'y': '2', 'z': '3'}]) |
| 957 |
|
| 958 |
def testNoMatch(self): |
| 959 |
self.assertRaisesWithMsg(base.DataError, |
| 960 |
"No handler grammar for '/knall/kopf'", |
| 961 |
self.g.parse, |
| 962 |
("/knall/kopf",)) |
| 963 |
|
| 964 |
|
| 965 |
if __name__=="__main__": |
| 966 |
testhelpers.main(HDF5GrammarTest) |