| 1 |
""" |
| 2 |
Some tests for the database interface and the surrounding helper code. |
| 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 math |
| 13 |
import os |
| 14 |
import sys |
| 15 |
import time |
| 16 |
import unittest |
| 17 |
|
| 18 |
import numpy |
| 19 |
|
| 20 |
from gavo.helpers import testhelpers |
| 21 |
|
| 22 |
from gavo import base |
| 23 |
from gavo import rsc |
| 24 |
from gavo import rscdesc |
| 25 |
from gavo import svcs |
| 26 |
from gavo import utils |
| 27 |
from gavo.base import config |
| 28 |
from gavo.base import sqlsupport |
| 29 |
from gavo.utils import pyfits |
| 30 |
|
| 31 |
import tresc |
| 32 |
|
| 33 |
|
| 34 |
class GetSQLTest(testhelpers.VerboseTest): |
| 35 |
# this is for "dumb" fields. See also viziertest and pqltest for advanced |
| 36 |
# SQL generation from stuff coming in from the web. |
| 37 |
def _assertSQLGenerated(self, ikArgs, inputPars, fragment, sqlPars): |
| 38 |
foundPars = {} |
| 39 |
inputKey = base.makeStruct(svcs.InputKey, **ikArgs) |
| 40 |
foundFragment = base.getSQLForField(inputKey, inputPars, foundPars) |
| 41 |
self.assertEqual(fragment, foundFragment) |
| 42 |
self.assertEqual(sqlPars, foundPars) |
| 43 |
|
| 44 |
def testSimpleString(self): |
| 45 |
self._assertSQLGenerated( |
| 46 |
{"name": "foo", "type": "text"}, |
| 47 |
{"foo": ["';"]}, |
| 48 |
'foo=%(foo0)s', {'foo0': "';"}) |
| 49 |
|
| 50 |
def testEmptyString(self): |
| 51 |
self._assertSQLGenerated( |
| 52 |
{"name": "foo", "type": "text"}, |
| 53 |
{"foo": [""]}, |
| 54 |
'foo=%(foo0)s', {'foo0': ""}) |
| 55 |
|
| 56 |
def testMissingString(self): |
| 57 |
self._assertSQLGenerated( |
| 58 |
{"name": "foo", "type": "text"}, |
| 59 |
{}, |
| 60 |
None, {}) |
| 61 |
|
| 62 |
def testIntSeq(self): |
| 63 |
self._assertSQLGenerated( |
| 64 |
{"name": "foo", "type": "integer"}, |
| 65 |
{"foo": list(map(int, "1 2 3 4".split()))}, |
| 66 |
'foo IN %(foo0)s', {'foo0': set([1,2,3,4])}) |
| 67 |
|
| 68 |
|
| 69 |
class ProfileTest(testhelpers.VerboseTest): |
| 70 |
parser = config.ProfileParser(["data"]) |
| 71 |
|
| 72 |
def testEmptyProfile(self): |
| 73 |
nullProfile = self.parser.parse("test1", None, "") |
| 74 |
self.assertRaisesWithMsg(base.StructureError, |
| 75 |
"Insufficient information to connect to the database in profile 'test1'.", |
| 76 |
base.getDBConnection, |
| 77 |
(nullProfile,)) |
| 78 |
|
| 79 |
def testInvalidProfile(self): |
| 80 |
self.assertRaisesWithMsg(config.ProfileParseError, |
| 81 |
"\"internal\", line 3: unknown setting 'hsot'", |
| 82 |
self.parser.parse, |
| 83 |
("test2", "internal", "database=gavo\nhsot=bar\n")) |
| 84 |
|
| 85 |
def testWhitespace(self): |
| 86 |
profile = self.parser.parse("foo", None, stream=""" |
| 87 |
user = honk |
| 88 |
|
| 89 |
password="secre t " |
| 90 |
|
| 91 |
""") |
| 92 |
self.assertEqual(profile.user, "honk") |
| 93 |
self.assertEqual(profile.password, "secre t ") |
| 94 |
|
| 95 |
def testUnknownProfile(self): |
| 96 |
self.assertRaisesWithMsg( |
| 97 |
config.ProfileParseError, |
| 98 |
"Requested db profile 'nonexisting' does not exist", |
| 99 |
base.getDBProfile, |
| 100 |
("nonexisting",)) |
| 101 |
|
| 102 |
|
| 103 |
class ConnectionsTest(testhelpers.VerboseTest): |
| 104 |
resources = [("conn", tresc.dbConnection)] |
| 105 |
|
| 106 |
def testServerVersion(self): |
| 107 |
version = base.getPgVersion() |
| 108 |
self.assertTrue(isinstance(version, tuple)) |
| 109 |
self.assertTrue(8<=version[0]<=40) # let's see if DaCHS lives that long |
| 110 |
self.assertTrue(0<version[1]<30) |
| 111 |
|
| 112 |
def testConfigReset(self): |
| 113 |
self.conn.configure([("statement_timeout", 0)]) |
| 114 |
with self.conn.parameters([("statement_timeout", 20*1000)]): |
| 115 |
self.assertEqual( |
| 116 |
self.conn.getParameter("statement_timeout"), "20s") |
| 117 |
self.assertEqual(self.conn.getParameter("statement_timeout"), '0') |
| 118 |
|
| 119 |
def testConfigResetBadQuery(self): |
| 120 |
self.conn.configure([("cursor_tuple_fraction", 1)]) |
| 121 |
self.conn.commit() |
| 122 |
|
| 123 |
try: |
| 124 |
with self.conn.parameters([("cursor_tuple_fraction", 0.2)]): |
| 125 |
self.assertEqual( |
| 126 |
self.conn.getParameter("cursor_tuple_fraction"), "0.2") |
| 127 |
self.conn.execute("ghibberish") |
| 128 |
except AssertionError: |
| 129 |
raise |
| 130 |
except: |
| 131 |
self.conn.rollback() |
| 132 |
|
| 133 |
self.assertEqual( |
| 134 |
self.conn.getParameter("cursor_tuple_fraction"), '1') |
| 135 |
|
| 136 |
def testConfigResetPlainException(self): |
| 137 |
prevVal = self.conn.getParameter("enable_seqscan") |
| 138 |
newVal = {"on": "off", "off": "on"}[prevVal] |
| 139 |
try: |
| 140 |
with self.conn.parameters([("enable_seqscan", newVal)]): |
| 141 |
self.assertEqual( |
| 142 |
self.conn.getParameter("enable_seqscan"), newVal) |
| 143 |
raise ValueError("test failure.") |
| 144 |
except AssertionError: |
| 145 |
raise |
| 146 |
except ValueError: # raised by myself, I guess |
| 147 |
pass |
| 148 |
self.assertEqual( |
| 149 |
self.conn.getParameter("enable_seqscan"), prevVal) |
| 150 |
|
| 151 |
def testConfigAutocommitted(self): |
| 152 |
with base.getTableConn() as conn: |
| 153 |
cursor = conn.cursor() |
| 154 |
cursor.execute("SELECT current_setting('statement_timeout')") |
| 155 |
prevVal = list(cursor)[0][0] |
| 156 |
with conn.parameters([("statement_timeout", 34)]): |
| 157 |
cursor.execute("SELECT current_setting('statement_timeout')") |
| 158 |
self.assertEqual(list(cursor)[0][0], "34ms") |
| 159 |
cursor.execute("SELECT current_setting('statement_timeout')") |
| 160 |
self.assertEqual(list(cursor)[0][0], prevVal) |
| 161 |
cursor.close() |
| 162 |
|
| 163 |
def testNoConnection(self): |
| 164 |
self.assertRaisesWithMsg( |
| 165 |
utils.ReportableError, |
| 166 |
utils.EqualingRE('(?s)Cannot connect to the database server. The database library reported:\n\n.*port 3322.*'), |
| 167 |
base.getDBConnection, |
| 168 |
(config.DBProfile(name="failing", host="localhost", port=3322, |
| 169 |
database="notexiting"),)) |
| 170 |
|
| 171 |
|
| 172 |
@contextlib.contextmanager |
| 173 |
def digestedTable(connection, name, columns, values): |
| 174 |
"""a context manager to have a temporary table with ddl and values, |
| 175 |
also providing the whole table after digestion by the database. |
| 176 |
|
| 177 |
Values is a list of dicts sutable for for INSERT statements. |
| 178 |
|
| 179 |
ddl is a string that is pasted behind create temp table. |
| 180 |
|
| 181 |
None of the inputs is validated in any way, so this function must |
| 182 |
never receive untrusted input. |
| 183 |
""" |
| 184 |
connection.execute("CREATE TEMP TABLE %s %s"%(name, columns)) |
| 185 |
for row in values: |
| 186 |
connection.execute("INSERT INTO %s (%s) VALUES (%s)"%( |
| 187 |
name, ", ".join(row), ", ".join("%%(%s)s"%s for s in row)), |
| 188 |
row) |
| 189 |
yield list(connection.queryToDicts("SELECT * FROM %s"%name)) |
| 190 |
connection.rollback() |
| 191 |
|
| 192 |
|
| 193 |
class TestTypes(testhelpers.VerboseTest): |
| 194 |
"""Tests for some special adapters we provide. |
| 195 |
""" |
| 196 |
resources = [("conn", tresc.dbConnection)] |
| 197 |
|
| 198 |
def testNumpyFloat32(self): |
| 199 |
with digestedTable(self.conn, "n_a_t", "(b REAL)", |
| 200 |
[{"b": numpy.float32(0.25)}]) as rows: |
| 201 |
self.assertEqual(rows[0]["b"], 0.25) |
| 202 |
|
| 203 |
def testNumpyFloat64(self): |
| 204 |
with digestedTable(self.conn, "n_a_t", "(b REAL)", |
| 205 |
[{"b": numpy.float64(0.25)}]) as rows: |
| 206 |
self.assertEqual(rows[0]["b"], 0.25) |
| 207 |
|
| 208 |
def testNumpyInt8(self): |
| 209 |
with digestedTable(self.conn, "n_a_t", "(b BIGINT)", |
| 210 |
[{"b": numpy.int8(10)}]) as rows: |
| 211 |
self.assertEqual(rows[0]["b"], 10) |
| 212 |
|
| 213 |
def testNumpyInt64(self): |
| 214 |
with digestedTable(self.conn, "n_a_t", "(b BIGINT)", |
| 215 |
[{"b": numpy.int64(388290102316)}]) as rows: |
| 216 |
self.assertEqual(rows[0]["b"], 388290102316) |
| 217 |
|
| 218 |
def testNumpyArray(self): |
| 219 |
with digestedTable(self.conn, "n_a_t", "(b integer[])", |
| 220 |
[{"b": [1, 5, 2]}]) as rows: |
| 221 |
self.assertEqual(rows[0]["b"], [1, 5, 2]) |
| 222 |
|
| 223 |
def testIntArray(self): |
| 224 |
with digestedTable(self.conn, "n_a_t", "(b double precision[])", |
| 225 |
[{"b": numpy.array([1.0, 1.5, 2])}]) as rows: |
| 226 |
self.assertEqual(rows[0]["b"], [1.0, 1.5, 2.0]) |
| 227 |
|
| 228 |
def testPyfitsUndefined(self): |
| 229 |
with digestedTable(self.conn, "n_a_t", "(a float, b text)", |
| 230 |
[{"a": pyfits.Undefined(), "b": pyfits.Undefined()}]) as rows: |
| 231 |
self.assertEqual(rows[0]["a"], None) |
| 232 |
self.assertEqual(rows[0]["b"], None) |
| 233 |
|
| 234 |
def testInt4Range(self): |
| 235 |
with digestedTable(self.conn, "n_a_t", "(a int4range)", |
| 236 |
[{"a": base.NumericRange(2, 3)}]) as rows: |
| 237 |
self.assertEqual(rows[0]["a"], base.NumericRange(2, 3)) |
| 238 |
|
| 239 |
def testNaN(self): |
| 240 |
with digestedTable(self.conn, "n_a_t", "(a real)", |
| 241 |
[{"a": float("NaN")}]) as rows: |
| 242 |
self.assertTrue(math.isnan(rows[0]["a"])) |
| 243 |
|
| 244 |
def testTextArray(self): |
| 245 |
with digestedTable(self.conn, "n_a_t", "(a text[])", |
| 246 |
[{"a": ["ein", "walde"]}]) as rows: |
| 247 |
self.assertEqual(rows[0]["a"], ["ein", "walde"]) |
| 248 |
|
| 249 |
def testVarcharsArray(self): |
| 250 |
with digestedTable(self.conn, "n_a_t", "(a varchar[])", |
| 251 |
[{"a": ["ein", "walde"]}]) as rows: |
| 252 |
self.assertEqual(rows[0]["a"], ["ein", "walde"]) |
| 253 |
|
| 254 |
|
| 255 |
class TestWithTableCreation(testhelpers.VerboseTest): |
| 256 |
resources = [("conn", tresc.dbConnection)] |
| 257 |
|
| 258 |
tableName = None |
| 259 |
rdId = "test.rd" |
| 260 |
rows = [] |
| 261 |
|
| 262 |
def _assertPrivileges(self, foundPrivs, expPrivs): |
| 263 |
# profile user might not be mentioned in table acl, so retrofit it |
| 264 |
profileUser = base.getDBProfile("admin").user |
| 265 |
expPrivs[profileUser] = foundPrivs[profileUser] |
| 266 |
self.assertEqual(set(foundPrivs), set(expPrivs)) |
| 267 |
for role in foundPrivs: |
| 268 |
self.assertEqual(foundPrivs[role], expPrivs[role], |
| 269 |
"Privileges for %s don't match: found %s, expected %s"%(role, |
| 270 |
foundPrivs[role], expPrivs[role])) |
| 271 |
|
| 272 |
def setUp(self): |
| 273 |
testhelpers.VerboseTest.setUp(self) |
| 274 |
if self.tableName is None: |
| 275 |
return |
| 276 |
self.querier = base.UnmanagedQuerier(connection=self.conn) |
| 277 |
self.tableDef = testhelpers.getTestTable(self.tableName, self.rdId) |
| 278 |
self.table = rsc.TableForDef(self.tableDef, rows=self.rows, |
| 279 |
connection=self.conn, create=True) |
| 280 |
self.conn.commit() |
| 281 |
|
| 282 |
def tearDown(self): |
| 283 |
if self.tableName is None: |
| 284 |
return |
| 285 |
self.table.drop() |
| 286 |
self.conn.commit() |
| 287 |
|
| 288 |
|
| 289 |
class TestPrivs(TestWithTableCreation): |
| 290 |
"""Tests for privilege management. |
| 291 |
""" |
| 292 |
tableName = "valSpec" |
| 293 |
|
| 294 |
resources = [("conn", tresc.dbConnection)] |
| 295 |
|
| 296 |
@unittest.skip("testadmin only gets READ any more, and it's too remote to investigate right now") |
| 297 |
def testDefaultPrivileges(self): |
| 298 |
self._assertPrivileges( |
| 299 |
self.querier.getTablePrivileges( |
| 300 |
self.tableDef.rd.schema, self.tableDef.id), |
| 301 |
self.querier.getACLFromRes(self.tableDef)) |
| 302 |
|
| 303 |
def testBadTableName(self): |
| 304 |
self.assertRaisesWithMsg(ValueError, |
| 305 |
"'botched/table()name' is not a SQL regular identifier", |
| 306 |
base.UnmanagedQuerier(self.conn).hasIndex, |
| 307 |
("botched/table()name", "quatschindex")) |
| 308 |
|
| 309 |
|
| 310 |
class TestADQLPrivs(TestPrivs): |
| 311 |
"""Tests for privilege management for ADQL-enabled tables. |
| 312 |
""" |
| 313 |
tableName = "adqltable" |
| 314 |
|
| 315 |
|
| 316 |
class TestRoleSetting(TestPrivs): |
| 317 |
tableName = "privtable" |
| 318 |
rdId = "privtest.rd" |
| 319 |
|
| 320 |
def setUp(self): |
| 321 |
# We need a private querier here since we must squeeze those |
| 322 |
# users in before TestPriv's setup |
| 323 |
try: |
| 324 |
with base.getWritableAdminConn() as conn: |
| 325 |
conn.execute("create user privtestuser") |
| 326 |
conn.execute("create user testadmin inherit") |
| 327 |
except base.DBError: # probably left over from a previous crash |
| 328 |
sys.stderr.write("Test roles already present." |
| 329 |
" Hope we'll clear them later.\n") |
| 330 |
|
| 331 |
self.profDir = base.getConfig("configDir") |
| 332 |
with open(os.path.join(self.profDir, "privtest"), "w") as f: |
| 333 |
f.write("include dsn\nuser=privtestuser\n") |
| 334 |
with open(os.path.join(self.profDir, "testadmin"), "w") as f: |
| 335 |
f.write("include dsn\nuser=testadmin\n") |
| 336 |
|
| 337 |
TestPrivs.setUp(self) |
| 338 |
|
| 339 |
def tearDown(self): |
| 340 |
TestPrivs.tearDown(self) |
| 341 |
self.conn.execute("drop schema test cascade") |
| 342 |
self.conn.execute("drop user if exists privtestuser") |
| 343 |
self.conn.execute("drop user if exists testadmin") |
| 344 |
self.conn.commit() |
| 345 |
os.unlink(os.path.join(self.profDir, "privtest")) |
| 346 |
os.unlink(os.path.join(self.profDir, "testadmin")) |
| 347 |
|
| 348 |
|
| 349 |
class AdhocQuerierTest(testhelpers.VerboseTest): |
| 350 |
resources = [("table", tresc.csTestTable), ("conn", tresc.dbConnection)] |
| 351 |
|
| 352 |
def testBasic(self): |
| 353 |
self.assertEqual(1, len(list(self.conn.query( |
| 354 |
"select * from %s limit 1"%self.table.tableDef.getQName())))) |
| 355 |
|
| 356 |
def testAdminQuerier(self): |
| 357 |
with base.getWritableAdminConn() as conn: |
| 358 |
self.assertRuns(conn.execute, |
| 359 |
("create role dont",)) |
| 360 |
self.assertRuns(conn.execute, |
| 361 |
("drop role dont",)) |
| 362 |
|
| 363 |
def testNoAdminQuerier(self): |
| 364 |
with base.getTableConn() as conn: |
| 365 |
self.assertRaises( |
| 366 |
(sqlsupport.ProgrammingError, sqlsupport.InternalError), |
| 367 |
conn.execute, |
| 368 |
"create role dont") |
| 369 |
|
| 370 |
def testNoInjectionOnGetColumns(self): |
| 371 |
q = base.UnmanagedQuerier(self.conn) |
| 372 |
self.assertRaisesWithMsg(ValueError, |
| 373 |
"'foo; drop tables' is not a SQL regular identifier", |
| 374 |
q.getColumnsFromDB, |
| 375 |
("foo; drop tables",)) |
| 376 |
|
| 377 |
def testGetColumns(self): |
| 378 |
with digestedTable(self.conn, "odd_table", |
| 379 |
"(t text, s smallint, i integer, b bigint," |
| 380 |
" r real, d double precision, ar real[], c char," |
| 381 |
" ad double precision[], odd char(20), frotsch bytea[30]," |
| 382 |
" fro bytea, ts timestamp, dt date, ti time," |
| 383 |
" boo boolean)", []): |
| 384 |
q = base.UnmanagedQuerier(self.conn) |
| 385 |
self.assertEqual(q.getColumnsFromDB("odd_table"), [ |
| 386 |
('t', 'text'), ('s', 'int2'), ('i', 'int4'), |
| 387 |
('b', 'int8'), ('r', 'float4'), ('d', 'float8'), |
| 388 |
('ar', '_float4'), ('c', 'bpchar'), ('ad', '_float8'), |
| 389 |
('odd', 'bpchar'), ('frotsch', '_bytea'), ('fro', 'bytea'), |
| 390 |
('ts', 'timestamp'), ('dt', 'date'), ('ti', 'time'), |
| 391 |
('boo', 'bool')]) |
| 392 |
|
| 393 |
def testRowEstimateGood(self): |
| 394 |
estimate = base.UnmanagedQuerier(self.conn |
| 395 |
).getRowEstimate("tap_schema.tables") |
| 396 |
self.assertTrue(isinstance(estimate, int)) |
| 397 |
self.assertTrue(0<=estimate<=200) |
| 398 |
|
| 399 |
def testRowEstimateBad(self): |
| 400 |
self.assertRaisesWithMsg(base.DBError, |
| 401 |
utils.EqualingRE('relation "tap_schema.goneaway" does not exist\n.*'), |
| 402 |
base.UnmanagedQuerier(self.conn).getRowEstimate, |
| 403 |
("tap_schema.goneaway",)) |
| 404 |
|
| 405 |
def testOIDGood(self): |
| 406 |
oid = base.UnmanagedQuerier(self.conn).getOIDForTable("tap_schema.tables") |
| 407 |
self.assertTrue(isinstance(oid, int)) |
| 408 |
self.assertTrue(1000<oid) |
| 409 |
|
| 410 |
def testOIDBad(self): |
| 411 |
self.assertRaisesWithMsg(base.DBError, |
| 412 |
utils.EqualingRE('relation "xanadu.goneaway" does not exist.*'), |
| 413 |
base.UnmanagedQuerier(self.conn).getOIDForTable, |
| 414 |
("xanadu.goneaway",)) |
| 415 |
|
| 416 |
def testPrivsForNonExisting(self): |
| 417 |
self.assertEqual( |
| 418 |
base.UnmanagedQuerier(self.conn |
| 419 |
).getTablePrivileges("xanadu", "goneaway"), |
| 420 |
{}) |
| 421 |
|
| 422 |
|
| 423 |
class DBOpsTest(testhelpers.VerboseTest): |
| 424 |
resources = [("conn", tresc.dbConnection)] |
| 425 |
|
| 426 |
def testDroppingMissing(self): |
| 427 |
self.assertEqual( |
| 428 |
base.UnmanagedQuerier(self.conn).dropTable("xanadu.goneaway"), |
| 429 |
None) |
| 430 |
|
| 431 |
|
| 432 |
class TestMetaTable(TestWithTableCreation): |
| 433 |
tableName = "typesTable" |
| 434 |
|
| 435 |
def testDcTablesEntry(self): |
| 436 |
with base.getTableConn() as conn: |
| 437 |
res = list(conn.query("select * from dc.tablemeta where tableName=%(n)s", |
| 438 |
{"n": self.tableDef.getQName()})) |
| 439 |
qName, srcRd, td, rd, adql, nrows = res[0] |
| 440 |
self.assertEqual(qName, 'test.typesTable') |
| 441 |
self.assertEqual(srcRd.split("/")[-1], 'test') |
| 442 |
self.assertEqual(adql, True) |
| 443 |
|
| 444 |
|
| 445 |
class TestMetaTableADQL(TestWithTableCreation): |
| 446 |
tableName = "adqltable" |
| 447 |
|
| 448 |
def testDcTablesEntry(self): |
| 449 |
res = list(self.conn.query( |
| 450 |
"select * from dc.tablemeta where tableName=%(n)s", |
| 451 |
{"n": self.tableDef.getQName()})) |
| 452 |
qName, srcRd, td, rd, adql, nrows = res[0] |
| 453 |
self.assertEqual(qName, 'test.adqltable') |
| 454 |
self.assertEqual(srcRd.split("/")[-1], 'test') |
| 455 |
self.assertEqual(adql, True) |
| 456 |
|
| 457 |
|
| 458 |
class TestWithDataImport(testhelpers.VerboseTest): |
| 459 |
"""base class for tests importing data up front. |
| 460 |
|
| 461 |
You need to set the ddId, which must point into test.rd |
| 462 |
""" |
| 463 |
resources = [("connection", tresc.dbConnection)] |
| 464 |
|
| 465 |
def setUp(self): |
| 466 |
testhelpers.VerboseTest.setUp(self) |
| 467 |
dd = testhelpers.getTestRD().getById(self.ddId) |
| 468 |
self.data = rsc.makeData(dd, connection=self.connection) |
| 469 |
|
| 470 |
|
| 471 |
class TestPreIndexSQLRunning(TestWithDataImport): |
| 472 |
"""tests for dbtables running preIndexSQL scripts. |
| 473 |
""" |
| 474 |
ddId = "import_sqlscript" |
| 475 |
|
| 476 |
def testScriptRan(self): |
| 477 |
ct = list(self.connection.query( |
| 478 |
"select count(*) from test.sqlscript"))[0][0] |
| 479 |
self.assertEqual(ct, 3) |
| 480 |
|
| 481 |
|
| 482 |
class TestPreIndexPythonRunning(TestWithDataImport): |
| 483 |
"""tests for dbtables running preIndexSQL scripts. |
| 484 |
""" |
| 485 |
ddId = "import_pythonscript" |
| 486 |
|
| 487 |
def testScriptRan(self): |
| 488 |
ct = list(self.connection.query("select * from test.pythonscript"))[0][0] |
| 489 |
self.assertEqual(ct, 123) |
| 490 |
|
| 491 |
|
| 492 |
class TestQueryExpands(TestWithTableCreation): |
| 493 |
"""tests for expansion of macros in dbtable's query. |
| 494 |
""" |
| 495 |
tableName = "adqltable" |
| 496 |
|
| 497 |
def testExpandedQuery(self): |
| 498 |
self.table.connection.execute( |
| 499 |
self.table.expand( |
| 500 |
r"insert into \qName (\colNames) values (-133.0)")) |
| 501 |
self.assertEqual( |
| 502 |
len(list(self.table.iterQuery([self.tableDef.getColumnByName("foo")], |
| 503 |
"foo=-133.0"))), |
| 504 |
1) |
| 505 |
|
| 506 |
def testBadMacroRaises(self): |
| 507 |
self.assertRaises(base.MacroError, self.table.expand, r"\monkmacrobad") |
| 508 |
|
| 509 |
|
| 510 |
class NewlyCreatedTest(testhelpers.VerboseTest): |
| 511 |
resources = [("connection", tresc.dbConnection)] |
| 512 |
|
| 513 |
def testNewlyCreated(self): |
| 514 |
rd = base.parseFromString(rscdesc.RD, |
| 515 |
'<resource schema="test"><table id="newly_created" onDisk="true"/>' |
| 516 |
'</resource>') |
| 517 |
rd.sourceId = "nct" |
| 518 |
td = rd.getById("newly_created") |
| 519 |
rsc.TableForDef(td, create=False, connection=self.connection).drop() |
| 520 |
self.connection.commit() |
| 521 |
|
| 522 |
try: |
| 523 |
t = rsc.TableForDef(td, create=True, connection=self.connection) |
| 524 |
self.assertEqual(t.newlyCreated, True) |
| 525 |
t = rsc.TableForDef(td, create=True, connection=self.connection) |
| 526 |
self.assertEqual(t.newlyCreated, False) |
| 527 |
finally: |
| 528 |
self.connection.rollback() |
| 529 |
|
| 530 |
|
| 531 |
class StatisticsTargetTest(testhelpers.VerboseTest): |
| 532 |
resources = [("connection", tresc.dbConnection)] |
| 533 |
|
| 534 |
def testSetStatTarget(self): |
| 535 |
rd = base.parseFromString(rscdesc.RD, |
| 536 |
"""<resource schema="test"><table id="statatest" onDisk="True"> |
| 537 |
<column name="quoted/x X"><property name="statisticsTarget">4</property> |
| 538 |
</column></table> |
| 539 |
<data id="import"><sources item="500"/><embeddedGrammar><iterator> |
| 540 |
<code> |
| 541 |
for i in range(int(self.sourceToken)):yield {"x": i} |
| 542 |
</code></iterator></embeddedGrammar> |
| 543 |
<make table="statatest"> |
| 544 |
<rowmaker><apply><code>result["x X"]=@x</code></apply></rowmaker> |
| 545 |
</make></data></resource>""") |
| 546 |
rd.sourceId = "internal" |
| 547 |
_ = rsc.makeData(rd.getById("import"), |
| 548 |
connection=self.connection) |
| 549 |
|
| 550 |
stats = list( |
| 551 |
self.connection.query("SELECT histogram_bounds from pg_stats" |
| 552 |
" WHERE tablename='statatest' and attname='x X'")) |
| 553 |
# The array isn't parsed right now, so I'm counting commas in the |
| 554 |
# literal. If it *is* parsed and you get an array here: Great! |
| 555 |
self.assertTrue(len(stats[0][0].split(","))<10, |
| 556 |
"Postgres made many more histogram bins than our statistics target") |
| 557 |
|
| 558 |
|
| 559 |
class TestIgnoreFrom(testhelpers.VerboseTest): |
| 560 |
resources = [("connection", tresc.dbConnection)] |
| 561 |
|
| 562 |
def testWorksWithoutTable(self): |
| 563 |
rsc.TableForDef(testhelpers.getTestRD().getById("prodtest"), |
| 564 |
connection=self.connection, create=False).drop() |
| 565 |
self.data = rsc.makeData( |
| 566 |
testhelpers.getTestRD().getById("productimport"), |
| 567 |
rsc.getParseOptions(keepGoing=True), |
| 568 |
connection=self.connection) |
| 569 |
self.assertEqual( |
| 570 |
set(self.connection.query("select object from test.prodtest")), |
| 571 |
set([('gabriel',), ('michael',)])) |
| 572 |
|
| 573 |
def testWorksWithTable(self): |
| 574 |
dd = testhelpers.getTestRD().getById("productimport") |
| 575 |
|
| 576 |
data1 = rsc.makeData(dd, |
| 577 |
rsc.getParseOptions(keepGoing=True), |
| 578 |
connection=self.connection) |
| 579 |
self.assertEqual(data1.nAffected, 2) |
| 580 |
|
| 581 |
modDD = dd.change(updating=True) |
| 582 |
|
| 583 |
data2 = rsc.makeData(modDD, |
| 584 |
rsc.getParseOptions(keepGoing=True), |
| 585 |
connection=self.connection) |
| 586 |
self.assertEqual(data2.nAffected, 0) |
| 587 |
|
| 588 |
|
| 589 |
class InformationSchemaTest(testhelpers.VerboseTest): |
| 590 |
resources = [("connection", tresc.dbConnection)] |
| 591 |
|
| 592 |
def testNoTableType(self): |
| 593 |
q = sqlsupport.UnmanagedQuerier(self.connection) |
| 594 |
self.assertEqual(q.getTableType("thereareno.monsters"), |
| 595 |
None) |
| 596 |
|
| 597 |
def _assertProperlyManaged(self, |
| 598 |
creationStatement, |
| 599 |
tableName, |
| 600 |
tableType): |
| 601 |
q = sqlsupport.UnmanagedQuerier(self.connection) |
| 602 |
# if things go seriously wrong in one of these tests, you may |
| 603 |
# have to manually remove the relations created here. |
| 604 |
self.connection.execute(creationStatement) |
| 605 |
try: |
| 606 |
self.assertEqual(q.getTableType(tableName), tableType) |
| 607 |
finally: |
| 608 |
q.dropTable(tableName) |
| 609 |
self.assertEqual(q.getTableType(tableName), None) |
| 610 |
|
| 611 |
def testTempTableManagement(self): |
| 612 |
self._assertProperlyManaged( |
| 613 |
"CREATE TEMP TABLE klutz (an INTEGER)", |
| 614 |
"klutz", |
| 615 |
"LOCAL TEMPORARY") |
| 616 |
|
| 617 |
def testNormalTableManagement(self): |
| 618 |
self._assertProperlyManaged( |
| 619 |
"CREATE TABLE tap_schema.klutz (an INTEGER)", |
| 620 |
"tap_schema.klutz", |
| 621 |
"BASE TABLE") |
| 622 |
|
| 623 |
def testPublicTableManagement(self): |
| 624 |
self._assertProperlyManaged( |
| 625 |
"CREATE TABLE klutz (an INTEGER)", |
| 626 |
"klutz", |
| 627 |
"BASE TABLE") |
| 628 |
|
| 629 |
def testViewManagement(self): |
| 630 |
self._assertProperlyManaged( |
| 631 |
"CREATE VIEW klutz AS (SELECT 1 as an)", |
| 632 |
"klutz", |
| 633 |
"VIEW") |
| 634 |
|
| 635 |
def testMaterializedViewManagement(self): |
| 636 |
self._assertProperlyManaged( |
| 637 |
"CREATE MATERIALIZED VIEW IF NOT EXISTS klutz AS (SELECT 1 as an)", |
| 638 |
"klutz", |
| 639 |
"MATERIALIZED VIEW") |
| 640 |
|
| 641 |
def testSchemaExists(self): |
| 642 |
querier = base.UnmanagedQuerier(self.connection) |
| 643 |
self.assertTrue(querier.schemaExists("TaP_ScHeMa")) |
| 644 |
|
| 645 |
|
| 646 |
class DerivedViewsDroppingTest(testhelpers.VerboseTest): |
| 647 |
resources = [("conn", tresc.dbConnection)] |
| 648 |
|
| 649 |
def testViewScriptRunning(self): |
| 650 |
with testhelpers.testFile("viewdropping.rd", |
| 651 |
inDir=base.getConfig("inputsDir"), |
| 652 |
content=r"""<resource schema="test"> |
| 653 |
<table id="to_derive" onDisk="True"> |
| 654 |
<column name="dist"/> |
| 655 |
</table> |
| 656 |
<table id="is_derived" onDisk="True"> |
| 657 |
<column original="to_derive.dist"/> |
| 658 |
<viewStatement> |
| 659 |
CREATE VIEW \qName AS (SELECT \colNames from \schema.to_derive) |
| 660 |
</viewStatement> |
| 661 |
<script type="beforeDrop" lang="python"> |
| 662 |
table.tableDef.rd.properlyDropped = True |
| 663 |
</script> |
| 664 |
</table> |
| 665 |
<data id="import"> |
| 666 |
<make table="to_derive"/> |
| 667 |
<make table="is_derived"/> |
| 668 |
</data> |
| 669 |
</resource>"""): |
| 670 |
rd = base.caches.getRD("viewdropping") |
| 671 |
data = rsc.makeData(rd.getById("import"), connection=self.conn) |
| 672 |
data.tables["to_derive"].drop() |
| 673 |
self.assertTrue(hasattr(rd, "properlyDropped"), |
| 674 |
"Derived view's todrop script hasn't run") |
| 675 |
|
| 676 |
|
| 677 |
class NonblockingQueryTest(testhelpers.VerboseTest): |
| 678 |
resources = [("conn", tresc.dbConnection)] |
| 679 |
|
| 680 |
def testRunning(self): |
| 681 |
q = sqlsupport.NonBlockingQuery(self.conn, "select" |
| 682 |
" table_name from TAP_SCHEMA.tables where table_name like %(nt)s" |
| 683 |
" order by table_name limit 1", |
| 684 |
{"nt": "tap_schema.%"}) |
| 685 |
with q: |
| 686 |
for i in range(100): |
| 687 |
if q.getResult() is not None: |
| 688 |
break |
| 689 |
time.sleep(0.01) |
| 690 |
else: |
| 691 |
raise AssertionError("Nonblocking query does not finish") |
| 692 |
|
| 693 |
self.assertEqual(q.getResult(), [('tap_schema.columns',)]) |
| 694 |
self.assertFalse(q.thread.is_alive()) |
| 695 |
|
| 696 |
def testFailing(self): |
| 697 |
q = sqlsupport.NonBlockingQuery(self.conn, "select * from junk") |
| 698 |
try: |
| 699 |
with q: |
| 700 |
while q.getResult() is None: |
| 701 |
time.sleep(0.01) |
| 702 |
except Exception as ex: |
| 703 |
self.assertEqual( |
| 704 |
ex.pgerror[:38], |
| 705 |
'ERROR: relation "junk" does not exist') |
| 706 |
else: |
| 707 |
raise AssertionError("No exception seen for failing query.") |
| 708 |
|
| 709 |
self.assertFalse(q.thread.is_alive()) |
| 710 |
|
| 711 |
def testAborting(self): |
| 712 |
q = sqlsupport.NonBlockingQuery(self.conn, |
| 713 |
"select (select avg(asin(sqrt(x)/224.0)) from generate_series(1, whomp) as x) as q from generate_series(1, 50000) as whomp") |
| 714 |
with q: |
| 715 |
q.abort() |
| 716 |
self.assertFalse(q.thread.is_alive()) |
| 717 |
|
| 718 |
def testNoResults(self): |
| 719 |
with sqlsupport.NonBlockingQuery(self.conn, |
| 720 |
"CREATE TEMP TABLE goner (ind integer)", |
| 721 |
fetchResults=False) as query: |
| 722 |
while query.getResult() is None: |
| 723 |
time.sleep(0.01) |
| 724 |
self.assertEqual(query.getResult(), []) |
| 725 |
|
| 726 |
|
| 727 |
class DBMetaTest(testhelpers.VerboseTest): |
| 728 |
def testVersionCurrent(self): |
| 729 |
from gavo.user import upgrade |
| 730 |
self.assertEqual( |
| 731 |
int(base.getDBMeta("schemaversion")), |
| 732 |
upgrade.CURRENT_SCHEMAVERSION) |
| 733 |
|
| 734 |
def testBadGetting(self): |
| 735 |
self.assertRaisesWithMsg( |
| 736 |
KeyError, |
| 737 |
"'xanadu'", |
| 738 |
base.getDBMeta, |
| 739 |
("xanadu",)) |
| 740 |
|
| 741 |
|
| 742 |
class GeometryCastTests(testhelpers.VerboseTest): |
| 743 |
# since what's tested here is defined in //adql, this should perhaps go to |
| 744 |
# adqltest? Perhaps we should pull all geometry-related ADQL testing into |
| 745 |
# a test suite of its own? |
| 746 |
resources = [("conn", tresc.dbConnection)] |
| 747 |
|
| 748 |
def testGoodPointCast(self): |
| 749 |
res = list(self.conn.query("select cast_to_point('270 45')"))[0][0] |
| 750 |
lon, lat = res.asDALI() |
| 751 |
self.assertAlmostEqual(lon, 270) |
| 752 |
self.assertAlmostEqual(lat, 45) |
| 753 |
|
| 754 |
def testWrongPointCard(self): |
| 755 |
self.assertRaisesWithMsg(base.DBError, |
| 756 |
"Not a DALI POINT literal: 270 45 23\nCONTEXT: PL/pgSQL function cast_to_point(text) line 8 at RAISE\n", |
| 757 |
list, |
| 758 |
(self.conn.query("select cast_to_point('270 45 23')"),)) |
| 759 |
|
| 760 |
def testWrongPointNumberSyntax(self): |
| 761 |
self.assertRaisesWithMsg(base.DBError, |
| 762 |
"invalid input syntax for type double precision: \"abc\"\nCONTEXT: PL/pgSQL function cast_to_point(text) line 10 at RETURN\n", |
| 763 |
list, |
| 764 |
(self.conn.query("select cast_to_point('abc def')"),)) |
| 765 |
|
| 766 |
def testGoodCircleCast(self): |
| 767 |
res = list(self.conn.query("select cast_to_circle('110.3 -3e-2 3e-6')" |
| 768 |
))[0][0] |
| 769 |
lon, lat, radius = res.asDALI() |
| 770 |
self.assertAlmostEqual(lon, 110.3) |
| 771 |
self.assertAlmostEqual(lat, -3e-2) |
| 772 |
self.assertAlmostEqual(radius, 3e-6) |
| 773 |
|
| 774 |
def testWrongCircleCard(self): |
| 775 |
self.assertRaisesWithMsg(base.DBError, |
| 776 |
"Not a DALI CIRCLE literal: 270 45\nCONTEXT: PL/pgSQL function cast_to_circle(text) line 8 at RAISE\n", |
| 777 |
list, |
| 778 |
(self.conn.query("select cast_to_circle('270 45')"),)) |
| 779 |
|
| 780 |
def testGoodPolyCast(self): |
| 781 |
res = list(self.conn.query( |
| 782 |
"select cast_to_polygon('270 45 271 45 270.5 44')" |
| 783 |
))[0][0] |
| 784 |
coos = res.asDALI() |
| 785 |
self.assertAlmostEqual(coos[4], 270.5) |
| 786 |
self.assertAlmostEqual(coos[5], 44) |
| 787 |
|
| 788 |
coverage = res.asSMoc(7).asASCII() |
| 789 |
# in case the following assertion changes, it's all possible |
| 790 |
# there's a better healpix library to praise... |
| 791 |
self.assertEqual(coverage, "7/60095 60138 7/") |
| 792 |
|
| 793 |
def testWrongPolyCard(self): |
| 794 |
self.assertRaisesWithMsg(base.DBError, |
| 795 |
"Not a DALI POLYGON literal: 270 45 271 45 270.5 44 28\nCONTEXT: PL/pgSQL function cast_to_polygon(text) line 14 at RAISE\n", |
| 796 |
list, |
| 797 |
(self.conn.query("select cast_to_polygon('270 45 271 45 270.5 44 28')"),)) |
| 798 |
|
| 799 |
|
| 800 |
if __name__=="__main__": |
| 801 |
testhelpers.main(AdhocQuerierTest) |