| 1 |
""" |
| 2 |
Tests pertaining to the data parsing system |
| 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 datetime |
| 13 |
import os |
| 14 |
import shutil |
| 15 |
import tarfile |
| 16 |
import tempfile |
| 17 |
import time |
| 18 |
from io import BytesIO |
| 19 |
|
| 20 |
from gavo.helpers import testhelpers |
| 21 |
|
| 22 |
from gavo import base |
| 23 |
from gavo import rsc |
| 24 |
from gavo import rscdef |
| 25 |
from gavo import rscdesc |
| 26 |
from gavo import utils |
| 27 |
from gavo.rsc import dumping |
| 28 |
|
| 29 |
import tresc |
| 30 |
|
| 31 |
|
| 32 |
class RowValidationTest(testhelpers.VerboseTest): |
| 33 |
def testOptional(self): |
| 34 |
rd = testhelpers.getTestRD() |
| 35 |
recDef = rd.getTableDefById("valSpec") |
| 36 |
rec = {} |
| 37 |
try: |
| 38 |
recDef.validateRow(rec) |
| 39 |
except base.ValidationError as ex: |
| 40 |
self.assertEqual(ex.colName, "a_num") |
| 41 |
rec["enum"] = "abysimal" |
| 42 |
self.assertRaises(base.ValidationError, recDef.validateRow, |
| 43 |
rec) |
| 44 |
rec["a_num"] = 14 |
| 45 |
self.assertTrue(recDef.validateRow(rec)==None) |
| 46 |
|
| 47 |
def testBadSchema(self): |
| 48 |
self.assertRaisesWithMsg(base.StructureError, |
| 49 |
'At IO:\'<resource schema="a;drop table foo"/>\', (1, 37):' |
| 50 |
' DaCHS schema attributes must be valid python identifiers', |
| 51 |
base.parseFromString, |
| 52 |
(rscdesc.RD, '<resource schema="a;drop table foo"/>')) |
| 53 |
|
| 54 |
|
| 55 |
@contextlib.contextmanager |
| 56 |
def _inputFile(fName, content): |
| 57 |
with open(fName, "w") as f: |
| 58 |
f.write(content) |
| 59 |
try: |
| 60 |
yield |
| 61 |
finally: |
| 62 |
os.unlink(fName) |
| 63 |
|
| 64 |
|
| 65 |
class SimpleParseTest(testhelpers.VerboseTest): |
| 66 |
"""tests for some simple parses. |
| 67 |
""" |
| 68 |
def _getDD(self): |
| 69 |
return base.parseFromString(rscdef.DataDescriptor, '<data>' |
| 70 |
'<sources>testInput.txt</sources>' |
| 71 |
'<columnGrammar><col key="val1">3</col>' |
| 72 |
'<col key="val2">6-10</col></columnGrammar>' |
| 73 |
'<table id="foo"><column name="x" type="integer"/>' |
| 74 |
'<column name="y" type="text"/>' |
| 75 |
'</table><rowmaker id="bla_foo">' |
| 76 |
'<map dest="y" src="val2"/>' |
| 77 |
'<map dest="x" src="val1"/>' |
| 78 |
'</rowmaker><make table="foo" rowmaker="bla_foo"/></data>') |
| 79 |
|
| 80 |
def testBasic(self): |
| 81 |
with _inputFile("testInput.txt", "xx1xxabc, xxxx\n"): |
| 82 |
dd = self._getDD() |
| 83 |
data = rsc.makeData(dd) |
| 84 |
self.assertEqual(data.getPrimaryTable().rows, [{'y': 'abc,', 'x': 1}]) |
| 85 |
|
| 86 |
def testRaising(self): |
| 87 |
with _inputFile("testInput.txt", "xxxxxabc, xxxx\n"): |
| 88 |
dd = self._getDD() |
| 89 |
self.assertRaisesWithMsg(base.ValidationError, |
| 90 |
"Field x: While building x in bla_foo: invalid literal for int()" |
| 91 |
" with base 10: 'x'", |
| 92 |
rsc.makeData, (dd,)) |
| 93 |
|
| 94 |
def testValidation(self): |
| 95 |
with _inputFile("testInput.txt", "xx1xxabc, xxxx\n"): |
| 96 |
dd = base.parseFromString(rscdef.DataDescriptor, '<data>' |
| 97 |
'<sources pattern="testInput.txt"/>' |
| 98 |
'<columnGrammar><col key="val1">3</col></columnGrammar>' |
| 99 |
'<table id="foo"><column name="x" type="integer"/>' |
| 100 |
'<column name="y" type="text"/></table><rowmaker id="bla_foo">' |
| 101 |
'<map dest="x" src="val1"/></rowmaker>' |
| 102 |
'<make table="foo" rowmaker="bla_foo"/></data>') |
| 103 |
rsc.makeData(dd, rsc.parseNonValidating) |
| 104 |
self.assertRaisesWithMsg(base.ValidationError, |
| 105 |
"Field y: y not bound in row", |
| 106 |
rsc.makeData, (dd, rsc.parseValidating)) |
| 107 |
|
| 108 |
def testNonExistingSource(self): |
| 109 |
dd = self._getDD() |
| 110 |
try: |
| 111 |
rsc.makeData(dd) |
| 112 |
except base.SourceParseError as ex: |
| 113 |
msg = str(ex) |
| 114 |
self.assertTrue(msg.startswith( |
| 115 |
"At start: I/O operation failed ([Errno 2] No such file or directory:")) |
| 116 |
self.assertTrue(msg.endswith("tests/testInput.txt')")) |
| 117 |
|
| 118 |
|
| 119 |
class RowsetTest(testhelpers.VerboseTest): |
| 120 |
def assertQueryReturns(self, query, expected): |
| 121 |
cursor = self.conn.cursor() |
| 122 |
cursor.execute(query) |
| 123 |
found = list(cursor) |
| 124 |
self.assertEqual(len(found), len(expected), |
| 125 |
"Rowset length didn't match: %s"%str(found)) |
| 126 |
for f, e in zip(sorted(found), sorted(expected)): |
| 127 |
self.assertEqual(f, e, "Rows don't match: %s vs. %s"%(f, e)) |
| 128 |
|
| 129 |
|
| 130 |
class TestProductsImport(RowsetTest): |
| 131 |
"""tests for operational import of real data. |
| 132 |
|
| 133 |
This is more of an integration test, but never mind that. |
| 134 |
""" |
| 135 |
resources = [("conn", tresc.prodtestTable)] |
| 136 |
|
| 137 |
def testWorkingImport(self): |
| 138 |
self.assertQueryReturns("select object from test.prodtest", |
| 139 |
[("gabriel",), ("michael",)]) |
| 140 |
|
| 141 |
def testInProducts(self): |
| 142 |
self.assertQueryReturns( |
| 143 |
"select * from dc.products where sourceTable='test.prodtest'", |
| 144 |
[('data/a.imp', 'X_test', datetime.date(2030, 12, 31), |
| 145 |
'text/plain', 'data/a.imp', 'test.prodtest', |
| 146 |
'data/broken.imp', None, 'text/plain'), |
| 147 |
('data/b.imp', 'X_test', datetime.date(2003, 12, 31), |
| 148 |
'text/plain', 'data/b.imp', 'test.prodtest', |
| 149 |
'http://example.com/borken.jpg', None, 'image/jpeg'),]) |
| 150 |
|
| 151 |
def testNoMixinInMem(self): |
| 152 |
self.assertRaisesWithMsg(base.StructureError, |
| 153 |
"Tables mixing in product must be onDisk, but foo is not", |
| 154 |
base.parseFromString, (rscdesc.RD, |
| 155 |
'<resource schema="test"><table id="foo" mixin="//products#table">' |
| 156 |
'</table></resource>',)) |
| 157 |
|
| 158 |
def testImportWithBadFails(self): |
| 159 |
dd = testhelpers.getTestRD().getById("productimport") |
| 160 |
self.assertRaisesWithMsg(base.SourceParseError, |
| 161 |
"At unspecified location: Not a key value pair: 'kaputt.'", |
| 162 |
rsc.makeData, |
| 163 |
(dd,), |
| 164 |
parseOptions=rsc.parseValidating, connection=self.conn) |
| 165 |
|
| 166 |
|
| 167 |
class ProductsSkippingTest(RowsetTest): |
| 168 |
resources = [("conn", tresc.dbConnection)] |
| 169 |
|
| 170 |
def _testImportWithSkipBehavesConsistently(self, parseOptions): |
| 171 |
# This is of course crappy behaviour we don't want, but it's hard |
| 172 |
# to fix this, and actually sometimes this "skip just one table" |
| 173 |
# might be what people want. Anyway, we need to be consistent. |
| 174 |
dd = testhelpers.getTestRD().getById("productimport-skip") |
| 175 |
data = rsc.makeData(dd, |
| 176 |
parseOptions=parseOptions, connection=self.conn) |
| 177 |
try: |
| 178 |
self.assertQueryReturns("select object from test.prodskip", |
| 179 |
[('gabriel',)]) |
| 180 |
self.assertQueryReturns("select accref from dc.products where" |
| 181 |
" sourceTable='test.prodskip'", |
| 182 |
[('data/a.imp',), ('data/b.imp',)]) |
| 183 |
finally: |
| 184 |
data.dropTables(parseOptions) |
| 185 |
self.conn.commit() |
| 186 |
|
| 187 |
def testImportWithSkipBehavesKeepGoing(self): |
| 188 |
self._testImportWithSkipBehavesConsistently( |
| 189 |
rsc.parseValidating.change(keepGoing=True)) |
| 190 |
|
| 191 |
def testImportWithSkipBehavesNormal(self): |
| 192 |
self._testImportWithSkipBehavesConsistently( |
| 193 |
rsc.parseValidating.change(keepGoing=False)) |
| 194 |
|
| 195 |
|
| 196 |
class IgnoredThingsTest(testhelpers.VerboseTest): |
| 197 |
rd = base.parseFromString(rscdesc.RD, |
| 198 |
"""<resource schema="test"> |
| 199 |
<table id="coll"> |
| 200 |
<column name="item" type="integer"/> |
| 201 |
</table> |
| 202 |
<data id="import"> |
| 203 |
<sources/> <!-- provided by text --> |
| 204 |
<embeddedGrammar> |
| 205 |
<iterator> |
| 206 |
<code> |
| 207 |
lower, upper = map(int, self.sourceToken.split()) |
| 208 |
for i in range(lower, upper): |
| 209 |
yield {"item": i} |
| 210 |
</code></iterator> |
| 211 |
<rowfilter> |
| 212 |
<code> |
| 213 |
if @item==223: |
| 214 |
raise SkipThis("Killing this source") |
| 215 |
yield row |
| 216 |
</code> |
| 217 |
</rowfilter> |
| 218 |
</embeddedGrammar> |
| 219 |
<make table="coll"> |
| 220 |
<rowmaker idmaps="*"> |
| 221 |
<apply> |
| 222 |
<code> |
| 223 |
if @item==23: |
| 224 |
raise IgnoreThisRow("Don't like 23") |
| 225 |
elif @item==123: |
| 226 |
raise SkipThis("That's quite enough") |
| 227 |
</code></apply></rowmaker></make> |
| 228 |
</data> |
| 229 |
</resource>""") |
| 230 |
|
| 231 |
def testIgnoreThisRow(self): |
| 232 |
d = rsc.makeData(self.rd.getById("import"), forceSource="22 25") |
| 233 |
res = [r["item"] for r in d.getPrimaryTable().rows] |
| 234 |
self.assertEqual(res, [22, 24]) |
| 235 |
|
| 236 |
def testSkipThis(self): |
| 237 |
d = rsc.makeData(self.rd.getById("import"), forceSource="122 125") |
| 238 |
res = [r["item"] for r in d.getPrimaryTable().rows] |
| 239 |
self.assertEqual(res, [122]) |
| 240 |
|
| 241 |
def testSkipThisInRowfilter(self): |
| 242 |
d = rsc.makeData(self.rd.getById("import"), forceSource="222 225") |
| 243 |
res = [r["item"] for r in d.getPrimaryTable().rows] |
| 244 |
self.assertEqual(res, [222]) |
| 245 |
|
| 246 |
|
| 247 |
class _WildResource(testhelpers.TestResource): |
| 248 |
def make(self, ignored): |
| 249 |
tempPath = tempfile.mkdtemp(suffix="parsetest", |
| 250 |
dir=str(base.getConfig("inputsdir"))) |
| 251 |
rdSrc = """<resource schema="%s"> |
| 252 |
<table onDisk="true" id="deleteme" mixin="//products#table"/> |
| 253 |
<data id="import"> |
| 254 |
<sources pattern="*"/> |
| 255 |
<keyValueGrammar> |
| 256 |
<rowfilter procDef="//products#define"> |
| 257 |
<bind key="accref">\\inputRelativePath{False}</bind> |
| 258 |
<bind key="table">"deleteme"</bind> |
| 259 |
</rowfilter> |
| 260 |
</keyValueGrammar> |
| 261 |
<make table="deleteme"/> |
| 262 |
</data> |
| 263 |
</resource>"""%os.path.basename(tempPath) |
| 264 |
rd = base.parseFromString(rscdesc.RD, rdSrc) |
| 265 |
return rd |
| 266 |
|
| 267 |
def clean(self, rd): |
| 268 |
shutil.rmtree(rd.resdir) |
| 269 |
|
| 270 |
|
| 271 |
class ProductsBadNameTest(testhelpers.VerboseTest, metaclass=testhelpers.SamplesBasedAutoTest): |
| 272 |
# Products are supposed to have well-behaved file names. |
| 273 |
# This is a test making sure bad file names are rejected. |
| 274 |
|
| 275 |
resources = [("rd", _WildResource())] |
| 276 |
|
| 277 |
def _runTest(self, sample): |
| 278 |
destName, shouldBeOk = sample |
| 279 |
fullPath = os.path.join(base.getConfig("inputsDir"), destName) |
| 280 |
f = open(fullPath, "w") |
| 281 |
try: |
| 282 |
ex = None |
| 283 |
try: |
| 284 |
list(self.rd.dds[0].grammar.parse(fullPath, None)) |
| 285 |
except ValueError as raised: |
| 286 |
ex = raised |
| 287 |
if shouldBeOk and ex: |
| 288 |
raise AssertionError("Filename %s should be legal but is not"%destName) |
| 289 |
elif not shouldBeOk and ex is None: |
| 290 |
raise AssertionError("Filename %s should be illegal" |
| 291 |
" but is not"%destName) |
| 292 |
finally: |
| 293 |
f.close() |
| 294 |
os.unlink(fullPath) |
| 295 |
|
| 296 |
samples = [ |
| 297 |
("ok_LOT,allowed-this_ought,to10000do.file", True), |
| 298 |
("Q2232+23.fits", False), |
| 299 |
("A&A23..1.fits", False), |
| 300 |
("name with blank.fits", False), |
| 301 |
("name%with%blank.fits", False), |
| 302 |
("don't want quotes", False),] |
| 303 |
|
| 304 |
|
| 305 |
class CleanedupTest(RowsetTest): |
| 306 |
"""tests for cleanup after table drop (may fail if other tests failed). |
| 307 |
""" |
| 308 |
resources = [("conn", tresc.dbConnection)] |
| 309 |
|
| 310 |
def testNotInProducts(self): |
| 311 |
# WARNING: test.prodtest is used by lots of other test. So, |
| 312 |
# this thing may not run in parallel to other tests, and |
| 313 |
# it *must* recreate productsimport when done. |
| 314 |
dd = testhelpers.getTestRD().getById("productimport") |
| 315 |
try: |
| 316 |
tresc.makeProdtestTable(self.conn) |
| 317 |
rsc.Data.drop(dd, |
| 318 |
connection=self.conn) |
| 319 |
self.assertQueryReturns( |
| 320 |
"select * from dc.products where sourceTable='test.prodtest'", |
| 321 |
[]) |
| 322 |
self.assertQueryReturns( |
| 323 |
"select * from dc.tablemeta where tableName='test.prodtest'", |
| 324 |
[]) |
| 325 |
finally: |
| 326 |
self.conn.rollback() |
| 327 |
tresc.makeProdtestTable(self.conn) |
| 328 |
self.conn.commit() |
| 329 |
|
| 330 |
|
| 331 |
class DispatchedGrammarTest(testhelpers.VerboseTest): |
| 332 |
def testSimple(self): |
| 333 |
rd = base.parseFromString(rscdesc.RD, |
| 334 |
""" |
| 335 |
<resource schema="test"> |
| 336 |
<table id="t1"><column name="x" type="text"/></table> |
| 337 |
<table id="t2"><column name="y" type="text"/></table> |
| 338 |
<data id="import"> |
| 339 |
<sources items="foo"/> |
| 340 |
<embeddedGrammar isDispatching="True"><iterator><code> |
| 341 |
yield "one", {"x": "x1", "y": "FAIL"} |
| 342 |
yield "two", {"x": "FAIL", "y": "y1"} |
| 343 |
yield "one", {"x": "x2", "y": "FAIL"} |
| 344 |
</code></iterator></embeddedGrammar> |
| 345 |
<make role="one" table="t1"/> |
| 346 |
<make role="two" table="t2"/> |
| 347 |
</data> |
| 348 |
</resource> |
| 349 |
""") |
| 350 |
data = rsc.makeData(rd.getById("import")) |
| 351 |
self.assertEqual([r["x"] for r in data.getTableWithRole("one").rows], |
| 352 |
["x1", "x2"]) |
| 353 |
self.assertEqual([r["y"] for r in data.getTableWithRole("two").rows], |
| 354 |
["y1"]) |
| 355 |
|
| 356 |
def testNoRole(self): |
| 357 |
dd = base.parseFromString(rscdef.DataDescriptor, """<data id="import"> |
| 358 |
<sources items="foo"/> |
| 359 |
<embeddedGrammar isDispatching="True"><iterator><code> |
| 360 |
yield "one", {"x": "x1", "y": "FAIL"} |
| 361 |
</code></iterator></embeddedGrammar> |
| 362 |
</data> |
| 363 |
""") |
| 364 |
self.assertRaisesWithMsg(base.ReportableError, |
| 365 |
"Grammar tries to feed to role 'one', but there is no corresponding make", |
| 366 |
rsc.makeData, (dd,)) |
| 367 |
|
| 368 |
|
| 369 |
class CrossResolutionTest(testhelpers.VerboseTest): |
| 370 |
# NOTE: DaCHS-internal code should use base.resolveCrossId instead of |
| 371 |
# of the getReferencedElement exercised here. |
| 372 |
def testItemAbsolute(self): |
| 373 |
res = rscdef.getReferencedElement("data/test#ADQLTest") |
| 374 |
self.assertEqual(res.id, "ADQLTest") |
| 375 |
|
| 376 |
def testRDAbsolute(self): |
| 377 |
res = rscdef.getReferencedElement("data/test") |
| 378 |
self.assertEqual(res.sourceId, "data/test") |
| 379 |
|
| 380 |
def testRDTypecheck(self): |
| 381 |
self.assertRaisesWithMsg(base.StructureError, |
| 382 |
"Reference to 'data/test' yielded object of type RD, but expected" |
| 383 |
" a(n) TableDef instance.", |
| 384 |
rscdef.getReferencedElement, |
| 385 |
("data/test", rscdef.TableDef)) |
| 386 |
|
| 387 |
def testItemError(self): |
| 388 |
self.assertRaisesWithMsg(base.NotFoundError, |
| 389 |
"Element with id 'nonexisting' could not be located in RD data/test", |
| 390 |
rscdef.getReferencedElement, |
| 391 |
("data/test#nonexisting",)) |
| 392 |
|
| 393 |
def testRDError(self): |
| 394 |
self.assertRaisesWithMsg(base.NotFoundError, |
| 395 |
"Resource descriptor 'nonexisting' could not be located in file system", |
| 396 |
rscdef.getReferencedElement, |
| 397 |
("nonexisting",)) |
| 398 |
|
| 399 |
def testItemRelative(self): |
| 400 |
wd = os.path.join(base.getConfig("inputsDir"), "test") |
| 401 |
with testhelpers.testFile(os.path.join(wd, "rel.rd"), |
| 402 |
"""<resource schema="test"><table id="bar"/></resource>"""): |
| 403 |
with utils.in_dir(wd): |
| 404 |
res = rscdef.getReferencedElement("rel#bar", rscdef.TableDef) |
| 405 |
self.assertEqual(res.id, "bar") |
| 406 |
|
| 407 |
def testRelativeMessage(self): |
| 408 |
wd = os.path.join(base.getConfig("inputsDir"), "test") |
| 409 |
with utils.in_dir(wd): |
| 410 |
self.assertRaisesWithMsg(base.NotFoundError, |
| 411 |
"Resource descriptor 'test/foo' could not be located in file system", |
| 412 |
rscdef.getReferencedElement, |
| 413 |
("foo#bar", rscdef.TableDef)) |
| 414 |
|
| 415 |
def testRDRelative(self): |
| 416 |
wd = os.path.join(base.getConfig("inputsDir"), "test") |
| 417 |
with testhelpers.testFile(os.path.join(wd, "rel.rd"), |
| 418 |
"""<resource schema="test"><table id="bar"/></resource>"""): |
| 419 |
with utils.in_dir(wd): |
| 420 |
res = rscdef.getReferencedElement("rel") |
| 421 |
self.assertEqual(res.sourceId, "test/rel") |
| 422 |
|
| 423 |
|
| 424 |
class _SourceHierarchy(testhelpers.TestResource): |
| 425 |
def make(self, ignored): |
| 426 |
self.root = tempfile.mkdtemp("sourcetest", dir=base.getConfig("inputsDir")) |
| 427 |
for dirInd in range(3): |
| 428 |
dirName = os.path.join(self.root, "dir%s"%dirInd) |
| 429 |
os.mkdir(dirName) |
| 430 |
for fileInd in range(dirInd+1): |
| 431 |
with open(os.path.join(dirName, "file.%s"%fileInd), "w") as f: |
| 432 |
f.write(str(fileInd)+"\n") |
| 433 |
|
| 434 |
linkDir = os.path.join(self.root, "links", "data") |
| 435 |
os.makedirs(linkDir) |
| 436 |
os.symlink(os.path.join(self.root, "dir1"), |
| 437 |
os.path.join(linkDir, "a")) |
| 438 |
os.symlink(os.path.join(self.root, "dir2"), |
| 439 |
os.path.join(linkDir, "b")) |
| 440 |
|
| 441 |
return os.path.basename(self.root) |
| 442 |
|
| 443 |
def clean(self, ignored): |
| 444 |
shutil.rmtree(self.root) |
| 445 |
|
| 446 |
|
| 447 |
class SourcesTest(testhelpers.VerboseTest): |
| 448 |
resources = [ |
| 449 |
("resdir", _SourceHierarchy()), ("connection", tresc.dbConnection)] |
| 450 |
|
| 451 |
def testFollowLinks(self): |
| 452 |
rd = base.parseFromString(rscdesc.RD, |
| 453 |
'<resource schema="%s"><data id="import">' |
| 454 |
'<sources recurse="True" pattern="links/file*"/></data></resource>'% |
| 455 |
self.resdir) |
| 456 |
|
| 457 |
self.assertEqual( |
| 458 |
["/".join(s.split("/")[-2:]) |
| 459 |
for s in rd.getById("import").sources.iterSources()], |
| 460 |
['a/file.0', 'a/file.1', 'b/file.0', 'b/file.1', 'b/file.2']) |
| 461 |
|
| 462 |
def testFollowLinksImmediate(self): |
| 463 |
rd = base.parseFromString(rscdesc.RD, |
| 464 |
'<resource schema="%s"><data id="import">' |
| 465 |
'<sources recurse="True" pattern="links/data/file*"/></data></resource>'% |
| 466 |
self.resdir) |
| 467 |
|
| 468 |
self.assertEqual( |
| 469 |
["/".join(s.split("/")[-2:]) |
| 470 |
for s in rd.getById("import").sources.iterSources()], |
| 471 |
['a/file.0', 'a/file.1', 'b/file.0', 'b/file.1', 'b/file.2']) |
| 472 |
|
| 473 |
def testRecursePattern(self): |
| 474 |
rd = base.parseFromString(rscdesc.RD, |
| 475 |
'<resource schema="%s"><data id="import">' |
| 476 |
'<sources recurse="True" pattern="dir*/*.0"/></data></resource>'% |
| 477 |
self.resdir) |
| 478 |
self.assertEqual( |
| 479 |
["/".join(s.split("/")[-2:]) |
| 480 |
for s in rd.getById("import").sources.iterSources()], |
| 481 |
['dir0/file.0', 'dir1/file.0', 'dir2/file.0']) |
| 482 |
|
| 483 |
def testIgnorePattern(self): |
| 484 |
rd = base.parseFromString(rscdesc.RD, |
| 485 |
'<resource schema="%s"><data id="import">' |
| 486 |
'<sources recurse="True" pattern="dir*/*">' |
| 487 |
'<ignoreSources pattern="*.1"/></sources></data></resource>'% |
| 488 |
self.resdir) |
| 489 |
self.assertEqual( |
| 490 |
["/".join(s.split("/")[-2:]) |
| 491 |
for s in rd.getById("import").sources.iterSources()], |
| 492 |
['dir0/file.0', 'dir1/file.0', 'dir2/file.0', 'dir2/file.2']) |
| 493 |
|
| 494 |
def testIgnoreFromdb(self): |
| 495 |
rd = base.parseFromString(rscdesc.RD, |
| 496 |
r""" |
| 497 |
<resource schema="test"> |
| 498 |
<table id="withdate" mixin="//products#table" onDisk="True" |
| 499 |
primary="accref" forceUnique="True" dupePolicy="overwrite"> |
| 500 |
<column name="mtime" type="timestamp"/> |
| 501 |
</table> |
| 502 |
<data id="import" updating="True"> |
| 503 |
<sources pattern="*.kram"> |
| 504 |
<ignoreSources |
| 505 |
fromdbUpdating="select accref, mtime from \schema.withdate"/> |
| 506 |
</sources> |
| 507 |
<columnGrammar> |
| 508 |
<rowfilter procDef="//products#define"> |
| 509 |
<bind key="table">"\schema.withdate"</bind> |
| 510 |
</rowfilter> |
| 511 |
</columnGrammar> |
| 512 |
<make table="withdate"> |
| 513 |
<rowmaker> |
| 514 |
<map key="mtime">datetime.datetime.utcfromtimestamp( |
| 515 |
os.path.getmtime(\fullPath))</map> |
| 516 |
</rowmaker> |
| 517 |
</make> |
| 518 |
</data> |
| 519 |
</resource>""") |
| 520 |
rd.sourceId = "test/withdate" |
| 521 |
|
| 522 |
dd = rd.getById("import") |
| 523 |
datadir = os.path.join(base.getConfig("inputsDir"), "test/") |
| 524 |
try: |
| 525 |
with testhelpers.testFile("a.kram", "a", inDir=datadir): |
| 526 |
with testhelpers.testFile("b.kram", "b", inDir=datadir): |
| 527 |
os.utime(datadir+"a.kram", (1e9, 1e9)) |
| 528 |
os.utime(datadir+"b.kram", (1.3e9, 1.3e9)) |
| 529 |
rsc.makeData(dd, connection=self.connection) |
| 530 |
|
| 531 |
ts = list(self.connection.query("select mtime from test.withdate" |
| 532 |
" where accref='test/a.kram'"))[0][0] |
| 533 |
self.assertEqual(ts, datetime.datetime(2001, 9, 9, 1, 46, 40)) |
| 534 |
|
| 535 |
os.utime(datadir+"a.kram", None) |
| 536 |
data = rsc.makeData(dd, connection=self.connection) |
| 537 |
# b.kram is not re-processed as it's not been touched; |
| 538 |
# but a.kram is; rowcount, however, is 0 here because |
| 539 |
# an exiting row is being overwritten. |
| 540 |
self.assertEqual(data.nAffected, 0) |
| 541 |
# but make sure the overwrite has actually taken place |
| 542 |
ts = list(self.connection.query("select mtime from test.withdate" |
| 543 |
" where accref='test/a.kram'"))[0][0] |
| 544 |
self.assertNotEqual(ts, datetime.datetime(2001, 9, 9, 1, 46, 40)) |
| 545 |
finally: |
| 546 |
rsc.Data.drop(dd, connection=self.connection) |
| 547 |
self.connection.commit() |
| 548 |
|
| 549 |
|
| 550 |
class _TestDump(testhelpers.TestResource): |
| 551 |
resources = [ |
| 552 |
("ad", tresc.adqlGeoTable), |
| 553 |
("cs", tresc.csTestTable),] |
| 554 |
|
| 555 |
def make(self, ignored): |
| 556 |
with utils.sandbox(): |
| 557 |
with open("my.dump", "wb") as f: |
| 558 |
rsc.createDump( |
| 559 |
["data/test#csdata", "data/test#ADQLgeo"], |
| 560 |
f, binary=False) |
| 561 |
with open("my.dump", "rb") as f: |
| 562 |
return f.read() |
| 563 |
|
| 564 |
|
| 565 |
class DumpsTest(testhelpers.VerboseTest): |
| 566 |
resources = [("tarbytes", _TestDump())] |
| 567 |
|
| 568 |
def testMembersPresent(self): |
| 569 |
tf = tarfile.open( |
| 570 |
fileobj=BytesIO(self.tarbytes.original), |
| 571 |
mode="r:gz") |
| 572 |
self.assertEqual([i.name for i in tf.getmembers()], |
| 573 |
["table_000.textdump", "table_001.textdump", "index.txt"]) |
| 574 |
|
| 575 |
def testInfo(self): |
| 576 |
ti = list(dumping.iterTableInfos(BytesIO(self.tarbytes.original))) |
| 577 |
self.assertEqual( |
| 578 |
set(i[1] for i in ti), |
| 579 |
set(["data/test#csdata", "data/test#ADQLgeo"])) |
| 580 |
self.assertEqual(set(i[2] for i in ti), set([True])) |
| 581 |
minDate = min(i[3] for i in ti) |
| 582 |
self.assertTrue(time.time()-20<=minDate<=time.time()) |
| 583 |
self.assertTrue(min(i[4] for i in ti)>10) |
| 584 |
|
| 585 |
def testRestore(self): |
| 586 |
# if this test fails, you may want to just re-create the test environment. |
| 587 |
with base.getWritableAdminConn() as conn: |
| 588 |
csRows = list(conn.queryToDicts("select * from test.csdata")) |
| 589 |
geoRows = list(conn.queryToDicts("select * from test.adqlgeo")) |
| 590 |
conn.execute("delete from test.csdata") |
| 591 |
conn.execute("drop table test.adqlgeo") |
| 592 |
conn.commit() |
| 593 |
|
| 594 |
self.assertEqual( |
| 595 |
list(conn.queryToDicts("select * from test.csdata")), |
| 596 |
[]) |
| 597 |
|
| 598 |
rsc.restoreDump(BytesIO(self.tarbytes.original)) |
| 599 |
|
| 600 |
with base.getTableConn() as conn: |
| 601 |
self.assertEqual( |
| 602 |
geoRows, |
| 603 |
list(conn.queryToDicts("select * from test.adqlgeo"))) |
| 604 |
self.assertEqual( |
| 605 |
csRows, |
| 606 |
list(conn.queryToDicts("select * from test.csdata"))) |
| 607 |
|
| 608 |
|
| 609 |
class ViewStatementTest(testhelpers.VerboseTest): |
| 610 |
resources = [("conn", tresc.dbConnection)] |
| 611 |
|
| 612 |
def testMalformed(self): |
| 613 |
rd = base.parseFromString(rscdesc.RD, """<resource schema="test"> |
| 614 |
<table onDisk="true" id="deleteme"> |
| 615 |
<column name="foo"/> |
| 616 |
<viewStatement> |
| 617 |
CREATE VIEW \\curtable AS ( |
| 618 |
SELECT \\colNames FROM ( |
| 619 |
SELECT 1 as bar, 2 as quux) AS q) |
| 620 |
</viewStatement> |
| 621 |
</table> |
| 622 |
<data id="import"> |
| 623 |
<make table="deleteme"/> |
| 624 |
</data> |
| 625 |
</resource>""") |
| 626 |
self.assertRaisesWithMsg(base.ReportableError, |
| 627 |
'View statement of table at IO:\'<resource schema="test"> <table onDisk="true" id="del...\', line 2 bad. Postgres error message: column "foo" does not exist\nLINE 3: SELECT foo FROM (\n ^\n', |
| 628 |
rsc.makeData, |
| 629 |
(rd.getById("import"),), |
| 630 |
connection=self.conn) |
| 631 |
|
| 632 |
|
| 633 |
def roundtripThroughDB(conn, type, testData): |
| 634 |
"""roundtrips the values in testData through a temporary database |
| 635 |
table with for type and returns the result. |
| 636 |
""" |
| 637 |
rd = base.parseFromString(rscdesc.RD, f"""<resource schema="test"> |
| 638 |
<table id="rttest" temporary="True" onDisk="True"> |
| 639 |
<column name="seq" type="integer"/> |
| 640 |
<column name="testval" type="{type}"/> |
| 641 |
</table> |
| 642 |
|
| 643 |
<data id="do_roundtrip"> |
| 644 |
<dictlistGrammar/> |
| 645 |
<make table="rttest"/> |
| 646 |
</data> |
| 647 |
</resource> |
| 648 |
""") |
| 649 |
rsc.makeData(rd.dds[0], |
| 650 |
forceSource=[{"testval": v, "seq": i} |
| 651 |
for i, v in enumerate(testData)], |
| 652 |
connection=conn) |
| 653 |
|
| 654 |
return [row[1] |
| 655 |
for row in sorted(conn.query("select seq, testval from rttest"))] |
| 656 |
|
| 657 |
|
| 658 |
class DatabaseRoundtripTest(testhelpers.VerboseTest): |
| 659 |
resources = [("conn", tresc.dbConnection)] |
| 660 |
|
| 661 |
def testBytes(self): |
| 662 |
afterRoundtrip = [bytes(v) for v in |
| 663 |
roundtripThroughDB(self.conn, "bytea", [ |
| 664 |
b'\0', b'a\0b', br'\x40', r'\070\100'])] |
| 665 |
# yes, the last (raw) string *does* interpret escapes. |
| 666 |
# That's (questionable) literals.parseBytes behaviour. |
| 667 |
self.assertEqual(afterRoundtrip, |
| 668 |
[b'\0', b'a\0b', b'\\x40', b'8@']) |
| 669 |
|
| 670 |
def testJson(self): |
| 671 |
afterRoundtrip = roundtripThroughDB(self.conn, "json", [ |
| 672 |
None, '"Grätsche"', ['eins', 'zwei'], {'key': 'value'}]) |
| 673 |
# it *is* a bit lame that json string literals lose their |
| 674 |
# quotes on roundtripping, but I think that's preferable |
| 675 |
# vs. not admitting in json literals. |
| 676 |
self.assertEqual(afterRoundtrip, |
| 677 |
[None, 'Grätsche', ['eins', 'zwei'], {'key': 'value'}]) |
| 678 |
|
| 679 |
def testJsonb(self): |
| 680 |
afterRoundtrip = roundtripThroughDB(self.conn, "jsonb", [ |
| 681 |
None, '"Grätsche"', ['eins', 'zwei'], {'key': 'value'}]) |
| 682 |
self.assertEqual(afterRoundtrip, |
| 683 |
[None, 'Grätsche', ['eins', 'zwei'], {'key': 'value'}]) |
| 684 |
|
| 685 |
|
| 686 |
class _DynTableRD(testhelpers.TestResource): |
| 687 |
def make(self, deps): |
| 688 |
return base.parseFromString(rscdesc.RD, """<resource schema="test"> |
| 689 |
<table id="a"> |
| 690 |
<param name="animal" type="text">Gnu</param> |
| 691 |
<column name="height" unit="m"/> |
| 692 |
</table> |
| 693 |
|
| 694 |
<table id="b"> |
| 695 |
<param name="animal" type="text">Bug</param> |
| 696 |
<column name="height" unit="mm"/> |
| 697 |
</table> |
| 698 |
|
| 699 |
<data id="import"> |
| 700 |
<sources item="x"/> |
| 701 |
<embeddedGrammar> |
| 702 |
<iterator> |
| 703 |
<code> |
| 704 |
for i in range(20): |
| 705 |
yield {"height": i} |
| 706 |
</code> |
| 707 |
</iterator> |
| 708 |
</embeddedGrammar> |
| 709 |
|
| 710 |
<make table="a"/> |
| 711 |
</data> |
| 712 |
</resource>""") |
| 713 |
|
| 714 |
|
| 715 |
class DynamicMakeTest(testhelpers.VerboseTest): |
| 716 |
resources = [("rd", _DynTableRD())] |
| 717 |
|
| 718 |
def testMakeTableA(self): |
| 719 |
dd = self.rd.getById("import") |
| 720 |
data = rsc.Data.createWithTable(dd, self.rd.getById("a")) |
| 721 |
rsc.makeData(dd, data=data) |
| 722 |
|
| 723 |
t = data.getPrimaryTable() |
| 724 |
self.assertEqual(t.getParam("animal"), "Gnu") |
| 725 |
self.assertEqual(t.tableDef.getColumnByName("height").unit, "m") |
| 726 |
|
| 727 |
def testMakeTableB(self): |
| 728 |
dd = self.rd.getById("import") |
| 729 |
data = rsc.Data.createWithTable(dd, self.rd.getById("b")) |
| 730 |
rsc.makeData(dd, data=data) |
| 731 |
|
| 732 |
t = data.getPrimaryTable() |
| 733 |
self.assertEqual(t.getParam("animal"), "Bug") |
| 734 |
self.assertEqual(t.tableDef.getColumnByName("height").unit, "mm") |
| 735 |
|
| 736 |
|
| 737 |
class OddImportsTest(tresc.TestWithDBConnection): |
| 738 |
def testImportStringIntoPoly(self): |
| 739 |
rd = base.parseFromString(rscdesc.RD, """<resource schema="test"> |
| 740 |
<table id="a" onDisk="True"> |
| 741 |
<column name="p" type="spoly"/> |
| 742 |
</table> |
| 743 |
|
| 744 |
<data id="import"><dictlistGrammar/><make table="a"/></data> |
| 745 |
</resource>""") |
| 746 |
self.assertRaisesWithMsg(base.DBError, |
| 747 |
"can't adapt type 'GeomExpr'", |
| 748 |
rsc.makeData, |
| 749 |
(rd.getById("import"),), |
| 750 |
forceSource=[{"p": "Union ICRS TOPOCENTER" |
| 751 |
" (Polygon 180.0 45.0 230.0 80.0 300.0 30.0 180.0 45.0" |
| 752 |
" Polygon 180.0 45.0 50.0 80.0 60.0 30.0 180.0 45.0)"}], |
| 753 |
connection=self.conn) |
| 754 |
|
| 755 |
|
| 756 |
if __name__=="__main__": |
| 757 |
testhelpers.main(DispatchedGrammarTest) |