""" Some tests for the database interface and the surrounding helper code. """ #c Copyright 2008-2025, the GAVO project #c #c This program is free software, covered by the GNU GPL. See the #c COPYING file in the source distribution. import contextlib import math import os import sys import time import unittest import numpy from gavo.helpers import testhelpers from gavo import base from gavo import rsc from gavo import rscdesc from gavo import svcs from gavo import utils from gavo.base import config from gavo.base import sqlsupport from gavo.utils import pyfits import tresc class GetSQLTest(testhelpers.VerboseTest): # this is for "dumb" fields. See also viziertest and pqltest for advanced # SQL generation from stuff coming in from the web. def _assertSQLGenerated(self, ikArgs, inputPars, fragment, sqlPars): foundPars = {} inputKey = base.makeStruct(svcs.InputKey, **ikArgs) foundFragment = base.getSQLForField(inputKey, inputPars, foundPars) self.assertEqual(fragment, foundFragment) self.assertEqual(sqlPars, foundPars) def testSimpleString(self): self._assertSQLGenerated( {"name": "foo", "type": "text"}, {"foo": ["';"]}, 'foo=%(foo0)s', {'foo0': "';"}) def testEmptyString(self): self._assertSQLGenerated( {"name": "foo", "type": "text"}, {"foo": [""]}, 'foo=%(foo0)s', {'foo0': ""}) def testMissingString(self): self._assertSQLGenerated( {"name": "foo", "type": "text"}, {}, None, {}) def testIntSeq(self): self._assertSQLGenerated( {"name": "foo", "type": "integer"}, {"foo": list(map(int, "1 2 3 4".split()))}, 'foo IN %(foo0)s', {'foo0': set([1,2,3,4])}) class ProfileTest(testhelpers.VerboseTest): parser = config.ProfileParser(["data"]) def testEmptyProfile(self): nullProfile = self.parser.parse("test1", None, "") self.assertRaisesWithMsg(base.StructureError, "Insufficient information to connect to the database in profile 'test1'.", base.getDBConnection, (nullProfile,)) def testInvalidProfile(self): self.assertRaisesWithMsg(config.ProfileParseError, "\"internal\", line 3: unknown setting 'hsot'", self.parser.parse, ("test2", "internal", "database=gavo\nhsot=bar\n")) def testWhitespace(self): profile = self.parser.parse("foo", None, stream=""" user = honk password="secre t " """) self.assertEqual(profile.user, "honk") self.assertEqual(profile.password, "secre t ") def testUnknownProfile(self): self.assertRaisesWithMsg( config.ProfileParseError, "Requested db profile 'nonexisting' does not exist", base.getDBProfile, ("nonexisting",)) class ConnectionsTest(testhelpers.VerboseTest): resources = [("conn", tresc.dbConnection)] def testServerVersion(self): version = base.getPgVersion() self.assertTrue(isinstance(version, tuple)) self.assertTrue(8<=version[0]<=40) # let's see if DaCHS lives that long self.assertTrue(0' '') rd.sourceId = "nct" td = rd.getById("newly_created") rsc.TableForDef(td, create=False, connection=self.connection).drop() self.connection.commit() try: t = rsc.TableForDef(td, create=True, connection=self.connection) self.assertEqual(t.newlyCreated, True) t = rsc.TableForDef(td, create=True, connection=self.connection) self.assertEqual(t.newlyCreated, False) finally: self.connection.rollback() class StatisticsTargetTest(testhelpers.VerboseTest): resources = [("connection", tresc.dbConnection)] def testSetStatTarget(self): rd = base.parseFromString(rscdesc.RD, """
4
for i in range(int(self.sourceToken)):yield {"x": i} result["x X"]=@x """) rd.sourceId = "internal" _ = rsc.makeData(rd.getById("import"), connection=self.connection) stats = list( self.connection.query("SELECT histogram_bounds from pg_stats" " WHERE tablename='statatest' and attname='x X'")) # The array isn't parsed right now, so I'm counting commas in the # literal. If it *is* parsed and you get an array here: Great! self.assertTrue(len(stats[0][0].split(","))<10, "Postgres made many more histogram bins than our statistics target") class TestIgnoreFrom(testhelpers.VerboseTest): resources = [("connection", tresc.dbConnection)] def testWorksWithoutTable(self): rsc.TableForDef(testhelpers.getTestRD().getById("prodtest"), connection=self.connection, create=False).drop() self.data = rsc.makeData( testhelpers.getTestRD().getById("productimport"), rsc.getParseOptions(keepGoing=True), connection=self.connection) self.assertEqual( set(self.connection.query("select object from test.prodtest")), set([('gabriel',), ('michael',)])) def testWorksWithTable(self): dd = testhelpers.getTestRD().getById("productimport") data1 = rsc.makeData(dd, rsc.getParseOptions(keepGoing=True), connection=self.connection) self.assertEqual(data1.nAffected, 2) modDD = dd.change(updating=True) data2 = rsc.makeData(modDD, rsc.getParseOptions(keepGoing=True), connection=self.connection) self.assertEqual(data2.nAffected, 0) class InformationSchemaTest(testhelpers.VerboseTest): resources = [("connection", tresc.dbConnection)] def testNoTableType(self): q = sqlsupport.UnmanagedQuerier(self.connection) self.assertEqual(q.getTableType("thereareno.monsters"), None) def _assertProperlyManaged(self, creationStatement, tableName, tableType): q = sqlsupport.UnmanagedQuerier(self.connection) # if things go seriously wrong in one of these tests, you may # have to manually remove the relations created here. self.connection.execute(creationStatement) try: self.assertEqual(q.getTableType(tableName), tableType) finally: q.dropTable(tableName) self.assertEqual(q.getTableType(tableName), None) def testTempTableManagement(self): self._assertProperlyManaged( "CREATE TEMP TABLE klutz (an INTEGER)", "klutz", "LOCAL TEMPORARY") def testNormalTableManagement(self): self._assertProperlyManaged( "CREATE TABLE tap_schema.klutz (an INTEGER)", "tap_schema.klutz", "BASE TABLE") def testPublicTableManagement(self): self._assertProperlyManaged( "CREATE TABLE klutz (an INTEGER)", "klutz", "BASE TABLE") def testViewManagement(self): self._assertProperlyManaged( "CREATE VIEW klutz AS (SELECT 1 as an)", "klutz", "VIEW") def testMaterializedViewManagement(self): self._assertProperlyManaged( "CREATE MATERIALIZED VIEW IF NOT EXISTS klutz AS (SELECT 1 as an)", "klutz", "MATERIALIZED VIEW") def testSchemaExists(self): querier = base.UnmanagedQuerier(self.connection) self.assertTrue(querier.schemaExists("TaP_ScHeMa")) class DerivedViewsDroppingTest(testhelpers.VerboseTest): resources = [("conn", tresc.dbConnection)] def testViewScriptRunning(self): with testhelpers.testFile("viewdropping.rd", inDir=base.getConfig("inputsDir"), content=r"""
CREATE VIEW \qName AS (SELECT \colNames from \schema.to_derive)
"""): rd = base.caches.getRD("viewdropping") data = rsc.makeData(rd.getById("import"), connection=self.conn) data.tables["to_derive"].drop() self.assertTrue(hasattr(rd, "properlyDropped"), "Derived view's todrop script hasn't run") class NonblockingQueryTest(testhelpers.VerboseTest): resources = [("conn", tresc.dbConnection)] def testRunning(self): q = sqlsupport.NonBlockingQuery(self.conn, "select" " table_name from TAP_SCHEMA.tables where table_name like %(nt)s" " order by table_name limit 1", {"nt": "tap_schema.%"}) with q: for i in range(100): if q.getResult() is not None: break time.sleep(0.01) else: raise AssertionError("Nonblocking query does not finish") self.assertEqual(q.getResult(), [('tap_schema.columns',)]) self.assertFalse(q.thread.is_alive()) def testFailing(self): q = sqlsupport.NonBlockingQuery(self.conn, "select * from junk") try: with q: while q.getResult() is None: time.sleep(0.01) except Exception as ex: self.assertEqual( ex.pgerror[:38], 'ERROR: relation "junk" does not exist') else: raise AssertionError("No exception seen for failing query.") self.assertFalse(q.thread.is_alive()) def testAborting(self): q = sqlsupport.NonBlockingQuery(self.conn, "select (select avg(asin(sqrt(x)/224.0)) from generate_series(1, whomp) as x) as q from generate_series(1, 50000) as whomp") with q: q.abort() self.assertFalse(q.thread.is_alive()) def testNoResults(self): with sqlsupport.NonBlockingQuery(self.conn, "CREATE TEMP TABLE goner (ind integer)", fetchResults=False) as query: while query.getResult() is None: time.sleep(0.01) self.assertEqual(query.getResult(), []) class DBMetaTest(testhelpers.VerboseTest): def testVersionCurrent(self): from gavo.user import upgrade self.assertEqual( int(base.getDBMeta("schemaversion")), upgrade.CURRENT_SCHEMAVERSION) def testBadGetting(self): self.assertRaisesWithMsg( KeyError, "'xanadu'", base.getDBMeta, ("xanadu",)) class GeometryCastTests(testhelpers.VerboseTest): # since what's tested here is defined in //adql, this should perhaps go to # adqltest? Perhaps we should pull all geometry-related ADQL testing into # a test suite of its own? resources = [("conn", tresc.dbConnection)] def testGoodPointCast(self): res = list(self.conn.query("select cast_to_point('270 45')"))[0][0] lon, lat = res.asDALI() self.assertAlmostEqual(lon, 270) self.assertAlmostEqual(lat, 45) def testWrongPointCard(self): self.assertRaisesWithMsg(base.DBError, "Not a DALI POINT literal: 270 45 23\nCONTEXT: PL/pgSQL function cast_to_point(text) line 8 at RAISE\n", list, (self.conn.query("select cast_to_point('270 45 23')"),)) def testWrongPointNumberSyntax(self): self.assertRaisesWithMsg(base.DBError, "invalid input syntax for type double precision: \"abc\"\nCONTEXT: PL/pgSQL function cast_to_point(text) line 10 at RETURN\n", list, (self.conn.query("select cast_to_point('abc def')"),)) def testGoodCircleCast(self): res = list(self.conn.query("select cast_to_circle('110.3 -3e-2 3e-6')" ))[0][0] lon, lat, radius = res.asDALI() self.assertAlmostEqual(lon, 110.3) self.assertAlmostEqual(lat, -3e-2) self.assertAlmostEqual(radius, 3e-6) def testWrongCircleCard(self): self.assertRaisesWithMsg(base.DBError, "Not a DALI CIRCLE literal: 270 45\nCONTEXT: PL/pgSQL function cast_to_circle(text) line 8 at RAISE\n", list, (self.conn.query("select cast_to_circle('270 45')"),)) def testGoodPolyCast(self): res = list(self.conn.query( "select cast_to_polygon('270 45 271 45 270.5 44')" ))[0][0] coos = res.asDALI() self.assertAlmostEqual(coos[4], 270.5) self.assertAlmostEqual(coos[5], 44) coverage = res.asSMoc(7).asASCII() # in case the following assertion changes, it's all possible # there's a better healpix library to praise... self.assertEqual(coverage, "7/60095 60138 7/") def testWrongPolyCard(self): self.assertRaisesWithMsg(base.DBError, "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", list, (self.conn.query("select cast_to_polygon('270 45 271 45 270.5 44 28')"),)) if __name__=="__main__": testhelpers.main(AdhocQuerierTest)